]> git.xonotic.org Git - xonotic/gmqcc.git/blob - con.c
Add whitespace to ternary-fte template so it matches (expected behaviour)
[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 uint32_t    opts_warn [1 + (COUNT_WARNINGS / 32)];
26 bool        opts_werror   = false;
27
28 /*
29  * isatty/STDERR_FILENO/STDOUT_FILNO
30  * + some other things likewise.
31  */
32 #ifndef _WIN32
33 #include <unistd.h>
34 #endif
35
36 #define GMQCC_IS_STDOUT(X) ((FILE*)((void*)X) == stdout)
37 #define GMQCC_IS_STDERR(X) ((FILE*)((void*)X) == stderr)
38 #define GMQCC_IS_DEFINE(X) (GMQCC_IS_STDERR(X) || GMQCC_IS_STDOUT(X))
39
40 typedef struct {
41     FILE *handle_err;
42     FILE *handle_out;
43
44     int   color_err;
45     int   color_out;
46 } con_t;
47
48 /*
49  * Doing colored output on windows is fucking stupid.  The linux way is
50  * the real way. So we emulate it on windows :)
51  */
52 #ifdef _WIN32
53 #define WIN32_LEAN_AND_MEAN
54 #include <windows.h>
55
56 /*
57  * Windows doesn't have constants for FILENO, sadly but the docs tell
58  * use the constant values.
59  */
60 #undef  STDERR_FILENO
61 #undef  STDOUT_FILENO
62 #define STDERR_FILENO 2
63 #define STDOUT_FILENO 1
64
65 /*
66  * Windows and it's posix underscore bullshit.  We simply fix this
67  * with yay, another macro :P
68  */
69 #define isatty _isatty
70
71 enum {
72     RESET = 0,
73     BOLD  = 1,
74     BLACK = 30,
75     RED,
76     GREEN,
77     YELLOW,
78     BLUE,
79     MAGENTA,
80     CYAN,
81     GRAY,
82     WHITE
83 };
84
85 enum {
86     WBLACK,
87     WBLUE,
88     WGREEN   = 2,
89     WRED     = 4,
90     WINTENSE = 8,
91     WCYAN    = WBLUE  | WGREEN,
92     WMAGENTA = WBLUE  | WRED,
93     WYELLOW  = WGREEN | WRED,
94     WWHITE   = WBLUE  | WGREEN | WRED
95 }
96
97 static const ansi2win[] = {
98     WBLACK,
99     WRED,
100     WGREEN,
101     WYELLOW,
102     WBLUE,
103     WMAGENTA,
104     WCYAN,
105     WWHITE
106 };
107
108 static void win_fputs(char *str, FILE *f) {
109     /* state for translate */
110     int acolor;
111     int wcolor;
112     int icolor;
113
114     int state;
115     int place;
116
117     /* attributes */
118     int intense  =  -1;
119     int colors[] = {-1, -1 };
120     int colorpos = 1;
121
122     CONSOLE_SCREEN_BUFFER_INFO cinfo;
123     GetConsoleScreenBufferInfo(
124         (GMQCC_IS_STDOUT(h)) ?
125             GetStdHandle(STD_OUTPUT_HANDLE) :
126             GetStdHandle(STD_ERROR_HANDLE), &cinfo
127     );
128     icolor = cinfo.wAttributes;
129
130     while (*str) {
131         if (*str == '\e')
132             state = '\e';
133         else if (state == '\e' && *str == '[')
134             state = '[';
135         else if (state == '[') {
136             if (*str != 'm') {
137                 colors[colorpos] = *str;
138                 colorpos--;
139             } else {
140                 int find;
141                 int mult;
142                 for (find = colorpos + 1, acolor = 0, mult = 1; find < 2; find++) {
143                     acolor += (colors[find] - 48) * mult;
144                     mult   *= 10;
145                 }
146
147                 /* convert to windows color */
148                 if (acolor == BOLD)
149                     intense = WINTENSE;
150                 else if (acolor == RESET) {
151                     intense = WBLACK;
152                     wcolor  = icolor;
153                 }
154                 else if (BLACK < acolor && acolor <= WHITE)
155                     wcolor = ansi2win[acolor - 30];
156                 else if (acolor == 90) {
157                     /* special gray really white man */
158                     wcolor  = WWHITE;
159                     intense = WBLACK;
160                 }
161
162                 SetConsoleTextattribute(
163                     (h == stdout) ?
164                     GetStdHandle(STD_OUTPUT_HANDLE) :
165                     GetStdHandle(STD_ERROR_HANDLE),
166
167                     wcolor | intense | (icolor & 0xF0)
168                 );
169                 colorpos =  1;
170                 state    = -1;
171             }
172         } else {
173             fputc(*str, h);
174         }
175     }
176     /* restore */
177     SetConsoleTextAttribute(
178         (GMQCC_IS_STDOUT(h)) ?
179         GetStdHandle(STD_OUTPUT_HANDLE) :
180         GetStdHandle(STD_ERROR_HANDLE),
181         icolor
182     );
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() {
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 = NULL;
219         ln   = _vscprintf(fmt, va);
220         data = malloc(ln + 1);
221         data[ln] = 0;
222         vsprintf(data, fmt, va);
223         if (GMQCC_IS_DEFINE(handle))
224             ln = win_fputs(data, handle);
225         else
226             ln = fputs(data, handle);
227         free(data);
228     }
229     #endif
230     return ln;
231 }
232
233 /**********************************************************************
234  * EXPOSED INTERFACE BEGINS
235  *********************************************************************/
236
237 void con_close() {
238     if (!GMQCC_IS_DEFINE(console.handle_err))
239         fclose(console.handle_err);
240     if (!GMQCC_IS_DEFINE(console.handle_out))
241         fclose(console.handle_out);
242 }
243
244 void con_color(int state) {
245     if (state)
246         con_enablecolor();
247     else {
248         console.color_err = 0;
249         console.color_out = 0;
250     }
251 }
252
253 void con_init() {
254     console.handle_err = stderr;
255     console.handle_out = stdout;
256     con_enablecolor();
257 }
258
259 void con_reset() {
260     con_close();
261     con_init ();
262 }
263
264 /*
265  * This is clever, say you want to change the console to use two
266  * files for out/err.  You pass in two strings, it will properly
267  * close the existing handles (if they're not std* handles) and
268  * open them.  Now say you want TO use stdout and stderr, this
269  * allows you to do that so long as you cast them to (char*).
270  * Say you need stdout for out, but want a file for error, you can
271  * do this too, just cast the stdout for (char*) and stick to a
272  * string for the error file.
273  */
274 int con_change(const char *out, const char *err) {
275     con_close();
276
277     if (GMQCC_IS_DEFINE(out)) {
278         console.handle_out = GMQCC_IS_STDOUT(out) ? stdout : stderr;
279         con_enablecolor();
280     } else if (!(console.handle_out = fopen(out, "w"))) return 0;
281
282     if (GMQCC_IS_DEFINE(err)) {
283         console.handle_err = GMQCC_IS_STDOUT(err) ? stdout : stderr;
284         con_enablecolor();
285     } else if (!(console.handle_err = fopen(err, "w"))) return 0;
286
287     /* no buffering */
288     setvbuf(console.handle_out, NULL, _IONBF, 0);
289     setvbuf(console.handle_err, NULL, _IONBF, 0);
290
291     return 1;
292 }
293
294 int con_verr(const char *fmt, va_list va) {
295     return con_write(console.handle_err, fmt, va);
296 }
297 int con_vout(const char *fmt, va_list va) {
298     return con_write(console.handle_out, fmt, va);
299 }
300
301 /*
302  * Standard stdout/stderr printf functions used generally where they need
303  * to be used.
304  */
305 int con_err(const char *fmt, ...) {
306     va_list  va;
307     int      ln = 0;
308     va_start(va, fmt);
309     con_verr(fmt, va);
310     va_end  (va);
311     return   ln;
312 }
313 int con_out(const char *fmt, ...) {
314     va_list  va;
315     int      ln = 0;
316     va_start(va, fmt);
317     con_vout(fmt, va);
318     va_end  (va);
319     return   ln;
320 }
321
322 /*
323  * Utility console message writes for lexer contexts.  These will allow
324  * for reporting of file:line based on lexer context, These are used
325  * heavily in the parser/ir/ast.
326  */
327 void con_vprintmsg(int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap) {
328     /* color selection table */
329     static int sel[] = {
330         CON_WHITE,
331         CON_CYAN,
332         CON_RED
333     };
334
335     int  err                         = !!(level == LVL_ERROR);
336     int  color                       = (err) ? console.color_err : console.color_out;
337     int (*print)(const char *, ...)  = (err) ? &con_err          : &con_out;
338     int (*vprint)(const char *, va_list) = (err) ? &con_verr : &con_vout;
339
340     if (color)
341         print("\033[0;%dm%s:%d: \033[0;%dm%s: \033[0m", CON_CYAN, name, (int)line, sel[level], msgtype);
342     else
343         print("%s:%d: %s: ", name, (int)line, msgtype);
344
345     vprint(msg, ap);
346     print("\n");
347 }
348
349 void con_printmsg(int level, const char *name, size_t line, const char *msgtype, const char *msg, ...) {
350     va_list   va;
351     va_start(va, msg);
352     con_vprintmsg(level, name, line, msgtype, msg, va);
353     va_end  (va);
354 }
355
356 void con_cvprintmsg(void *ctx, int lvl, const char *msgtype, const char *msg, va_list ap) {
357     con_vprintmsg(lvl, ((lex_ctx*)ctx)->file, ((lex_ctx*)ctx)->line, msgtype, msg, ap);
358 }
359
360 void con_cprintmsg (void *ctx, int lvl, const char *msgtype, const char *msg, ...) {
361     va_list   va;
362     va_start(va, msg);
363     con_cvprintmsg(ctx, lvl, msgtype, msg, va);
364     va_end  (va);
365 }
366
367 /* General error interface */
368 size_t compile_errors = 0;
369 size_t compile_warnings = 0;
370
371 void compile_error(lex_ctx ctx, const char *msg, ...)
372 {
373     va_list ap;
374     ++compile_errors;
375     va_start(ap, msg);
376     con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", msg, ap);
377     va_end(ap);
378 }
379
380 bool GMQCC_WARN compile_warning(lex_ctx ctx, int warntype, const char *fmt, ...)
381 {
382     va_list ap;
383     int lvl = LVL_WARNING;
384
385     if (!OPTS_WARN(warntype))
386         return false;
387
388     if (opts_werror) {
389         ++compile_errors;
390         lvl = LVL_ERROR;
391     }
392     else
393         ++compile_warnings;
394
395     va_start(ap, fmt);
396     con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
397     va_end(ap);
398
399     return opts_werror;
400 }