I have the following ANTLR grammar to implement 2 shell commands 'connect' and 'cd' to be used in a Java program:
grammar ShellCommands;
@header
{
package ...;
import ....ShellCommandProcessor;
} // @header
@parser::members
{
/**
define a member about to hold the link to the command processor
*/
ShellCommandProcessor cp;
/**
define specific constructor which will make known the command processor
*/
public ShellCommandsParser(TokenStream input, ShellCommandProcessor cmdProc)
{
this(input);
cp = cmdProc;
} // ShellCommandsParser
/**
overwrite error message emitter
*/
public void emitErrorMessage(String message)
{
System.out.println(message);
} // emitErrorMessage
} // @members
/**
my grammar starts here
*/
commandline: command
;
command :
| 'connect' 'port' '=' INT { cp.connect($INT.text); }
| 'cd' DIR { cp.changeToDirectory($DIR.text); }
;
fragment DIRNAMEPART
: ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'/'|'.')+
;
INT : ('0'..'9')+
;
DIR : DIRNAMEPART+
;
WS : (' '|'\t')+ { skip(); }
;
Compiling the above grammar ('INT' defined before 'DIR') and then running my shell program the following sequence of inputs results in a parser error:
Shell [V0.1.5 B427 20.08.2026 17:45:44]
> connect port=28566
> Shell: connection with server at localhost:28566 has been established
localhost:28566/> cd 007
localhost:28566/> line 1:3 mismatched input '007' expecting DIR
localhost:28566/> 17:46:11.086 Err_0004 Unknown Shell command: [cd 007]
localhost:28566/>
The specified numeric port will be accepted but the desired 'change to directory' into a directory with a completely numeric name results in an error. Of course changing into a directory whose name doesn't consist only of numerics is possible:
Shell [V0.1.5 B429 20.08.2026 17:55:11]
> connect port=28566
> Shell: connection with server at localhost:28566 has been established
localhost:28566/> cd Spanish
localhost:28566/>
localhost:28566/Spanish>
Now I'm changing the sequence of the 'INT' and 'DIR' definitions in my grammar:
...
commandline: command
;
command :
| 'connect' 'port' '=' INT { cp.connect($INT.text); }
| 'cd' DIR { cp.changeToDirectory($DIR.text); }
;
fragment DIRNAMEPART
: ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'/'|'.')+
;
DIR : DIRNAMEPART+
;
INT : ('0'..'9')+
;
WS : (' '|'\t')+ { skip(); }
;
After compiling the changed grammer the following sequence of input results in a parser error:
Shell [V0.1.5 B428 20.08.2026 17:49:58]
> connect port=28566
> line 1:13 mismatched input '28566' expecting INT
> 17:50:17.482 Err_0004 Unknown Shell command: [connect port=28566]
>
Specifying the numeric port results in a parser error.
The problem is clear: depending on the sequence of my 'DIR' and 'INT' definitions either the port number will be interpreted as a 'DIR' or the (completely numeric) directory name will be interpreted as an 'INT' since both definitions contain '0'..'9'.
Any ideas how I can solve this problem?