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