JSTQL-JS-Transform/src/parser/parse.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

import * as babelparser from "@babel/parser";
2023-12-11 18:38:30 +00:00
import * as t from "@babel/types";
2023-12-11 18:38:30 +00:00
export interface InternalDSLVariable {
[internals: string]: string[];
2023-12-11 18:38:30 +00:00
}
export interface InternalParseResult {
prelude: InternalDSLVariable;
cleanedJS: string;
2023-12-11 18:38:30 +00:00
}
export function parseInternal(code: string): InternalParseResult {
let cleanedJS = "";
let temp = "";
let flag = false;
let prelude: InternalDSLVariable = {};
2023-12-11 18:38:30 +00:00
for (let i = 0; i < code.length; i++) {
if (code[i] === "<" && code[i + 1] === "<") {
// From now in we are inside of the DSL custom block
flag = true;
i += 1;
continue;
}
2023-12-11 18:38:30 +00:00
if (flag && code[i] === ">" && code[i + 1] === ">") {
// We encountered a closing tag
flag = false;
let { identifier, types } = parseInternalString(temp);
2023-12-11 18:38:30 +00:00
cleanedJS += identifier;
2023-12-11 18:38:30 +00:00
prelude[identifier] = types;
i += 1;
temp = "";
continue;
2023-12-11 18:38:30 +00:00
}
if (flag) {
temp += code[i];
} else {
cleanedJS += code[i];
}
2023-12-11 18:38:30 +00:00
}
return { prelude, cleanedJS };
}
function parseInternalString(dslString: string): {
identifier: string;
types: string[];
} {
let [identifier, typeString, ..._] = dslString
.replace(/\s/g, "")
.split(":");
if (_.length > 0) {
// This is an error, and it means we probably have encountered two bitshift operators
throw new Error("Probably encountered bitshift");
}
return {
identifier,
2024-05-12 18:06:37 +00:00
types: typeString ? typeString.split("|") : [""],
};
}
2023-12-11 18:38:30 +00:00
export function parse_with_plugins(
code: string
): babelparser.ParseResult<t.File> {
return babelparser.parse(code, {
plugins: [["pipelineOperator", { proposal: "hack", topicToken: "%" }]],
});
2023-12-11 18:38:30 +00:00
}