How to solve OutOfMemoryException when parsing large files using Antlr4 in C #?

I am trying to parse a large file (about 500 MB) using Antlr4 using C #. But I have an OutOfMemoryException exception.

My current code is described below:

var path = GetInput(Path.Combine(DatFilePath)); // Build the large file
var inputStream = new StreamReader(path);
var input = new UnbufferedCharStream(inputStream);
GroupGrammarLexer lexer = new GroupGrammarLexer(input);
lexer.TokenFactory = new CommonTokenFactory(true);
var tokens = new UnbufferedTokenStream(lexer);
GroupGrammarParser parser = new GroupGrammarParser(tokens);
parser.BuildParseTree = false;
GroupGrammarParser.FileContext tree = parser.file(); // here I get OutOfMemoryException

My grammar:

grammar grammar

/*
 * Parser Rules
 */

 file: row+;
 row: group | comment | not;
 group: GROUP NAME ATTACHTO NAME; 
 comment: '**' .*? NL;
 not: .*? NL;


GROUP   : '*'? G R O U P ;
ATTACHTO : '*'? A T T A C H T O ;
W : ('W'|'w') ;
E : ('E'|'e') ;
L : ('L'|'l') ;
G : ('G'|'g') ;
R : ('R'|'r') ;
O : ('O'|'o') ;
U : ('U'|'u') ;
P : ('P'|'p') ;
A : ('A'|'a') ;
T : ('T'|'t') ;
C : ('C'|'c') ;
H : ('H'|'h') ;
NAME    : '\''[a-zA-Z0-9_]+'\'' ;
WS: (' ') -> skip;
NL:   '\r'? '\n';

I have identified all the tips about large files, but I still get an OutOfMemoryException. When I test this code with a smaller file, it works great.

Is there something I am missing?

I appreciate any help.

Regards

+4
source share
1 answer

Try tokenize and parse in a stream with an increased stack size:

Thread thread = new Thread(delegate ()
{
    // Tokenize and parse here
},
500000);
thread.Start();
0

Source: https://habr.com/ru/post/1682526/


All Articles