]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - conout.c
Use the _t consistency naming scheme. Also various 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;
109     int wcolor;
110     int icolor;
111
112     int state = 0;
113
114     /* attributes */
115     int intense  =  -1;
116     int colors[] = {-1, -1 };
117     int colorpos = 1;
118     int length   = 0;
119     CONSOLE_SCREEN_BUFFER_INFO cinfo;
120     GetConsoleScreenBufferInfo (
121         (GMQCC_IS_STDOUT(h)) ?
122             GetStdHandle(STD_OUTPUT_HANDLE) :
123             GetStdHandle(STD_ERROR_HANDLE), &cinfo
124     );
125     icolor = cinfo.wAttributes;
126
127     while (*str) {
128         if (*str == '\x1B')
129             state = '\x1B';
130         else if (state == '\x1B' && *str == '[')
131             state = '[';
132         else if (state == '[') {
133             if (*str != 'm') {
134                 colors[colorpos] = *str;
135                 colorpos--;
136             } else {
137                 int find;
138                 int mult;
139                 for (find = colorpos + 1, acolor = 0, mult = 1; find < 2; find++) {
140                     acolor += (colors[find] - 48) * mult;
141                     mult   *= 10;
142                 }
143
144                 /* convert to windows color */
145                 if (acolor == BOLD)
146                     intense = WINTENSE;
147                 else if (acolor == RESET) {
148                     intense = WBLACK;
149                     wcolor  = icolor;
150                 }
151                 else if (BLACK <= acolor && acolor <= WHITE)
152                     wcolor = ansi2win[acolor - 30];
153                 else if (acolor == 90) {
154                     /* special gray really white man */
155                     wcolor  = WWHITE;
156                     intense = WBLACK;
157                 }
158
159                 SetConsoleTextAttribute (
160                     (GMQCC_IS_STDOUT(h)) ?
161                     GetStdHandle(STD_OUTPUT_HANDLE) :
162                     GetStdHandle(STD_ERROR_HANDLE),
163
164                     wcolor | intense | (icolor & 0xF0)
165                 );
166                 colorpos =  1;
167                 state    = -1;
168             }
169         } else {
170             fs_file_write(str, 1, 1, stdout);
171             length ++;
172         }
173         str++;
174     }
175     /* restore */
176     SetConsoleTextAttribute(
177         (GMQCC_IS_STDOUT(h)) ?
178         GetStdHandle(STD_OUTPUT_HANDLE) :
179         GetStdHandle(STD_ERROR_HANDLE),
180         icolor
181     );
182     return length;
183 }
184 #endif
185
186 /*
187  * We use standard files as default. These can be changed at any time
188  * with con_change(F, F)
189  */
190 static con_t console;
191
192 /*
193  * Enables color on output if supported.
194  * NOTE: The support for checking colors is NULL.  On windows this will
195  * always work, on *nix it depends if the term has colors.
196  *
197  * NOTE: This prevents colored output to piped stdout/err via isatty
198  * checks.
199  */
200 static void con_enablecolor(void) {
201     if (console.handle_err == stderr || console.handle_err == stdout)
202         console.color_err = !!(isatty(STDERR_FILENO));
203     if (console.handle_out == stderr || console.handle_out == stdout)
204         console.color_out = !!(isatty(STDOUT_FILENO));
205 }
206
207 /*
208  * Does a write to the handle with the format string and list of
209  * arguments.  This colorizes for windows as well via translate
210  * step.
211  */
212 static int con_write(FILE *handle, const char *fmt, va_list va) {
213     int      ln;
214     #ifndef _WIN32
215     ln = vfprintf(handle, fmt, va);
216     #else
217     {
218         char data[4096];
219         memset(data, 0, sizeof(data));
220 #ifdef _MSC_VER
221         vsnprintf_s(data, sizeof(data), sizeof(data), fmt, va);
222 #else
223         vsnprintf(data, sizeof(data), fmt, va);
224 #endif
225         ln = (GMQCC_IS_DEFINE(handle)) ? win_fputs(handle, data) : fs_file_puts(handle, data);
226     }
227     #endif
228     return ln;
229 }
230
231 /**********************************************************************
232  * EXPOSED INTERFACE BEGINS
233  *********************************************************************/
234
235 void con_close() {
236     if (!GMQCC_IS_DEFINE(console.handle_err))
237         fs_file_close(console.handle_err);
238     if (!GMQCC_IS_DEFINE(console.handle_out))
239         fs_file_close(console.handle_out);
240 }
241
242 void con_color(int state) {
243     if (state)
244         con_enablecolor();
245     else {
246         console.color_err = 0;
247         console.color_out = 0;
248     }
249 }
250
251 void con_init() {
252     console.handle_err = stderr;
253     console.handle_out = stdout;
254     con_enablecolor();
255 }
256
257 void con_reset() {
258     con_close();
259     con_init ();
260 }
261
262 /*
263  * This is clever, say you want to change the console to use two
264  * files for out/err.  You pass in two strings, it will properly
265  * close the existing handles (if they're not std* handles) and
266  * open them.  Now say you want TO use stdout and stderr, this
267  * allows you to do that so long as you cast them to (char*).
268  * Say you need stdout for out, but want a file for error, you can
269  * do this too, just cast the stdout for (char*) and stick to a
270  * string for the error file.
271  */
272 int con_change(const char *out, const char *err) {
273     con_close();
274
275     if (!out) out = (const char *)((!console.handle_out) ? stdout : console.handle_out);
276     if (!err) err = (const char *)((!console.handle_err) ? stderr : console.handle_err);
277
278     if (GMQCC_IS_DEFINE(out)) {
279         console.handle_out = GMQCC_IS_STDOUT(out) ? stdout : stderr;
280         con_enablecolor();
281     } else if (!(console.handle_out = fs_file_open(out, "w"))) return 0;
282
283     if (GMQCC_IS_DEFINE(err)) {
284         console.handle_err = GMQCC_IS_STDOUT(err) ? stdout : stderr;
285         con_enablecolor();
286     } else if (!(console.handle_err = fs_file_open(err, "w"))) return 0;
287
288     return 1;
289 }
290
291 /*
292  * Defaultizer because stdio.h shouldn't be used anywhere except here
293  * and inside file.c To prevent mis-match of wrapper-interfaces.
294  */
295 FILE *con_default_out() {
296     return (console.handle_out = stdout);
297 }
298 FILE *con_default_err() {
299     return (console.handle_err = stderr);
300 }
301
302 int con_verr(const char *fmt, va_list va) {
303     return con_write(console.handle_err, fmt, va);
304 }
305 int con_vout(const char *fmt, va_list va) {
306     return con_write(console.handle_out, fmt, va);
307 }
308
309 /*
310  * Standard stdout/stderr printf functions used generally where they need
311  * to be used.
312  */
313 int con_err(const char *fmt, ...) {
314     va_list  va;
315     int      ln = 0;
316     va_start(va, fmt);
317     con_verr(fmt, va);
318     va_end  (va);
319     return   ln;
320 }
321 int con_out(const char *fmt, ...) {
322     va_list  va;
323     int      ln = 0;
324     va_start(va, fmt);
325     con_vout(fmt, va);
326     va_end  (va);
327     return   ln;
328 }
329
330 #ifndef QCVM_EXECUTOR
331 /*
332  * Utility console message writes for lexer contexts.  These will allow
333  * for reporting of file:line based on lexer context, These are used
334  * heavily in the parser/ir/ast.
335  */
336 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) {
337     /* color selection table */
338     static int sel[] = {
339         CON_WHITE,
340         CON_CYAN,
341         CON_RED
342     };
343
344     int  err                         = !!(level == LVL_ERROR);
345     int  color                       = (err) ? console.color_err : console.color_out;
346     int (*print) (const char *, ...)  = (err) ? &con_err          : &con_out;
347     int (*vprint)(const char *, va_list) = (err) ? &con_verr : &con_vout;
348
349     if (color)
350         print("\033[0;%dm%s:%d:%d: \033[0;%dm%s: \033[0m", CON_CYAN, name, (int)line, (int)column, sel[level], msgtype);
351     else
352         print("%s:%d:%d: %s: ", name, (int)line, (int)column, msgtype);
353
354     vprint(msg, ap);
355     if (condname)
356         print(" [%s]\n", condname);
357     else
358         print("\n");
359 }
360
361 void con_vprintmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, va_list ap) {
362     con_vprintmsg_c(level, name, line, column, msgtype, msg, ap, NULL);
363 }
364
365 void con_printmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, ...) {
366     va_list   va;
367     va_start(va, msg);
368     con_vprintmsg(level, name, line, column, msgtype, msg, va);
369     va_end  (va);
370 }
371
372 void con_cvprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, va_list ap) {
373     con_vprintmsg(lvl, ctx.file, ctx.line, ctx.column, msgtype, msg, ap);
374 }
375
376 void con_cprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, ...) {
377     va_list   va;
378     va_start(va, msg);
379     con_cvprintmsg(ctx, lvl, msgtype, msg, va);
380     va_end  (va);
381 }
382
383 /* General error interface */
384 size_t compile_errors   = 0;
385 size_t compile_warnings = 0;
386 size_t compile_Werrors  = 0;
387 static lex_ctx_t first_werror;
388
389 void compile_show_werrors()
390 {
391     con_cprintmsg(first_werror, LVL_ERROR, "first warning", "was here");
392 }
393
394 void vcompile_error(lex_ctx_t ctx, const char *msg, va_list ap)
395 {
396     ++compile_errors;
397     con_cvprintmsg(ctx, LVL_ERROR, "error", msg, ap);
398 }
399
400 void compile_error(lex_ctx_t ctx, const char *msg, ...)
401 {
402     va_list ap;
403     va_start(ap, msg);
404     vcompile_error(ctx, msg, ap);
405     va_end(ap);
406 }
407
408 bool GMQCC_WARN vcompile_warning(lex_ctx_t ctx, int warntype, const char *fmt, va_list ap)
409 {
410     const char *msgtype = "warning";
411     int         lvl     = LVL_WARNING;
412     char        warn_name[1024];
413
414     if (!OPTS_WARN(warntype))
415         return false;
416
417     warn_name[0] = '-';
418     warn_name[1] = 'W';
419     (void)util_strtononcmd(opts_warn_list[warntype].name, warn_name+2, sizeof(warn_name)-2);
420
421     ++compile_warnings;
422     if (OPTS_WERROR(warntype)) {
423         if (!compile_Werrors)
424             first_werror = ctx;
425         ++compile_Werrors;
426         msgtype = "Werror";
427         if (OPTS_FLAG(BAIL_ON_WERROR)) {
428             msgtype = "error";
429             ++compile_errors;
430         }
431         lvl = LVL_ERROR;
432     }
433
434     con_vprintmsg_c(lvl, ctx.file, ctx.line, ctx.column, msgtype, fmt, ap, warn_name);
435
436     return OPTS_WERROR(warntype) && OPTS_FLAG(BAIL_ON_WERROR);
437 }
438
439 bool GMQCC_WARN compile_warning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
440 {
441     bool r;
442     va_list ap;
443     va_start(ap, fmt);
444     r = vcompile_warning(ctx, warntype, fmt, ap);
445     va_end(ap);
446     return r;
447 }
448 #endif