1 /* 2 * Copyright (c) 2025 Shenzhen Kaihong Digital. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package antlr; 17 18 import org.antlr.v4.runtime.BaseErrorListener; 19 import org.antlr.v4.runtime.RecognitionException; 20 import org.antlr.v4.runtime.Recognizer; 21 import org.antlr.v4.runtime.Token; 22 import org.antlr.v4.runtime.misc.IntervalSet; 23 24 import java.util.Locale; 25 26 /** 27 * <h3>类名:该类用于xxx</h3> 28 * description typescript error listener 29 * 30 * @author Administrator 31 * date 2025-02-28 32 * @version 1.0 33 * @since 2025-02-28 34 */ 35 public class CPP14ErrorListener extends BaseErrorListener { 36 @Override syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e)37 public void syntaxError(Recognizer<?, ?> recognizer, 38 Object offendingSymbol, 39 int line, 40 int charPositionInLine, 41 String msg, 42 RecognitionException e) { 43 System.err.println("syntax error"); 44 System.out.println("syntax error"); 45 // 输出错误位置和消息 46 String errorHeader = String.format(Locale.ROOT, "语法错误@行%d:%d - ", line, charPositionInLine + 1); 47 String errorDetail = String.format("符号 '%s' 无效,预期: %s", 48 ((Token) offendingSymbol).getText(), 49 getExpectedTokens(recognizer, e)); 50 System.err.println(errorHeader + errorDetail + " | 错误详情: " + msg); 51 } 52 getExpectedTokens(Recognizer<?, ?> recognizer, RecognitionException e)53 private String getExpectedTokens(Recognizer<?, ?> recognizer, RecognitionException e) { 54 if (e == null) { 55 return "未知预期符号"; 56 } 57 IntervalSet expectedTokens = e.getExpectedTokens(); 58 return expectedTokens.toString(recognizer.getVocabulary()); 59 } 60 }