Skip to content

Instantly share code, notes, and snippets.

@IanSSenne
Last active March 23, 2022 15:04
Show Gist options
  • Save IanSSenne/96c5d73c465527da664030ba965a55c2 to your computer and use it in GitHub Desktop.
Save IanSSenne/96c5d73c465527da664030ba965a55c2 to your computer and use it in GitHub Desktop.
type discard = never;
type AppendArgument<Base, Next> = Base extends (...args: infer E) => infer R
? (...args: [...E, Next]) => R
: never;
type ArgumentResult<T> =
| {
success: true;
value: T;
raw: string;
push?: boolean;
}
| {
success: false;
error: string;
depth?: number;
};
type GuessTypeBasedOnArgumentResultType<T extends ArgumentResult<any>> =
T extends { value: infer U }
? U extends { success: false }
? discard
: U
: discard;
type CommandResult =
| {
success: true;
executionSuccess: boolean;
executionError?: any;
}
| {
success: false;
error: string;
depth?: number;
};
class ArgumentMatcher {
name!: string;
matches(value: string): ArgumentResult<any> {
return {
success: false,
error: "NOT IMPLEMENTED",
};
}
setName(name: string): this {
this.name = name;
return this;
}
}
class RootArgumentMatcher {
name!: string;
matches(value: string): ArgumentResult<any> {
return {
success: true,
value: "",
raw: "",
push: false,
};
}
setName(name: string): this {
this.name = name;
return this;
}
}
class LiteralArgumentMatcher extends ArgumentMatcher {
constructor(private readonly literal: string) {
super();
}
matches(value: string): ArgumentResult<null> {
return value === this.literal || value.startsWith(this.literal + " ")
? {
success: true,
value: null,
raw: this.literal,
push: false,
}
: {
success: false,
error: `Expected '${this.literal}'`,
};
}
}
class Selector {}
class StringArgumentMatcher extends ArgumentMatcher {
constructor() {
super();
}
matches(value: string): ArgumentResult<string> {
return {
success: true,
value,
raw: value,
push: true,
};
}
}
class NumberArgumentMatcher extends ArgumentMatcher {
constructor() {
super();
}
matches(value: string): ArgumentResult<number> {
try {
const match = value.match(/^(-*(?:\d(?:\.\d+)*|(?:\.\d+)))/);
if (match) {
const value2 = parseFloat(match[0]);
if (Number.isNaN(value2) && Array.isArray(match)) {
return {
success: false,
error: `Expected a number for '${this.name}'`,
};
} else {
return {
success: true,
value: value2,
raw: match[0],
push: true,
};
}
}
return {
success: false,
error: `Expected a number for '${this.name}'`,
};
} catch (e) {
return {
success: false,
error: `Expected a number for '${this.name}'`,
};
}
}
}
class SelectorArgumentMatcher extends ArgumentMatcher {
constructor() {
super();
}
}
interface CommandContext {}
class ArgumentBuilder<
HandlerFn extends Function = (ctx: CommandContext) => void
> {
actions: ArgumentBuilder[];
depth = 0;
executable?: HandlerFn;
constructor(
public readonly matcher: ArgumentMatcher = new RootArgumentMatcher()
) {
this.actions = [];
}
private bind<T extends ArgumentBuilder<any>>(ab: T): T {
this.actions.push(ab);
ab.setDepth(this.depth + 1);
return ab;
}
private setDepth(depth: number) {
this.depth = depth;
}
literal(value: string): ArgumentBuilder<HandlerFn> {
return this.bind(
new ArgumentBuilder<HandlerFn>(
new LiteralArgumentMatcher(value).setName(value)
)
);
}
number(name: string): ArgumentBuilder<AppendArgument<HandlerFn, number>> {
return this.bind(
new ArgumentBuilder<AppendArgument<HandlerFn, number>>(
new NumberArgumentMatcher().setName(name)
)
);
}
string(name: string): ArgumentBuilder<AppendArgument<HandlerFn, string>> {
return this.bind(
new ArgumentBuilder<AppendArgument<HandlerFn, string>>(
new StringArgumentMatcher().setName(name)
)
);
}
argument<ArgumentType extends ArgumentMatcher>(
name: string,
matcher: ArgumentType
): ArgumentBuilder<
AppendArgument<
HandlerFn,
GuessTypeBasedOnArgumentResultType<ReturnType<ArgumentType["matches"]>>
>
> {
return this.bind(
new ArgumentBuilder<
AppendArgument<
HandlerFn,
GuessTypeBasedOnArgumentResultType<
ReturnType<ArgumentType["matches"]>
>
>
>(matcher.setName(name))
);
}
selector(): ArgumentBuilder<AppendArgument<HandlerFn, Selector>> {
return this.bind(
new ArgumentBuilder<AppendArgument<HandlerFn, Selector>>(
new SelectorArgumentMatcher()
)
);
}
executes(callback: HandlerFn) {
this.bind(new ArgumentBuilder<HandlerFn>()).executable = callback;
}
evaluate(
ctx: CommandContext,
command: string,
args: any[] = []
): CommandResult {
if (command.length === 0) {
if (this.executable) {
try {
this.executable(ctx, ...args);
} catch (e: any) {
return {
success: true,
executionSuccess: false,
executionError: e,
};
}
return { success: true, executionSuccess: true };
} else {
return {
success: false,
error: "Unexpected end of command",
};
}
}
let result = this.matcher.matches(command.trim());
if (result.success === true) {
let results = [];
for (const action of this.actions) {
const result2 = action.evaluate(
ctx,
command.trim().substring(result.raw.length),
result.push ? [...args, result.value] : [...args]
);
if (result2.success) return result2;
results.push(result2);
}
const min = Math.min(...results.map((r) => r.depth || Infinity));
return results.find((r) => r.depth === min) as CommandResult;
} else {
return {
success: false,
error: result.error,
depth: this.depth,
};
}
}
}
//// EXAMPLES
const root = new ArgumentBuilder();
let fork = root.literal("dice").number("sides");
fork.number("count").executes((ctx, sides, count) => {
console.log(`Rolling ${count} ${sides}-sided dice`);
});
fork.string("question").executes((ctx, a, b) => {
console.log(`1/${a} chances for ${b}?`);
});
root.evaluate({ a: 1 }, "dice 3 test");
Copyright 2022 Ian Senne
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@IanSSenne
Copy link
Author

this project is mostly complete, impliments tree based parsing of strings, arguments should extend ArgumentMatcher
currently implimented are the string and number argument matchers, Selector does exist but was for testing the types.

the goal of this was to learn to use infer and the usages of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment