Command Line Flags in Chapel

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Chapel provides a CommandLineOptions module for basic command-line flag parsing. We’ll use this module to implement our example command-line program.

use CommandLineOptions;

config const word: string = "foo";
config const numb: int = 42;
config const fork: bool = false;
config var svar: string = "bar";

proc main() {
  // Parse the command-line arguments
  parseCommandLineOptions();

  // Print out the parsed options
  writeln("word: ", word);
  writeln("numb: ", numb);
  writeln("fork: ", fork);
  writeln("svar: ", svar);
  
  // Print any trailing positional arguments
  const args = CommandLineOptions.arguments();
  writeln("tail: ", args);
}

In Chapel, we use config variables to declare command-line options. The parseCommandLineOptions() function is called to process the command-line arguments.

To experiment with the command-line flags program, compile it and then run the resulting binary directly.

$ chpl command_line_flags.chpl -o command_line_flags

Try out the built program by first giving it values for all flags.

$ ./command_line_flags --word=opt --numb=7 --fork=true --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: []

Note that if you omit flags, they automatically take their default values.

$ ./command_line_flags --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []

Trailing positional arguments can be provided after any flags.

$ ./command_line_flags --word=opt a1 a2 a3
word: opt
...
tail: a1 a2 a3

Chapel’s command-line parsing allows flags to appear anywhere in the command line, not just before positional arguments.

Use --help flag to get automatically generated help text for the command-line program.

$ ./command_line_flags --help
Usage: ./command_line_flags [options]
Options:
  --word=<string>  a string (default: "foo")
  --numb=<int>     an int (default: 42)
  --fork=<bool>    a bool (default: false)
  --svar=<string>  a string var (default: "bar")
  --help           Show this help message

If you provide a flag that wasn’t specified, the program will print an error message and show the help text.

$ ./command_line_flags --wat
error: Unknown flag: "--wat"
Usage: ./command_line_flags [options]
...

Chapel’s command-line option handling is built into the language and runtime, providing a simpler and more integrated approach compared to separate flag parsing libraries.