str/src/vm/commands/rsub.ts

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-11-12 03:37:32 +00:00
import {Command, ParseContext, StrTerm} from "./command.js";
import {LexInput} from "../lexer.js";
import {StrVM} from "../vm.js";
import {Awaitable} from "../../util/types.js";
import {LSubData} from "./lsub.js";
2025-11-12 03:37:32 +00:00
export type RSubData = {
offset: StrTerm,
length?: StrTerm,
}
export class RSub extends Command<RSubData> {
attemptParse(context: ParseContext): RSubData {
return {
offset: context.popTerm(),
length: context.popOptionalTerm(),
}
}
getDisplayName(): string {
return 'rsub'
}
isParseCandidate(token: LexInput): boolean {
return this.isKeyword(token, 'rsub')
}
execute(vm: StrVM, data: LSubData): Awaitable<StrVM> {
return vm.inPlace(ctx =>
ctx.replaceSubject(sub =>
sub.modify(s => {
const offset = ctx.resolveInt(data.offset)
const length = data.length ? ctx.resolveInt(data.length) : s.length
return s.split('') // fixme: do the math so we don't have to do this bs
.reverse()
.slice(offset, offset + length)
.reverse()
.join('')
})))
}
2025-11-12 03:37:32 +00:00
}