-
Notifications
You must be signed in to change notification settings - Fork 2
/
MiniJavaError_Presenter.py
40 lines (33 loc) · 1.18 KB
/
MiniJavaError_Presenter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#-*- coding: utf-8 -*-
from antlr4.error.ErrorListener import *
class MiniJava_ErrorListener(ErrorListener):
'''
An inherited listener class to listen to the syntax errors.
The error triger is defined in the .g4 file.
'''
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
'''
An overwrite of the original method.
See https://www.antlr.org/api/Java/org/antlr/v4/runtime/ANTLRErrorListener.html for more details
recognizer: What parser got the error
offendingSymbol: The offending token in the input token stream
'''
print('line ' + str(line) + ':' + str(column) + '\t' + msg, file=sys.stderr)
self.print_detail(recognizer, offendingSymbol, line, column, msg, e)
def print_detail(self, recognizer, offendingSymbol, line, column, msg, e):
token = recognizer.getCurrentToken()
in_stream = token.getInputStream()
string = str(in_stream)
string = string.split('\n')[line - 1] # get the error line
print(string)
# Using '↑' to show the wrong token
# e.g. int 0number
# ↑
underline = ''
for i in range(column):
if string[i] == '\t':
underline += '\t'
else:
underline += ' '
underline += '↑'
print(underline)