-
Notifications
You must be signed in to change notification settings - Fork 3
/
ghc-colorizer
executable file
·372 lines (326 loc) · 11.6 KB
/
ghc-colorizer
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python
'''
NAME
ghc-colorizer - Colorizes diagnostic output from GHC.
SYNOPSIS
ghc-colorizer --with-ghc=GHC_PATH [-f[no-]color-diagnostics] [ARG...]
DESCRIPTION
`ghc-colorizer` adds color to the diagnostic output (errors and
warnings) from GHC.
To use this script, simply run it with an additional argument
`--with-ghc=GHC_PATH` and pass the usual arguments as if this were GHC.
Here, `GHC_PATH` should be a path pointing to the actual GHC executable
(don't point it to this script!).
OPTIONS
--with-ghc=GHC_PATH
Specifies the path to the GHC executable. This argument must be
specified exactly once. Additional arguments of this form are
instead passed to GHC.
-f[no-]color-diagnostics
Can be used to suppress or force colored output. If omitted,
the script will attempt to automatically determine whether
colored output is supported.
EXAMPLE
#!/bin/sh
script_path=`cd "\`dirname \"$0\"\`" && pwd`
ghc_path="$script_path/ghc-7.8.2"
if type >/dev/null 2>&1 ghc-colorizer
then ghc-colorizer --with-ghc="$ghc_path" "$@"
else "$ghc_path" "$@"
fi
DEPRECATION
With the release of native support for colored diagnostics in GHC 8.2,
this tool is deprecated and no longer necessary.
'''
from __future__ import unicode_literals
import os, re, subprocess, sys
# ----------------------------------------------------------------------------
# global constants
# ----------------------------------------------------------------------------
# name of this program
PROG = os.path.basename(sys.argv[0])
WARNING_COLOR = 35
ERROR_COLOR = 31
ARROW_COLOR = 32
ARROW_CHAR = "^"
LOCATION_FORMAT = [
"{filename}:{row1}:{col1}:",
"{filename}:{row1}:{col1}-{col2}:",
"{filename}:({row1},{col1})-({row2},{col2}):",
]
def color_support():
# whether standard error is a display device (as opposed to, say, a pipe)
if not sys.stderr.isatty():
return False
try:
import curses
curses.setupterm()
except Exception:
return False
# detect support for colors
if curses.tigetnum("colors") <= 0:
return False
return True
# ----------------------------------------------------------------------------
# parse args and run GHC
# ----------------------------------------------------------------------------
# this can be overridden later on by args
enabled = color_support()
# whether error spans are shown (note that we will turn it on anyway, but this
# affects whether the number is actually printed)j
error_spans = False
# parse arguments
args = [None] # to be replaced with GHC path
for arg in sys.argv[1:]:
if args[0] is None and arg.startswith("--with-ghc="):
args[0] = arg[len("--with-ghc="):]
elif arg == "-fcolor-diagnostics":
enabled = True
elif arg == "-fno-color-diagnostics":
enabled = False
elif arg == "-ferror-spans":
error_spans = True
args.append(arg)
elif arg == "--interactive":
enabled = False
args.append(arg)
else:
args.append(arg)
if args[0] is None:
sys.stderr.write("{0}: must specify '--with-ghc=GHC_PATH'\n".format(PROG))
sys.exit(2)
# run GHC
if not enabled:
os.execvp(args[0], args)
try:
if not error_spans:
args.append("-ferror-spans")
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
except Exception as e:
sys.stderr.write("{0}: can't execute: {1}\n{2} {3}\n"
.format(PROG, args[0], " " * len(PROG), str(e)))
sys.exit(1)
# ----------------------------------------------------------------------------
# helper functions
# ----------------------------------------------------------------------------
cached_file_name = None
cached_file_lines = ()
def get_line_from_file(name, line_number):
'''(str, int) -> none | str'''
global cached_file_name, cached_file_lines
if cached_file_name != name:
try:
with open(name, "r") as f:
cached_file_lines = tuple(f)
cached_file_name = name
except OSError:
return
except UnicodeDecodeError:
return
try:
return cached_file_lines[line_number]
except IndexError:
pass
def tag(s):
return "\x1b[{}m".format(s)
bold_tag = tag(1)
reset_tag = tag(0)
def bold(s):
return bold_tag + str(s) + reset_tag
def color_tag(color_id, bold=False):
b = "1;" if bold else ""
return tag("0;" + b + str(color_id))
class Block(object):
def __init__(self):
self.lines = []
self.clear()
def is_empty(self):
return not self.filename
def clear(self):
self.filename = None
self.row1 = None
self.col1 = None
self.row2 = None
self.col2 = None
self.header = None
self.is_error = None
del self.lines[:]
def highlight_code(s):
repl = color_tag(37, True) + r"\2" + reset_tag + bold_tag
s = re.sub(r"(`)(\S*)(')", repl, s,)
s = re.sub(r"(\x2018)(\S*)(\x2019)", repl, s)
return s
def show_error_location(filename, row1, col1, row2, col2):
source_line = get_line_from_file(filename, row1)
if source_line is None:
sys.stderr.write("\n")
return
source_line = (source_line
.replace("\t", " ") # tabs are evil
.replace("\r", " "))
if not source_line.endswith("\n"):
source_line += "\n"
span = (min(len(source_line) - 2, col2) - col1)
arrow = col1 * " " + color_tag(ARROW_COLOR, True) + ARROW_CHAR + \
"~" * span + reset_tag
sys.stderr.write("{}{}{}\n".format(reset_tag, source_line, arrow))
# ----------------------------------------------------------------------------
# process diagnostic output
# ----------------------------------------------------------------------------
error_tally = 0
warning_tally = 0
lines = list(proc.stderr)
block = Block()
if lines and lines[-1].decode("utf-8").rstrip():
lines.append(b"\n")
for i, line in enumerate(lines):
line = line.decode("utf-8").rstrip()
if block.is_empty():
m = re.match(r"(?P<filename>.*):(?:" +
r"(?P<row>\d+):(?P<col>\d+)(?:-(?P<end>\d+))?|" +
r"\((?P<row1>\d+),(?P<col1>\d+)\)-" +
r"\((?P<row2>\d+),(?P<col2>\d+)\)" +
r"):(?P<line>.*)$", line)
if not m:
# avoid printing the last line if it's empty
if line or i != len(lines) - 1:
sys.stderr.write(line + "\n")
continue
# begin block
block.filename = m.group("filename")
line = m.group("line")
if m.group("row") is not None:
block.row1 = m.group("row")
block.col1 = m.group("col")
block.row2 = m.group("row")
block.col2 = m.group("end") or block.col1
fmt = LOCATION_FORMAT[1]
else:
block.row1 = m.group("row1")
block.col1 = m.group("col1")
block.row2 = m.group("row2")
block.col2 = m.group("col2")
fmt = LOCATION_FORMAT[2]
if not error_spans:
fmt = LOCATION_FORMAT[0]
block.header = fmt.format(
filename=block.filename,
row1=block.row1,
row2=block.row2,
col1=block.col1,
col2=block.col2,
)
block.row1 = int(block.row1) - 1
block.col1 = int(block.col1) - 1
block.row2 = int(block.row2) - 1
block.col2 = int(block.col2) - 1
if line:
line = line.lstrip()
m = re.match(r"([wW]arning|[eE]rror):(.*)$", line)
if m:
msg_type, rest = m.groups()
if msg_type.lower() == "warning":
color_id = WARNING_COLOR
block.is_error = False
else:
color_id = ERROR_COLOR
block.is_error = True
line = " {}{}:{}{}{}".format(
color_tag(color_id, True),
msg_type,
reset_tag,
bold_tag,
rest,
)
block.lines.append(line)
continue
# continue block
if line:
block.lines.append(line)
continue
# end block
sys.stderr.write(bold_tag)
sys.stderr.write(block.header)
if len(block.lines) > 0:
line0 = block.lines[0]
if block.is_error is None:
err_patt = "|".join((
"Couldn't match",
"No instance",
"Not in scope",
"Could not find module",
"parse error",
"Ambiguous occurrence",
"Occurs check",
"File name does not match module name",
"lexical error",
"error:",
"(?P<pre>.*)(?P<msg>does not export)",
"Could not deduce",
"Expecting one more argument",
"Constructor .* should have [0-9] arguments?",
))
m = re.match("(?P<indent> *)(?P<full>{})(?P<rest>.*)$"
.format(err_patt), line0)
if m:
if m.group("msg") is None:
indent = m.group("indent")
msg = m.group("full")
rest = m.group("rest")
else:
groups = m.groupdict()
indent = m.group("indent") + (groups.get("pre", None) or "")
msg = m.group("msg")
rest = (groups.get("post", None) or "") + m.group("rest")
block.is_error = True
color = color_tag(ERROR_COLOR, True)
line0 = highlight_code(indent + color + msg +
reset_tag + bold_tag + rest)
warn_patt = "|".join((
"warning:",
))
m = re.match("( *)({})(.*)$".format(warn_patt), line0)
if m:
indent, msg, rest = m.groups()
block.is_error = False
color = color_tag(WARNING_COLOR, True)
line0 = highlight_code(indent + color + msg +
reset_tag + bold_tag + rest)
sys.stderr.write("\n")
sys.stderr.write(line0 + "\n")
for line in block.lines[1:]:
line = highlight_code(line)
sys.stderr.write(line + "\n")
show_error_location(block.filename,
block.row1, block.col1,
block.row2, block.col2)
if block.is_error == False:
warning_tally += 1
elif block.is_error == True:
error_tally += 1
block.clear()
# print the tally (English language is hard)
def make_plural(count, word):
return "{} {}{}".format(count, word, "s" if count > 1 else "")
def make_chain(phrases):
if len(phrases) > 2:
return ", ".join(phrases[:-1]) + " and " + phrases[-1]
elif len(phrases) == 2:
return phrases[0] + " and " + phrases[1]
elif len(phrases) == 1:
return phrases[0]
else:
return ""
return "{} {}{}".format(count, word, "s" if count > 1 else "")
# display tallies
tally_msgs = []
if warning_tally > 0:
tally_msgs.append(make_plural(warning_tally, "warning"))
if error_tally > 0:
tally_msgs.append(make_plural(error_tally, "error"))
if tally_msgs:
sys.stderr.write(make_chain(tally_msgs) + " generated.\n")
# done, now wait for it to quit
sys.stderr.close()
proc.wait()
sys.exit(proc.returncode)