@@ -168,19 +168,41 @@ export default class Grammar {
168168 * for the specific options.
169169 */
170170 static fromGrammarFile ( grammarFile , options = { } , grammarType = 'bnf' ) {
171- const grammarData = Grammar . dataFromGrammarFile ( grammarFile , grammarType ) ;
171+ const grammarData = Grammar . dataFromGrammarFile ( grammarFile , { grammarType } ) ;
172172 return Grammar . fromData ( grammarData , options ) ;
173173 }
174174
175175 /**
176176 * Reads grammar file data. Supports reading `bnf`,
177177 * and `lex` grammars based on mode.
178178 */
179- static dataFromGrammarFile ( grammarFile , grammarType = 'bnf' ) {
180- return Grammar . dataFromString (
181- fs . readFileSync ( grammarFile , 'utf-8' ) ,
182- grammarType
183- ) ;
179+ static dataFromGrammarFile ( grammarFile , { grammarType = 'bnf' , useLocation = false } ) {
180+ const grammar = fs . readFileSync ( grammarFile , 'utf8' ) ;
181+
182+ // check if the bnf grammar contains location capture characters
183+ if ( grammarType === 'bnf' && ! useLocation ) {
184+ const bnf = grammar
185+ // lexer rules
186+ . replace ( / % l e x [ \n \s \S ] * ?\/ l e x / g, '' )
187+ // comments
188+ . replace ( / \/ \* [ \n \s \S ] * ?\* \/ / g, '' )
189+ . replace ( / \/ \/ .* ?\n / g, '' )
190+ //strings
191+ . replace ( / ' ( \\ .| [ ^ ' \\ ] ) * ' / g, '' )
192+ . replace ( / " ( \\ .| [ ^ " \\ ] ) * " / g, '' )
193+ . replace ( / ` ( \\ .| [ ^ ` \\ ] ) * ` / g, '' )
194+ // module include
195+ . replace ( / % { [ \n \s \S ] * ?% } / g, '' ) ;
196+
197+ if ( / @ \w + / . test ( bnf ) ) {
198+ console . info ( colors . red (
199+ 'The grammar file contains location capture characters (@), which require the ' +
200+ '"--loc" option, but it has not been provided. The generated parser will throw an error.'
201+ ) ) ;
202+ }
203+ }
204+
205+ return Grammar . dataFromString ( grammar , grammarType ) ;
184206 }
185207
186208 /**
0 commit comments