I want to write my own command line library from scratch. What algorithm should I use in order to parse gnu style args like in getopt for example ? I mean what's the best way other than tokenizing and parse them in a naive way? Should I try to look at LR, LL algorithms or this is way too overkill?

  • 4
  • The best way is to tokenize and parse in the naive way. A simple Split function call will get you all of the top-level tokens, in most cases, and another split will separate the switches from the parameters, so compiler-level parsers are always overkill. Most of the existing command line parsing libraries are too complicated; it's simpler just to write a naive class. – Robert Harvey Dec 5 '17 at 16:25
  • 1
    See also stackoverflow.com/questions/491595 and stackoverflow.com/questions/1524661. As you can see, there's plenty of prior art. – Robert Harvey Dec 5 '17 at 16:48
  • Algorithms like LR are concerned with context free grammars, i.e. recursive syntax. Command line flags don't generally feature complicated syntax, but generally only flags and key-value pairs. An ad-hoc approach is often entirely sufficient. Once you want combined flags (-abc = -a -b -c), --foo=bar style values, or abbreviations, then using an existing options parsing library seems sensible. – amon Dec 5 '17 at 18:59

An LL(1) parser is a top down left to right parser, that needs only to know one symbol in advance. This is sufficient to parse a command line syntax.

But constructing an LL(1) parser seems to be an overkill for this kind of tasks, where a loop, a couple of ifs and some flags would completely do the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.