问题描述:

I am using Antlr4 for command line parsing.

The format of my grammar is

Command: subcommand1 | subcommand2

subcommand1: 'sub1' option1 option2

subcommand2: 'sub2' option3 option4

option1 : '-option1' ID

option2 : '-option2' ID

option3 : '-option3' ID

option4 : '-option4' ID

ID : [a-zA-Z0-9]+

I want the options for each subcommand to be order insensitive

For e.g subcommand -option1 ABC -option2 PQR should be considered as a valid input

As well as subcommand -option2 PQR -option1 ABC should also be considered as a valid input

One brute force way of changing the grammar could be

subcommand1: 'sub1' ( option1 option2 | option2 option1)

subcommand2: 'sub2' ( option3 option4 | option3 option4)

But this doesn't make it generic and adding one more option will require listing of 6 permutation of the options.

Is there an easy way of doing it?

网友答案:

You should make your grammar generic. Don't hardcode option names in the grammar, but generate a generic lexer and then interpret option names in your application.

I mean something like this:

grammar CommandLine;
command: ID option*;
option: OPTION ID;
OPTION: '-' ID;
ID : [a-zA-Z0-9]+;

Then use code to extract option names.

相关阅读:
Top