Skip to content

Commit

Permalink
implemented define
Browse files Browse the repository at this point in the history
  • Loading branch information
Glowman554 committed Oct 16, 2023
1 parent 5c1879f commit 28a5ff4
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ async function main() {
let code = Deno.readTextFileSync(input);
const preprocessor = new Preprocessor(includes);
code = preprocessor.preprocess(code);
// Deno.writeTextFileSync(output + ".pp", code);
const lexer = new Lexer(code);
const tokens = lexer.tokenize();
Deno.writeTextFileSync(output + ".tokens.json", JSON.stringify(tokens, undefined, 4));
Expand Down
46 changes: 44 additions & 2 deletions src/preprocessor.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
interface Define {
name: string;
value: string;
}

export class Preprocessor {
include_paths: string[];
included_files: string[];
Expand All @@ -15,7 +20,8 @@ export class Preprocessor {
}
}

preprocess(code: string): string {

preprocessIncludes(code: string): string {
const matches = code.match(/\$include ?<[\w/\.]*.\w*>/g);
if (matches) {
for (let i = 0; i < matches.length; i++) {
Expand All @@ -38,10 +44,46 @@ export class Preprocessor {

if (!this.included_files.includes(inc)) {
this.included_files.push(inc);
code += "\n" + this.preprocess(ncode);
code += "\n" + this.preprocessIncludes(ncode);
}
}
}
return code;
}

preprocessDefines(code: string): string {
const matches = code.match(/\$define ([^ ]*) (.*)/g);

const defines: Define[] = [];

if (matches) {
for (let i = 0; i < matches.length; i++) {
code = code.replace(matches[i], "");

const defineSplit = matches[i].split(" ");
defineSplit.shift();

const defineName = defineSplit.shift() as string;
const defineValue = defineSplit.join(" ");

defines.push({
name: defineName,
value: defineValue
});
}
}

for (const define of defines) {
code = code.replaceAll(define.name, define.value);
}

return code;
}


preprocess(code: string): string {
code = this.preprocessIncludes(code);
code = this.preprocessDefines(code);
return code;
}
}
12 changes: 12 additions & 0 deletions tests/defines.fl
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
$include <std.fl>

$define STRING_TEST "Hello world!"
$define INT_TEST 1234
$define OTHER_TEST printi

function spark(int argc, str[] argv) -> int {
prints(STRING_TEST);
printi(INT_TEST);
OTHER_TEST(INT_TEST);
return 0;
}
5 changes: 5 additions & 0 deletions tests/defines.fl.expect
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"arguments": [],
"output": ["Hello world!", "1234", "1234"],
"should_fail": false
}

0 comments on commit 28a5ff4

Please sign in to comment.