scripts/brainfzck

lang-brainfzck-0.0.1 source code

Package

Name
lang-brainfzck
Version
0.0.1
Uploaded
2026-06-06 21:16:38
Repository
https://github.com/tobyink/zuzu-lang-brainfzck
Dependencies
Metadata
zuzu-distribution.json
Archive
Download .tar.gz
#!/usr/bin/env zuzu

from lang/brainfzck import brainfzck;
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: brainfzck [options] [file|-]",
		"",
		"Options:",
		"  -e, --eval SOURCE   Run SOURCE instead of reading a file",
		"  -o, --output FILE   Write output to FILE instead of STDOUT",
		"  --eof MODE          EOF mode: zero, minus-one, or unchanged",
		"  --tape-size N       Maximum tape cells, default 30000",
		"  --cell-size N       Cell wrapping modulus, default 256",
		"  -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 "brainfzck: --eval does not accept a file argument";
		}
		return "" _ opts{eval};
	}
	if ( argv.length() == 0 or argv[0] eq "-" ) {
		if ( argv.length() > 1 ) {
			die "brainfzck: expected at most one input file";
		}
		return _read_stdin();
	}
	if ( argv.length() > 1 ) {
		die "brainfzck: 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",
			"eof=s",
			"tape-size=i",
			"cell-size=i",
		],
	);
	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 source := _read_source( parsed{argv}, opts );
	let run_opts := {};
	run_opts.set( "eof", opts{eof} ) if opts{eof} != null;
	run_opts.set( "tape_size", opts{"tape-size"} )
		if opts{"tape-size"} != null;
	run_opts.set( "cell_size", opts{"cell-size"} )
		if opts{"cell-size"} != null;

	let output := brainfzck( source, run_opts );
	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);
}