scripts/forth.zzs

lang-forth-0.0.2 source code

Package

Name
lang-forth
Version
0.0.2
Uploaded
2026-06-12 23:11:04
Repository
https://github.com/tobyink/zuzu-lang-forth
Dependencies
Metadata
zuzu-distribution.json
Archive
Download .tar.gz
#!/usr/bin/env zuzu

from lang/forth import forth;
from std/getopt import Getopt;
from std/io import Path, STDERR, STDIN, STDOUT;
from std/proc import Proc;
from std/string import join;

function _usage () {
	return join( "\n", [
		"Usage: forth.zzs [options] [file|-]",
		"",
		"Options:",
		"  -e, --eval SOURCE   Run SOURCE instead of reading a file",
		"  -o, --output FILE   Write output to FILE instead of STDOUT",
		"  -h, --help          Show this help",
	] ) _ "\n";
}

function _read_stdin () {
	let chunks := [];
	while ( true ) {
		let line := STDIN.next_line();
		last if line == null;
		chunks.push(line);
	}
	return join( "", chunks );
}

function _read_source ( argv, opts ) {
	if ( opts.exists("eval") ) {
		if ( argv.length() != 0 ) {
			die "forth.zzs: --eval does not accept a file argument";
		}
		return "" _ opts{eval};
	}
	if ( argv.length() == 0 or argv[0] eq "-" ) {
		if ( argv.length() > 1 ) {
			die "forth.zzs: expected at most one input file";
		}
		return _read_stdin();
	}
	if ( argv.length() > 1 ) {
		die "forth.zzs: expected at most one input file";
	}
	return ( new Path(argv[0]) ).slurp_utf8();
}

function _run ( argv ) {
	let parsed := Getopt.parse(
		argv,
		[
			"help|h",
			"eval|e=s",
			"output|o=s",
		],
	);
	if ( not parsed{ok} ) {
		STDERR.say(parsed{error});
		STDERR.print(_usage());
		return 2;
	}

	let opts := parsed{options};
	if ( opts{help} ) {
		STDOUT.print(_usage());
		return 0;
	}

	let output := forth(
		_read_source( parsed{argv}, opts ),
		{ source_name: opts.exists("eval") ? "-e" : "<input>" },
	);
	if ( opts{output} != null ) {
		( new Path( "" _ opts{output} ) ).spew_utf8(output);
	}
	else {
		STDOUT.print(output);
	}

	return 0;
}

function __main__ ( argv ) {
	let status := 0;
	try {
		status := _run(argv);
	}
	catch ( Exception e ) {
		STDERR.say(e.to_String());
		status := 1;
	};
	Proc.exit(status);
}