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