95 lines
2.8 KiB
TypeScript
95 lines
2.8 KiB
TypeScript
//type ParserError = UnclosedQuoteError;
|
|
|
|
interface UnclosedQuoteError {
|
|
type: "UnclosedQuote";
|
|
message: string;
|
|
timestamp: number;
|
|
}
|
|
|
|
export function tokenize(input: string): string[] {
|
|
enum State {
|
|
Normal,
|
|
SingleQuote,
|
|
DoubleQuote,
|
|
Escape,
|
|
}
|
|
|
|
const tokens: string[] = [];
|
|
const buffer: string[] = [];
|
|
let state = State.Normal;
|
|
let escapeReturnState = State.Normal;
|
|
|
|
function flushBuffer() {
|
|
if (buffer.length > 0) {
|
|
tokens.push(buffer.join(""));
|
|
buffer.length = 0;
|
|
}
|
|
}
|
|
|
|
for (const char of input) {
|
|
switch (state) {
|
|
case State.Normal:
|
|
if (char === '"') {
|
|
flushBuffer();
|
|
state = State.DoubleQuote;
|
|
} else if (char === "'") {
|
|
flushBuffer();
|
|
state = State.SingleQuote;
|
|
} else if (char === "\\") {
|
|
escapeReturnState = State.Normal;
|
|
state = State.Escape;
|
|
} else if (char === " ") {
|
|
flushBuffer();
|
|
} else {
|
|
buffer.push(char);
|
|
}
|
|
break;
|
|
case State.SingleQuote:
|
|
if (char === "'") {
|
|
flushBuffer();
|
|
state = State.Normal;
|
|
} else {
|
|
buffer.push(char);
|
|
}
|
|
break;
|
|
case State.DoubleQuote:
|
|
if (char === '"') {
|
|
flushBuffer();
|
|
state = State.Normal;
|
|
} else if (char === "\\") {
|
|
escapeReturnState = State.DoubleQuote;
|
|
state = State.Escape;
|
|
} else {
|
|
buffer.push(char);
|
|
}
|
|
break;
|
|
case State.Escape:
|
|
if (escapeReturnState === State.DoubleQuote) {
|
|
if (char === "$" || char === "`" || char === '"' || char === "\\" || char === "\n") {
|
|
if (char !== "\n") {
|
|
buffer.push(char);
|
|
}
|
|
} else {
|
|
buffer.push("\\");
|
|
buffer.push(char);
|
|
}
|
|
} else {
|
|
buffer.push(char);
|
|
}
|
|
state = escapeReturnState;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (state === State.DoubleQuote || state === State.SingleQuote) {
|
|
throw {
|
|
type: "UnclosedQuote",
|
|
message: `Tokenizer returned with an unclosed quote`,
|
|
timestamp: Date.now(),
|
|
} satisfies UnclosedQuoteError;
|
|
}
|
|
|
|
flushBuffer();
|
|
return tokens;
|
|
}
|