user2132212
user2132212

Reputation: 1

Handling comments and Line/Column numbers in COBOL grammar using Javacc

I am working on a COBOL Parser using JavaCC. The COBOL file usually will have columns 1 to 6 as Line/Column numbers. If Line/Column numbers are not present it will have spaces.

I need to know how to handle comments and Sequence Area in a COBOL file and parse only Main Area.

I have tried many expressions but none is working. I created a special token that will check for new line and then six occurrences of spaces or any character except space and carriage return and after that seventh character will be "*" for comments and " " for normal lines.

I am using the Cobol.jj file available here http://java.net/downloads/javacc/contrib/grammars/cobol.jj

Can anyone suggest me what grammar should i use?

the sample of my grammar file:

    PARSER_END(CblParser)

////////////////////////////////////////////////////////////////////////////////
// Lexical structure
////////////////////////////////////////////////////////////////////////////////

SPECIAL_TOKEN :
{
  < EOL: "\n" > : LINE_START 
| < SPACECHAR: ( " " | "\t" | "\f" | ";" | "\r" )+ >
}

SPECIAL_TOKEN :
{
  < COMMENT: ( ~["\n","\r"," "] ~["\n","\r"," "] ~["\n","\r"," "] ~["\n","\r"," "] ~["\n","\r"," "] ~["\n","\r"," "] ) ( "*" | "|" ) (~["\n","\r"])* >
| < PREPROC_COMMENT: "*|" (~["\n","\r"])* >
| < SPACE_SEPARATOR : ( <SPACECHAR> | <EOL> )+ >
| < COMMA_SEPARATOR : "," <SPACE_SEPARATOR> >
}

<LINE_START> SKIP :
{
 < ((~[])(~[])(~[])(~[])(~[])(~[])) (" ") >
}

Upvotes: 0

Views: 976

Answers (1)

Theodore Norvell
Theodore Norvell

Reputation: 16221

Since the parser starts at the start of a line, you should use the DEFAULT state to represent the start of a line. I would do something like the following [untested code follows].

// At the start of each line, the first 6 characters are ignored and the 7th is used
// to determine whether this is a code line or a comment line.
// (Continuation lines are handled elsewhere.)
// If there are fewer than 7 characters on the line, it is ignored.
// Note that there will be a TokenManagerError if a line has at least 7 characters and
// the 7th character is other than a "*", a "/", or a space.
<DEFAULT> SKIP :
{
   < (~[]){0,6} ("\n" | "\r" | "\r\n") > :DEFAULT
|
   < (~[]){6} (" ") > :CODE
|
   < (~[]){6} ("*"|"/")  :COMMENT
}

<COMMENT> SKIP :
{   // At the end of a comment line, return to the DEFAULT state.
    < "\n" | "\r" | "\r\n" > : DEFAULT
|   // All non-end-of-line characters on a comment line are ignored.
    < ~["\n","\r"] > : COMMENT
}
<CODE> SKIP :
{   // At the end of a code line, return to the DEFAULT state.
    < "\n" | "\r" | "\r\n" > : DEFAULT
|   // White space is skipped, as are semicolons.
    < ( " " | "\t" | "\f" | ";" )+ >
}
<CODE> TOKEN :
{  
    < ACCEPT: "accept" >
|  
    ... // all rules for tokens should be in the CODE state.
}

Upvotes: 1

Related Questions