1 /////////////////////////////////////////////////////////////////////////////////////////////// 2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules. 3 // Copyright (C) 2001-2025 the original author or authors. 4 // 5 // This library is free software; you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 2.1 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library; if not, write to the Free Software 17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 18 /////////////////////////////////////////////////////////////////////////////////////////////// 19 20 package com.puppycrawl.tools.checkstyle.grammar; 21 22 import org.antlr.v4.runtime.CharStream; 23 import org.antlr.v4.runtime.Lexer; 24 import org.antlr.v4.runtime.atn.ATN; 25 import org.antlr.v4.runtime.atn.LexerATNSimulator; 26 import org.antlr.v4.runtime.atn.PredictionContextCache; 27 import org.antlr.v4.runtime.dfa.DFA; 28 29 /** 30 * Extends the LexerATNSimulator class in order to override 31 * the 'consume()' method so that we can handle '\r' line 32 * endings (pre-OSX macOS line endings) correctly in the 33 * ANTLR lexer. 34 */ 35 public class CrAwareLexerSimulator extends LexerATNSimulator { 36 37 /** 38 * Constructs a CrAwareLexerSimulator to interpret the input 39 * from the lexer. 40 * 41 * @param lexer the current lexer 42 * @param augmented the augmented transition network 43 * @param decisionToDfa the DFA to store our states in 44 * @param sharedContextCache cache of PredictionContext objects 45 */ 46 public CrAwareLexerSimulator(Lexer lexer, ATN augmented, 47 DFA[] decisionToDfa, 48 PredictionContextCache sharedContextCache) { 49 super(lexer, augmented, decisionToDfa, sharedContextCache); 50 } 51 52 /** 53 * Overrides the 'consume()' method to add support for 54 * '\r' (carriage return) line endings. 55 * 56 * @param input the Character stream of the file we are parsing 57 */ 58 @Override 59 public void consume(CharStream input) { 60 final int currentChar = input.LA(1); 61 if (currentChar == '\n') { 62 line++; 63 charPositionInLine = 0; 64 } 65 else if (currentChar == '\r') { 66 final int nextChar = input.LA(2); 67 if (nextChar != '\n') { 68 line++; 69 charPositionInLine = 0; 70 } 71 } 72 else { 73 charPositionInLine++; 74 } 75 input.consume(); 76 } 77 }