]> git.xonotic.org Git - xonotic/gmqcc.git/blob - conout.c
Initial platform / compiler specific code refactoring.
[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         platform_vsnprintf(data, sizeof(data), fmt, va);
220         ln = (GMQCC_IS_DEFINE(handle)) ? win_fputs(handle, data) : fs_file_puts(handle, data);
221     }
222     #endif
223     return ln;
224 }
225
226 /**********************************************************************
227  * EXPOSED INTERFACE BEGINS
228  *********************************************************************/
229
230 void con_close() {
231     if (!GMQCC_IS_DEFINE(console.handle_err))
232         fs_file_close(console.handle_err);
233     if (!GMQCC_IS_DEFINE(console.handle_out))
234         fs_file_close(console.handle_out);
235 }
236
237 void con_color(int state) {
238     if (state)
239         con_enablecolor();
240     else {
241         console.color_err = 0;
242         console.color_out = 0;
243     }
244 }
245
246 void con_init() {
247     console.handle_err = stderr;
248     console.handle_out = stdout;
249     con_enablecolor();
250 }
251
252 void con_reset() {
253     con_close();
254     con_init ();
255 }
256
257 /*
258  * This is clever, say you want to change the console to use two
259  * files for out/err.  You pass in two strings, it will properly
260  * close the existing handles (if they're not std* handles) and
261  * open them.  Now say you want TO use stdout and stderr, this
262  * allows you to do that so long as you cast them to (char*).
263  * Say you need stdout for out, but want a file for error, you can
264  * do this too, just cast the stdout for (char*) and stick to a
265  * string for the error file.
266  */
267 int con_change(const char *out, const char *err) {
268     con_close();
269
270     if (!out) out = (const char *)((!console.handle_out) ? stdout : console.handle_out);
271     if (!err) err = (const char *)((!console.handle_err) ? stderr : console.handle_err);
272
273     if (GMQCC_IS_DEFINE(out)) {
274         console.handle_out = GMQCC_IS_STDOUT(out) ? stdout : stderr;
275         con_enablecolor();
276     } else if (!(console.handle_out = fs_file_open(out, "w"))) return 0;
277
278     if (GMQCC_IS_DEFINE(err)) {
279         console.handle_err = GMQCC_IS_STDOUT(err) ? stdout : stderr;
280         con_enablecolor();
281     } else if (!(console.handle_err = fs_file_open(err, "w"))) return 0;
282
283     return 1;
284 }
285
286 /*
287  * Defaultizer because stdio.h shouldn't be used anywhere except here
288  * and inside file.c To prevent mis-match of wrapper-interfaces.
289  */
290 FILE *con_default_out() {
291     return (console.handle_out = stdout);
292 }
293 FILE *con_default_err() {
294     return (console.handle_err = stderr);
295 }
296
297 int con_verr(const char *fmt, va_list va) {
298     return con_write(console.handle_err, fmt, va);
299 }
300 int con_vout(const char *fmt, va_list va) {
301     return con_write(console.handle_out, fmt, va);
302 }
303
304 /*
305  * Standard stdout/stderr printf functions used generally where they need
306  * to be used.
307  */
308 int con_err(const char *fmt, ...) {
309     va_list  va;
310     int      ln = 0;
311     va_start(va, fmt);
312     con_verr(fmt, va);
313     va_end  (va);
314     return   ln;
315 }
316 int con_out(const char *fmt, ...) {
317     va_list  va;
318     int      ln = 0;
319     va_start(va, fmt);
320     con_vout(fmt, va);
321     va_end  (va);
322     return   ln;
323 }
324
325 /*
326  * Utility console message writes for lexer contexts.  These will allow
327  * for reporting of file:line based on lexer context, These are used
328  * heavily in the parser/ir/ast.
329  */
330 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) {
331     /* color selection table */
332     static int sel[] = {
333         CON_WHITE,
334         CON_CYAN,
335         CON_RED
336     };
337
338     int  err                         = !!(level == LVL_ERROR);
339     int  color                       = (err) ? console.color_err : console.color_out;
340     int (*print) (const char *, ...)  = (err) ? &con_err          : &con_out;
341     int (*vprint)(const char *, va_list) = (err) ? &con_verr : &con_vout;
342
343     if (color)
344         print("\033[0;%dm%s:%d:%d: \033[0;%dm%s: \033[0m", CON_CYAN, name, (int)line, (int)column, sel[level], msgtype);
345     else
346         print("%s:%d:%d: %s: ", name, (int)line, (int)column, msgtype);
347
348     vprint(msg, ap);
349     if (condname)
350         print(" [%s]\n", condname);
351     else
352         print("\n");
353 }
354
355 void con_vprintmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, va_list ap) {
356     con_vprintmsg_c(level, name, line, column, msgtype, msg, ap, NULL);
357 }
358
359 void con_printmsg(int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, ...) {
360     va_list   va;
361     va_start(va, msg);
362     con_vprintmsg(level, name, line, column, msgtype, msg, va);
363     va_end  (va);
364 }
365
366 void con_cvprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, va_list ap) {
367     con_vprintmsg(lvl, ctx.file, ctx.line, ctx.column, msgtype, msg, ap);
368 }
369
370 void con_cprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, ...) {
371     va_list   va;
372     va_start(va, msg);
373     con_cvprintmsg(ctx, lvl, msgtype, msg, va);
374     va_end  (va);
375 }
376
377 #ifndef QCVM_EXECUTOR
378 /* General error interface */
379 size_t compile_errors   = 0;
380 size_t compile_warnings = 0;
381 size_t compile_Werrors  = 0;
382 static lex_ctx_t first_werror;
383
384 void compile_show_werrors()
385 {
386     con_cprintmsg(first_werror, LVL_ERROR, "first warning", "was here");
387 }
388
389 void vcompile_error(lex_ctx_t ctx, const char *msg, va_list ap)
390 {
391     ++compile_errors;
392     con_cvprintmsg(ctx, LVL_ERROR, "error", msg, ap);
393 }
394
395 void compile_error(lex_ctx_t ctx, const char *msg, ...)
396 {
397     va_list ap;
398     va_start(ap, msg);
399     vcompile_error(ctx, msg, ap);
400     va_end(ap);
401 }
402
403 bool GMQCC_WARN vcompile_warning(lex_ctx_t ctx, int warntype, const char *fmt, va_list ap)
404 {
405     const char *msgtype = "warning";
406     int         lvl     = LVL_WARNING;
407     char        warn_name[1024];
408
409     if (!OPTS_WARN(warntype))
410         return false;
411
412     warn_name[0] = '-';
413     warn_name[1] = 'W';
414     (void)util_strtononcmd(opts_warn_list[warntype].name, warn_name+2, sizeof(warn_name)-2);
415
416     ++compile_warnings;
417     if (OPTS_WERROR(warntype)) {
418         if (!compile_Werrors)
419             first_werror = ctx;
420         ++compile_Werrors;
421         msgtype = "Werror";
422         if (OPTS_FLAG(BAIL_ON_WERROR)) {
423             msgtype = "error";
424             ++compile_errors;
425         }
426         lvl = LVL_ERROR;
427     }
428
429     con_vprintmsg_c(lvl, ctx.file, ctx.line, ctx.column, msgtype, fmt, ap, warn_name);
430
431     return OPTS_WERROR(warntype) && OPTS_FLAG(BAIL_ON_WERROR);
432 }
433
434 bool GMQCC_WARN compile_warning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
435 {
436     bool r;
437     va_list ap;
438     va_start(ap, fmt);
439     r = vcompile_warning(ctx, warntype, fmt, ap);
440     va_end(ap);
441     return r;
442 }
443 #endif