]> git.xonotic.org Git - xonotic/gmqcc.git/blob - con.c
7406caed3fc67ab25a01bdc476645cb9b395d253
[xonotic/gmqcc.git] / con.c
1 /*
2  * Copyright (C) 2012
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 #endif
32
33 #define GMQCC_IS_STDOUT(X) ((FILE*)((void*)X) == stdout)
34 #define GMQCC_IS_STDERR(X) ((FILE*)((void*)X) == stderr)
35 #define GMQCC_IS_DEFINE(X) (GMQCC_IS_STDERR(X) || GMQCC_IS_STDOUT(X))
36
37 typedef struct {
38     FILE *handle_err;
39     FILE *handle_out;
40
41     int   color_err;
42     int   color_out;
43 } con_t;
44
45 /*
46  * Doing colored output on windows is fucking stupid.  The linux way is
47  * the real way. So we emulate it on windows :)
48  */
49 #ifdef _MSC_VER
50 #define WIN32_LEAN_AND_MEAN
51 #include <windows.h>
52
53 /*
54  * Windows doesn't have constants for FILENO, sadly but the docs tell
55  * use the constant values.
56  */
57 #undef  STDERR_FILENO
58 #undef  STDOUT_FILENO
59 #define STDERR_FILENO 2
60 #define STDOUT_FILENO 1
61
62 /*
63  * Windows and it's posix underscore bullshit.  We simply fix this
64  * with yay, another macro :P
65  */
66 #define isatty _isatty
67
68 enum {
69     RESET = 0,
70     BOLD  = 1,
71     BLACK = 30,
72     RED,
73     GREEN,
74     YELLOW,
75     BLUE,
76     MAGENTA,
77     CYAN,
78     GRAY,
79     WHITE
80 };
81
82 enum {
83     WBLACK,
84     WBLUE,
85     WGREEN   = 2,
86     WRED     = 4,
87     WINTENSE = 8,
88     WCYAN    = WBLUE  | WGREEN,
89     WMAGENTA = WBLUE  | WRED,
90     WYELLOW  = WGREEN | WRED,
91     WWHITE   = WBLUE  | WGREEN | WRED
92 }
93
94 static const ansi2win[] = {
95     WBLACK,
96     WRED,
97     WGREEN,
98     WYELLOW,
99     WBLUE,
100     WMAGENTA,
101     WCYAN,
102     WWHITE
103 };
104
105 static void win_fputs(char *str, FILE *h) {
106     /* state for translate */
107     int acolor;
108     int wcolor;
109     int icolor;
110
111     int state;
112     int place;
113
114     /* attributes */
115     int intense  =  -1;
116     int colors[] = {-1, -1 };
117     int colorpos = 1;
118
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 == '\e')
129             state = '\e';
130         else if (state == '\e' && *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                     (h == stdout) ?
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             fputc(*str, h);
171         }
172     }
173     /* restore */
174     SetConsoleTextAttribute(
175         (GMQCC_IS_STDOUT(h)) ?
176         GetStdHandle(STD_OUTPUT_HANDLE) :
177         GetStdHandle(STD_ERROR_HANDLE),
178         icolor
179     );
180 }
181 #endif
182
183 /*
184  * We use standard files as default. These can be changed at any time
185  * with con_change(F, F)
186  */
187 static con_t console;
188
189 /*
190  * Enables color on output if supported.
191  * NOTE: The support for checking colors is NULL.  On windows this will
192  * always work, on *nix it depends if the term has colors.
193  *
194  * NOTE: This prevents colored output to piped stdout/err via isatty
195  * checks.
196  */
197 static void con_enablecolor() {
198     if (console.handle_err == stderr || console.handle_err == stdout)
199         console.color_err = !!(isatty(STDERR_FILENO));
200     if (console.handle_out == stderr || console.handle_out == stdout)
201         console.color_out = !!(isatty(STDOUT_FILENO));
202 }
203
204 /*
205  * Does a write to the handle with the format string and list of
206  * arguments.  This colorizes for windows as well via translate
207  * step.
208  */
209 static int con_write(FILE *handle, const char *fmt, va_list va) {
210     int      ln;
211     #ifndef _MSC_VER
212     ln = vfprintf(handle, fmt, va);
213     #else
214     {
215         char *data = NULL;
216         ln   = _vscprintf(fmt, va);
217         data = malloc(ln + 1);
218         data[ln] = 0;
219         vsprintf(data, fmt, va);
220         if (GMQCC_IS_DEFINE(handle))
221             ln = win_fputs(data, handle);
222         else
223             ln = fputs(data, handle);
224         free(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         fclose(console.handle_err);
237     if (!GMQCC_IS_DEFINE(console.handle_out))
238         fclose(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 (GMQCC_IS_DEFINE(out)) {
275         console.handle_out = GMQCC_IS_STDOUT(out) ? stdout : stderr;
276         con_enablecolor();
277     } else if (!(console.handle_out = fopen(out, "w"))) return 0;
278
279     if (GMQCC_IS_DEFINE(err)) {
280         console.handle_err = GMQCC_IS_STDOUT(err) ? stdout : stderr;
281         con_enablecolor();
282     } else if (!(console.handle_err = fopen(err, "w"))) return 0;
283
284     /* no buffering */
285     setvbuf(console.handle_out, NULL, _IONBF, 0);
286     setvbuf(console.handle_err, NULL, _IONBF, 0);
287
288     return 1;
289 }
290
291 int con_verr(const char *fmt, va_list va) {
292     return con_write(console.handle_err, fmt, va);
293 }
294 int con_vout(const char *fmt, va_list va) {
295     return con_write(console.handle_out, fmt, va);
296 }
297
298 /*
299  * Standard stdout/stderr printf functions used generally where they need
300  * to be used.
301  */
302 int con_err(const char *fmt, ...) {
303     va_list  va;
304     int      ln = 0;
305     va_start(va, fmt);
306     con_verr(fmt, va);
307     va_end  (va);
308     return   ln;
309 }
310 int con_out(const char *fmt, ...) {
311     va_list  va;
312     int      ln = 0;
313     va_start(va, fmt);
314     con_vout(fmt, va);
315     va_end  (va);
316     return   ln;
317 }
318
319 /*
320  * Utility console message writes for lexer contexts.  These will allow
321  * for reporting of file:line based on lexer context, These are used
322  * heavily in the parser/ir/ast.
323  */
324 void con_vprintmsg_c(int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap, const char *condname) {
325     /* color selection table */
326     static int sel[] = {
327         CON_WHITE,
328         CON_CYAN,
329         CON_RED
330     };
331
332     int  err                         = !!(level == LVL_ERROR);
333     int  color                       = (err) ? console.color_err : console.color_out;
334     int (*print) (const char *, ...)  = (err) ? &con_err          : &con_out;
335     int (*vprint)(const char *, va_list) = (err) ? &con_verr : &con_vout;
336
337     if (color)
338         print("\033[0;%dm%s:%d: \033[0;%dm%s: \033[0m", CON_CYAN, name, (int)line, sel[level], msgtype);
339     else
340         print("%s:%d: %s: ", name, (int)line, msgtype);
341
342     vprint(msg, ap);
343     if (condname)
344         print(" [%s]\n", condname);
345     else
346         print("\n");
347 }
348
349 void con_vprintmsg(int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap) {
350     con_vprintmsg_c(level, name, line, msgtype, msg, ap, NULL);
351 }
352
353 void con_printmsg(int level, const char *name, size_t line, const char *msgtype, const char *msg, ...) {
354     va_list   va;
355     va_start(va, msg);
356     con_vprintmsg(level, name, line, msgtype, msg, va);
357     va_end  (va);
358 }
359
360 void con_cvprintmsg(void *ctx, int lvl, const char *msgtype, const char *msg, va_list ap) {
361     con_vprintmsg(lvl, ((lex_ctx*)ctx)->file, ((lex_ctx*)ctx)->line, msgtype, msg, ap);
362 }
363
364 void con_cprintmsg (void *ctx, int lvl, const char *msgtype, const char *msg, ...) {
365     va_list   va;
366     va_start(va, msg);
367     con_cvprintmsg(ctx, lvl, msgtype, msg, va);
368     va_end  (va);
369 }
370
371 /* General error interface */
372 size_t compile_errors = 0;
373 size_t compile_warnings = 0;
374
375 void vcompile_error(lex_ctx ctx, const char *msg, va_list ap)
376 {
377     ++compile_errors;
378     con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", msg, ap);
379 }
380
381 void compile_error(lex_ctx ctx, const char *msg, ...)
382 {
383     va_list ap;
384     va_start(ap, msg);
385     vcompile_error(ctx, msg, ap);
386     va_end(ap);
387 }
388
389 bool GMQCC_WARN vcompile_warning(lex_ctx ctx, int warntype, const char *fmt, va_list ap)
390 {
391     int lvl = LVL_WARNING;
392     char warn_name[1024];
393
394     if (!OPTS_WARN(warntype))
395         return false;
396
397     warn_name[0] = '-';
398     warn_name[1] = 'W';
399     (void)util_strtononcmd(opts_warn_list[warntype].name, warn_name+2, sizeof(warn_name)-2);
400
401     if (opts.werror) {
402         ++compile_errors;
403         lvl = LVL_ERROR;
404     }
405     else
406         ++compile_warnings;
407
408     con_vprintmsg_c(lvl, ctx.file, ctx.line, (opts.werror ? "error" : "warning"), fmt, ap, warn_name);
409
410     return opts.werror;
411 }
412
413 bool GMQCC_WARN compile_warning(lex_ctx ctx, int warntype, const char *fmt, ...)
414 {
415     bool r;
416     va_list ap;
417     va_start(ap, fmt);
418     r = vcompile_warning(ctx, warntype, fmt, ap);
419     va_end(ap);
420     return r;
421 }