There are no specific rules for parsing command-line arguments, and there is a more popular Unix-style and Microsoft-style. In fact, in addition to the UNIX style of the more consistent, Microsoft's own provision of command-line parameter parsing there are many styles. In the main function under the. NET platform, just decompose the parameters into a space-separated array, which requires a switch, and some switches have their own parameters of the situation is not enough, and in order to resolve these parameters need to learn part of lexical analysis knowledge, this is not very useful command line parameters appear some "chicken", Of course, with ANTLR to deal with the command line parameters are somewhat chicken, and is large only small use, because the ANTLR grammar rules are more complex, learning to have a certain degree of difficulty. But for developers who have already used ANTLR for DSL development, the problem with resolving command-line parameter resolution is a snap.
We need to first define the input rules for command-line arguments, refer to the command-line tools provided by the. Net framework, and make the following rules:
1, with the Space division parameters, and the. NET command-line parameters are consistent.
2, Options or switches (switch) with/or/or-as a sign.
3, options can have parameters, use colon: split, the option of the argument if multiple use commas (,) or semicolons (;) separated.
4, after the option is the command line itself parameters.
5. The name of the option begins with an English letter.
6, the parameters of the option and the parameters of the command line itself can be used in English letters and numbers, underscores, if you include Double-byte code or special characters, you need to use double quotes.
When the rules are well established, start to the point:
The first step, the need to download from the ANTLR Web site (http://www.antlr.org) ANTLR class library and related learning materials and tools, the tool is more important ANTLR works.
The second step is to edit the lexical and grammatical rules using ANTLR works or a text editor:
grammar CmdPara;
options{
language=CSharp2;
output=AST;
ASTLabelType=CommonTree;
}
tokens{
Option;
}
cmdLine : String option* para* EOF!;
option
: swt ((':' para)((','|';')para)*)? ->^(Option swt para*);
swt : ('/'|'-'|'\\') ID -> ID;
para : String|INT|ID;
ID : ('a'..'z'|'A'..'Z')(('a'..'z')
|('A'..'Z')
|'0'..'9'
|'&'
|'/'
|'\\'
|'.'
|'_'
)*; //don't support chinese
String : ('"' .+ '"')|('\'' .+ '\'');
INT : ('1'..'9')('0'..'9')*
;
WS
: (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;}
;