Created
April 2, 2022 04:39
-
-
Save wunki/c5468582facd15ea0f44dff106855de5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
// Errors which can be returned when parsing the command line arguments. | |
const ParseArgsError = error{TooManyArguments}; | |
// The different commands which may be run. | |
const Command = union(enum) { | |
startRepl, | |
runInterpreter: []const u8, | |
}; | |
pub fn main() anyerror!void { | |
// initiate an memory allocator, which we wil free as soon as we | |
// exit this scope. | |
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
defer arena.deinit(); | |
const allocator = arena.allocator(); | |
// get the commandline arguments | |
const args = try std.process.argsAlloc(allocator); | |
defer std.process.argsFree(allocator, args); | |
const command = try parseArgs(args); | |
switch (command) { | |
Command.startRepl => std.debug.print("start the repl", .{}), | |
Command.runInterpreter => |file| std.debug.print("running the file: {s}", .{file}), | |
} | |
} | |
/// Parses the commandline arguments and returns the command to execute. | |
fn parseArgs(args: [][]const u8) ParseArgsError!Command { | |
if (args.len > 2) return ParseArgsError.TooManyArguments; | |
const action: Command = switch (args.len) { | |
1 => Command.startRepl, | |
else => Command{ .runInterpreter = args[1] }, | |
}; | |
return action; | |
} | |
test "no arguments should start the repl" { | |
var arg: []const u8 = "lucy"; | |
const argsList = &[_][]const u8{arg}; | |
try std.testing.expectEqual(parseArgs(argsList), Command.startRepl); | |
} | |
test "extra argument should interpret the file" { | |
var argOne: []const u8 = "lucy"; | |
var argTwo: []const u8 = "main.lucy"; | |
const argsList = &[_][]const u8{ argOne, argTwo }; | |
try std.testing.expectEqual(parseArgs(argsList), Command{ .runInterpreter = "main.lucy" }); | |
} | |
test "too many arguments should raise an error" { | |
var argOne: []const u8 = "lucy"; | |
var argTwo: []const u8 = "main.lucy"; | |
var argThree: []const u8 = "boo"; | |
const argsList = &[_][]const u8{ argOne, argTwo, argThree }; | |
try std.testing.expectError(ParseArgsError.TooManyArguments, parseArgs(argsList)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment