v2 / vlib / v / util / errors.v
266 lines · 242 sloc · 8.2 KB · adcd421456d50a26e50f1caef933caf539c3b8e5
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4@[has_globals]
5module util
6
7import os
8import strings
9import term
10import v.errors
11import v.token
12
13// The filepath:line:col: format is the default C compiler error output format.
14// It allows editors and IDE's like emacs to quickly find the errors in the
15// output and jump to their source with a keyboard shortcut.
16// Note: using only the filename may lead to inability of IDE/editors
17// to find the source file, when the IDE has a different working folder than
18// v itself.
19// error_context_before - how many lines of source context to print before the pointer line
20// error_context_after - ^^^ same, but after
21const error_context_before = 2
22const error_context_after = 2
23
24// emanager.support_color - should the error and other messages
25// have ANSI terminal escape color codes in them.
26// By default, v tries to autodetect, if the terminal supports colors.
27// Use -color and -nocolor options to override the detection decision.
28pub const emanager = new_error_manager()
29
30pub struct EManager {
31mut:
32 support_color bool
33}
34
35pub fn new_error_manager() &EManager {
36 return &EManager{
37 support_color: term.can_show_color_on_stderr() && term.can_show_color_on_stdout()
38 }
39}
40
41pub fn (e &EManager) set_support_color(b bool) {
42 unsafe {
43 mut me := e
44 me.support_color = b
45 }
46}
47
48pub fn bold(msg string) string {
49 if !emanager.support_color {
50 return msg
51 }
52 return term.bold(msg)
53}
54
55pub fn color(kind string, msg string) string {
56 if !emanager.support_color {
57 return msg
58 }
59 if kind.contains('error') {
60 return term.red(msg)
61 }
62 if kind.contains('notice') {
63 return term.yellow(msg)
64 }
65 if kind.contains('details') {
66 return term.bright_blue(msg)
67 }
68 return term.magenta(msg)
69}
70
71const normalised_workdir = os.wd_at_startup.replace('\\', '/') + '/'
72
73const verror_paths_absolute = os.getenv('VERROR_PATHS') == 'absolute'
74
75// path_styled_for_error_messages converts the given file `path`, into one suitable for displaying
76// in error messages, produced by the V compiler.
77//
78// When the file path is prefixed by the working folder, usually that means, that the resulting
79// path, will be relative to the current working folder. Relative paths are shorter and stabler,
80// because they only depend on the project, and not on the parent folders.
81// If the current working folder of the compiler is NOT a prefix of the given path, then this
82// function will return an absolute path instead. Absolute paths are longer, and also platform/user
83// dependent, but they have the advantage of being more easily processible by tools on the same
84// machine.
85//
86// The V user can opt out of that relativisation, by setting the environment variable VERROR_PATHS,
87// to `absolute`. That is useful for starting the V compiler from an IDE or another program, where
88// the concept of a "current working folder", is not as clear as working manually with the compiler
89// in a shell. By setting VERROR_PATHS=absolute, the IDE/editor can ensure, that the produced error
90// messages will have file locations that are easy to find and jump to locally.
91//
92// NOTE: path_styled_for_error_messages will *always* use `/` in the error paths, no matter the OS,
93// to ensure stable compiler error output in the tests.
94pub fn path_styled_for_error_messages(path string) string {
95 mut rpath := os.real_path(path)
96 rpath = rpath.replace('\\', '/')
97 if verror_paths_absolute {
98 return rpath
99 }
100 if rpath.starts_with(normalised_workdir) {
101 rpath = rpath.replace_once(normalised_workdir, '')
102 }
103 return rpath
104}
105
106// formatted_error - `kind` may be 'error' or 'warn'
107pub fn formatted_error(kind string, omsg string, filepath string, pos token.Pos) string {
108 emsg := omsg.replace('main.', '')
109 path := path_styled_for_error_messages(filepath)
110 position := if filepath != '' {
111 '${path}:${pos.line_nr + 1}:${int_max(1, pos.col + 1)}:'
112 } else {
113 ''
114 }
115 scontext := source_file_context(kind, filepath, pos).join('\n')
116 final_position := bold(position)
117 final_kind := bold(color(kind, kind))
118 final_msg := emsg
119 final_context := if scontext.len > 0 { '\n${scontext}' } else { '' }
120
121 return '${final_position} ${final_kind} ${final_msg}${final_context}'.trim_space()
122}
123
124@[heap]
125struct LinesCache {
126mut:
127 lines map[string][]string
128}
129
130__global lines_cache = &LinesCache{}
131
132pub fn cached_file2sourcelines(path string) []string {
133 if res := lines_cache.lines[path] {
134 return res
135 }
136 source := read_file(path) or { '' }
137 res := set_source_for_path(path, source)
138 return res
139}
140
141// set_source_for_path should be called for every file, over which you want to use util.formatted_error
142pub fn set_source_for_path(path string, source string) []string {
143 lines := source.split_into_lines()
144 lines_cache.lines[path] = lines
145 return lines
146}
147
148pub fn source_file_context(kind string, filepath string, pos token.Pos) []string {
149 mut clines := []string{}
150 source_lines := unsafe { cached_file2sourcelines(filepath) }
151 if source_lines.len == 0 {
152 return clines
153 }
154 bline := int_max(0, pos.line_nr - error_context_before)
155 aline := int_max(0, int_min(source_lines.len - 1, pos.line_nr + error_context_after))
156 tab_spaces := ' '
157 for iline := bline; iline <= aline; iline++ {
158 sline := source_lines[iline] or { '' }
159 start_column := int_max(0, int_min(pos.col, sline.len))
160 end_column := int_max(0, int_min(pos.col + int_max(0, pos.len), sline.len))
161 cline := if iline == pos.line_nr {
162 sline[..start_column] + color(kind, sline[start_column..end_column]) +
163 sline[end_column..]
164 } else {
165 sline
166 }
167 clines << '${iline + 1:5d} | ' + cline.replace('\t', tab_spaces)
168 //
169 if iline == pos.line_nr {
170 // The pointerline should have the same spaces/tabs as the offending
171 // line, so that it prints the ^ character exactly on the *same spot*
172 // where it is needed. That is the reason we can not just
173 // use strings.repeat(` `, col) to form it.
174 mut pointerline_builder := strings.new_builder(sline.len)
175 for i := 0; i < start_column; {
176 if sline[i].is_space() {
177 pointerline_builder.write_u8(sline[i])
178 i++
179 } else {
180 char_len := utf8_char_len(sline[i])
181 spaces := ' '.repeat(utf8_str_visible_length(sline#[i..i + char_len]))
182 pointerline_builder.write_string(spaces)
183 i += char_len
184 }
185 }
186 underline_len := utf8_str_visible_length(sline[start_column..end_column])
187 underline := if underline_len > 1 { '~'.repeat(underline_len) } else { '^' }
188 pointerline_builder.write_string(bold(color(kind, underline)))
189 clines << ' | ' + pointerline_builder.str().replace('\t', tab_spaces)
190 }
191 }
192 return clines
193}
194
195@[noreturn]
196pub fn verror(kind string, s string) {
197 final_kind := bold(color(kind, kind))
198 eprintln('${final_kind}: ${s}')
199 exit(1)
200}
201
202pub fn vlines_escape_path(path string, ccompiler string) string {
203 return cescaped_path(os.real_path(path))
204}
205
206pub fn show_compiler_message(kind string, err errors.CompilerMessage) {
207 ferror := formatted_error(kind, err.message, err.file_path, err.pos)
208 eprintln(ferror)
209 if err.details.len > 0 {
210 eprintln(bold('Details: ') + color('details', err.details))
211 }
212 // Display call stack if available
213 if err.call_stack.len > 0 {
214 for item in err.call_stack {
215 caller_path := path_styled_for_error_messages(item.file_path)
216 eprintln(bold('called from') + ' ${caller_path}:${item.pos.line_nr +
217 1}:${int_max(1, item.pos.col + 1)}')
218 // Display code context for the caller location
219 scontext := source_file_context(kind, item.file_path, item.pos).join('\n')
220 if scontext.len > 0 {
221 eprintln(scontext)
222 }
223 }
224 }
225}
226
227pub struct JsonError {
228pub:
229 path string
230 message string
231 line_nr int
232 col int
233 len int
234}
235
236pub fn print_json_errors(errs []JsonError) {
237 // Can't import x.json2 or json, so have to manually generate json
238 eprintln('[')
239 for i, e in errs {
240 msg := e.message.replace('"', '\\"').replace('\n', '\\n')
241 eprintln('{
242"path":"${e.path}",
243"message":"${msg}",
244"line_nr":${e.line_nr},
245"col":${e.col},
246"len":${e.len}
247}')
248 if i < errs.len - 1 {
249 eprintln(',')
250 }
251 }
252 eprintln(']')
253}
254
255/*
256pub fn print_json_error(kind string, err errors.CompilerMessage) {
257 e := JsonError{
258 message: err.message
259 path: err.file_path
260 line_nr: err.pos.line_nr + 1
261 col: err.pos.col + 1
262 len: err.pos.len
263 }
264 eprintln(json2.encode_pretty(e))
265}
266*/
267