]> git.xonotic.org Git - xonotic/gmqcc.git/blob - conout.c
Cleanups
[xonotic/gmqcc.git] / conout.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Dale Weiler
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include "gmqcc.h"
24
25 /*
26  * isatty/STDERR_FILENO/STDOUT_FILNO
27  * + some other things likewise.
28  */
29 #ifndef _WIN32
30 #   include <unistd.h>
31 #else
32 #   include <io.h>
33     /*
34      * Windows and it's posix underscore bullshit.  We simply fix this
35      * with yay, another macro :P
36      */
37 #   define isatty _isatty
38 #endif
39
40 #define GMQCC_IS_STDOUT(X) ((FILE*)((void*)X) == stdout)
41 #define GMQCC_IS_STDERR(X) ((FILE*)((void*)X) == stderr)
42 #define GMQCC_IS_DEFINE(X) (GMQCC_IS_STDERR(X) || GMQCC_IS_STDOUT(X))
43
44 typedef struct {
45     FILE *handle_err;
46     FILE *handle_out;
47
48     int   color_err;
49     int   color_out;
50 } con_t;
51
52 /*
53  * Doing colored output on windows is fucking stupid.  The linux way is
54  * the real way. So we emulate it on windows :)
55  */
56 #ifdef _WIN32
57 #define WIN32_LEAN_AND_MEAN
58 #include <windows.h>
59
60 /*
61  * Windows doesn't have constants for FILENO, sadly but the docs tell
62  * use the constant values.
63  */
64 #undef  STDERR_FILENO
65 #undef  STDOUT_FILENO
66 #define STDERR_FILENO 2
67 #define STDOUT_FILENO 1
68
69 enum {
70     RESET = 0,
71     BOLD  = 1,
72     BLACK = 30,
73     RED,
74     GREEN,
75     YELLOW,
76     BLUE,
77     MAGENTA,
78     CYAN,
79     GRAY,
80     WHITE = GRAY
81 };
82
83 enum {
84     WBLACK,
85     WBLUE,
86     WGREEN   = 2,
87     WRED     = 4,
88     WINTENSE = 8,
89     WCYAN    = WBLUE  | WGREEN,
90     WMAGENTA = WBLUE  | WRED,
91     WYELLOW  = WGREEN | WRED,
92     WWHITE   = WBLUE  | WGREEN | WRED
93 };
94
95 static const int ansi2win[] = {
96     WBLACK,
97     WRED,
98     WGREEN,
99     WYELLOW,
100     WBLUE,
101     WMAGENTA,
102     WCYAN,
103     WWHITE
104 };
105
106 static int win_fputs(FILE *h, const char *str) {
107     /* state for translate */
108     int acolor = 0;
109     int wcolor = 0;
110     int icolor = 0;
111     int state  = 0;
112
113     /* attributes */
114     int intense  =  -1;
115     int colors[] = {-1, -1 };
116     int colorpos = 1;
117     int length   = 0;
118     CONSOLE_SCREEN_BUFFER_INFO cinfo;
119     GetConsoleScreenBufferInfo (
120         (GMQCC_IS_STDOUT(h)) ?
121             GetStdHandle(STD_OUTPUT_HANDLE) :
122             GetStdHandle(STD_ERROR_HANDLE), &cinfo
123     );
124     icolor = cinfo.wAttributes;
125
126     while (*str) {
127         if (*str == '\x1B')
128             state = '\x1B';
129         else if (state == '\x1B' && *str == '[')
130             state = '[';
131         else if (state == '[') {
132             if (*str != 'm') {
133                 colors[colorpos] = *str;
134                 colorpos--;
135             } else {
136                 int find;
137                 int mult;
138                 for (find = colorpos + 1, acolor = 0, mult = 1; find < 2; find++) {
139                     acolor += (colors[find] - 48) * mult;
140                     mult   *= 10;
141                 }
142
143                 /* convert to windows color */
144                 if (acolor == BOLD)
145                     intense = WINTENSE;
146                 else if (acolor == RESET) {
147                     intense = WBLACK;
148                     wcolor  = icolor;
149                 }
150                 else if (BLACK <= acolor && acolor <= WHITE)
151                     wcolor = ansi2win[acolor - 30];
152                 else if (acolor == 90) {
153                     /* special gray really white man */
154                     wcolor  = WWHITE;
155                     intense = WBLACK;
156                 }
157
158                 SetConsoleTextAttribute (
159                     (GMQCC_IS_STDOUT(h)) ?
160                     GetStdHandle(STD_OUTPUT_HANDLE) :
161                     GetStdHandle(STD_ERROR_HANDLE),
162
163                     wcolor | intense | (icolor & 0xF0)
164                 );
165                 colorpos =  1;
166                 state    = -1;
167             }
168         } else {
169             fs_file_write(str, 1, 1, stdout);
170             length ++;
171         }
172         str++;
173     }
174     /* restore */
175     SetConsoleTextAttribute(
176         (GMQCC_IS_STDOUT(h)) ?
177         GetStdHandle(STD_OUTPUT_HANDLE) :
178         GetStdHandle(STD_ERROR_HANDLE),
179         icolor
180     );
181     return length;
182 }
183 #endif
184
185 /*
186  * We use standard files as default. These can be changed at any time
187  * with con_change(F, F)
188  */
189 static con_t console;
190
191 /*
192  * Enables color on output if supported.
193  * NOTE: The support for checking colors is NULL.  On windows this will
194  * always work, on *nix it depends if the term has colors.
195  *
196  * NOTE: This prevents colored output to piped stdout/err via isatty
197  * checks.
198  */
199 static void con_enablecolor(void) {
200     if (console.handle_err == stderr || console.handle_err == stdout)
201         console.color_err = !!(isatty(STDERR_FILENO));
202     if (console.handle_out == stderr || console.handle_out == stdout)
203         console.color_out = !!(isatty(STDOUT_FILENO));
204 }
205
206 /*
207  * Does a write to the handle with the format string and list of
208  * arguments.  This colorizes for windows as well via translate
209  * step.
210  */
211 static int con_write(FILE *handle, const char *fmt, va_list va) {
212     int      ln;
213     #ifndef _WIN32
214     ln = vfprintf(handle, fmt, va);
215     #else
216     {
217         char data[4096];
218         memset(data, 0, sizeof(data));
219 #ifdef _MSC_VER
220         vsnprintf_s(data, sizeof(data), sizeof(data), fmt, va);
221 #else
222         vsnprintf(data, sizeof(data), fmt, va);
223 #endif
224         ln = (GMQCC_IS_DEFINE(handle)) ? win_fputs(handle, data) : fs_file_puts(handle, data);
225     }
226     #endif
227     return ln;
228 }
229
230 /**********************************************************************
231  * EXPOSED INTERFACE BEGINS
232  *********************************************************************/
233
234 void con_close() {
235     if (!GMQCC_IS_DEFINE(console.handle_err))
236         fs_file_close(console.handle_err);
237     if (!GMQCC_IS_DEFINE(console.handle_out))
238         fs_file_close(console.handle_out);
239 }
240
241 void con_color(int state) {
242     if (state)
243         con_enablecolor();
244     else {
245         console.color_err = 0;
246         console.color_out = 0;
247     }
248 }
249
250 void con_init() {
251     console.handle_err = stderr;
252     console.handle_out = stdout;
253     con_enablecolor();
254 }
255
256 void con_reset() {
257     con_close();
258     con_init ();
259 }
260
261 /*
262  * This is clever, say you want to change the console to use two
263  * files for out/err.  You pass in two strings, it will properly
264  * close the existing handles (if they're not std* handles) and
265  * open them.  Now say you want TO use stdout and stderr, this
266  * allows you to do that so long as you cast them to (char*).
267  * Say you need stdout for out, but want a file for error, you can
268  * do this too, just cast the stdout for (char*) and stick to a
269  * string for the error file.
270  */
271 int con_change(const char *out, const char *err) {
272     con_close();
273
274     if (!out) out = (const char *)((!console.handle_out) ? stdout : console.handle_out);
275     if (!err) err = (const char *)((!console.handle_err) ? stderr : console.handle_err);
276
277     if (GMQCC_IS_DEFINE(out)) {
278         console.handle_out = GMQCC_IS_STDOUT(out) ? stdout : stderr;
279         con_enablecolor();
280     } else if (!(console.handle_out = fs_file_open(out, "w"))) return 0;
281
282     if (GMQCC_IS_DEFINE(err)) {
283         console.handle_err = GMQCC_IS_STDOUT(err) ? stdout : stderr;
284         con_enablecolor();
285     } else if (!(console.handle_err = fs_file_open(err, "w"))) return 0;
286
287     return 1;
288 }
289
290 /*
291  * Defaultizer because stdio.h shouldn't be used anywhere except here
292  * and inside file.c To prevent mis-match of wrapper-interfaces.
293  */
294 FILE *con_default_out() {
295     return (console.handle_out = stdout);
296 }
297 FILE *con_default_err() {
298     return (console.handle_err = stderr);
299 }
300
301 int con_verr(const char *fmt, va_list va) {
302     return con_write(console.handle_err, fmt, va);
303 }
304 int con_vout(const char *fmt, va_list va) {
305     return con_write(console.handle_out, fmt, va);
306 }
307
308 /*
309  * Standard stdout/stderr printf functions used generally where they need
310  * to be used.
311  */
312 int con_err(const char *fmt, ...) {
313     va_list  va;
314     int      ln = 0;
315     va_start(va, fmt);
316     con_verr(fmt, va);
317     va_end  (va);
318     return   ln;
319 }
320 int con_out(const char *fmt, ...) {
321     va_list  va;
322     int      ln = 0;
323     va_start(va, fmt);
324     con_vout(fmt, va);
325     va_end  (va);
326     return   ln;
327 }
328
329 #ifndef QCVM_EXECUTOR
330 /*
331  * Utility console message writes for lexer contexts.  These will allow
332  * for reporting of file:line based on lexer context, These are used
333  * heavily in the parser/ir/ast.
334  */
335 static void con_vprintmsg_c(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, va_list ap, const char *condname) {
336     /* color selection table */
337     static int sel[] = {
338         CON_WHITE,
339         CON_CYAN,
340         CON_RED
341     };
342
343     int  err                         = !!(level == LVL_ERROR);
344     int  color                       = (err) ? console.color_err : console.color_out;
345     int (*print) (const char *, ...)  = (err) ? &con_err          : &con_out;
346     int (*vprint)(const char *, va_list) = (err) ? &con_verr : &con_vout;
347
348     if (color)
349         print("\033[0;%dm%s:%d:%d: \033[0;%dm%s: \033[0m", CON_CYAN, name, (int)line, (int)column, sel[level], msgtype);
350     else
351         print("%s:%d:%d: %s: ", name, (int)line, (int)column, msgtype);
352
353     vprint(msg, ap);
354     if (condname)
355         print(" [%s]\n", condname);
356     else
357         print("\n");
358 }
359
360 void con_vprintmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, va_list ap) {
361     con_vprintmsg_c(level, name, line, column, msgtype, msg, ap, NULL);
362 }
363
364 void con_printmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, ...) {
365     va_list   va;
366     va_start(va, msg);
367     con_vprintmsg(level, name, line, column, msgtype, msg, va);
368     va_end  (va);
369 }
370
371 void con_cvprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, va_list ap) {
372     con_vprintmsg(lvl, ctx.file, ctx.line, ctx.column, msgtype, msg, ap);
373 }
374
375 void con_cprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, ...) {
376     va_list   va;
377     va_start(va, msg);
378     con_cvprintmsg(ctx, lvl, msgtype, msg, va);
379     va_end  (va);
380 }
381
382 /* General error interface */
383 size_t compile_errors   = 0;
384 size_t compile_warnings = 0;
385 size_t compile_Werrors  = 0;
386 static lex_ctx_t first_werror;
387
388 void compile_show_werrors()
389 {
390     con_cprintmsg(first_werror, LVL_ERROR, "first warning", "was here");
391 }
392
393 void vcompile_error(lex_ctx_t ctx, const char *msg, va_list ap)
394 {
395     ++compile_errors;
396     con_cvprintmsg(ctx, LVL_ERROR, "error", msg, ap);
397 }
398
399 void compile_error(lex_ctx_t ctx, const char *msg, ...)
400 {
401     va_list ap;
402     va_start(ap, msg);
403     vcompile_error(ctx, msg, ap);
404     va_end(ap);
405 }
406
407 bool GMQCC_WARN vcompile_warning(lex_ctx_t ctx, int warntype, const char *fmt, va_list ap)
408 {
409     const char *msgtype = "warning";
410     int         lvl     = LVL_WARNING;
411     char        warn_name[1024];
412
413     if (!OPTS_WARN(warntype))
414         return false;
415
416     warn_name[0] = '-';
417     warn_name[1] = 'W';
418     (void)util_strtononcmd(opts_warn_list[warntype].name, warn_name+2, sizeof(warn_name)-2);
419
420     ++compile_warnings;
421     if (OPTS_WERROR(warntype)) {
422         if (!compile_Werrors)
423             first_werror = ctx;
424         ++compile_Werrors;
425         msgtype = "Werror";
426         if (OPTS_FLAG(BAIL_ON_WERROR)) {
427             msgtype = "error";
428             ++compile_errors;
429         }
430         lvl = LVL_ERROR;
431     }
432
433     con_vprintmsg_c(lvl, ctx.file, ctx.line, ctx.column, msgtype, fmt, ap, warn_name);
434
435     return OPTS_WERROR(warntype) && OPTS_FLAG(BAIL_ON_WERROR);
436 }
437
438 bool GMQCC_WARN compile_warning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
439 {
440     bool r;
441     va_list ap;
442     va_start(ap, fmt);
443     r = vcompile_warning(ctx, warntype, fmt, ap);
444     va_end(ap);
445     return r;
446 }
447 #endif