]> git.xonotic.org Git - xonotic/gmqcc.git/blob - asm.c
Trailing whitespace was imminent, pending editor configuration change to accomodate...
[xonotic/gmqcc.git] / asm.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  * Following parse states:
26  *     ASM_FUNCTION -- in a function accepting input statements
27  *     ....
28  */
29 typedef enum {
30     ASM_NULL,
31     ASM_FUNCTION
32 } asm_state;
33
34 typedef struct {
35     char *name;   /* name of constant    */
36     char  type;   /* type, float, vector, string */
37     char  elem;   /* 0=x, 1=y, or 2=Z?   */
38     int   offset; /* location in globals */
39 } globals;
40 VECTOR_MAKE(globals, assembly_constants);
41
42 /*
43  * Assembly text processing: this handles the internal collection
44  * of text to allow parsing and assemblation.
45  */
46 static char *const asm_getline(size_t *byte, FILE *fp) {
47     char   *line = NULL;
48     size_t  read = util_getline(&line, byte, fp);
49     *byte = read;
50     if (read == -1) {
51         mem_d (line);
52         return NULL;
53     }
54     return line;
55 }
56
57 /*
58  * Entire external interface for main.c - to perform actual assemblation
59  * of assembly files.
60  */
61 void asm_init(const char *file, FILE **fp) {
62     *fp = fopen(file, "r");
63     code_init();
64 }
65 void asm_close(FILE *fp) {
66     fclose(fp);
67     code_write();
68 }
69 void asm_clear() {
70     size_t i = 0;
71     for (; i < assembly_constants_elements; i++)
72         mem_d(assembly_constants_data[i].name);
73     mem_d(assembly_constants_data);
74 }
75
76 /*
77  * Dumps all values of all constants and assembly related
78  * information obtained during the assembly procedure.
79  */
80 void asm_dumps() {
81     size_t i = 0;
82     for (; i < assembly_constants_elements; i++) {
83         globals *g = &assembly_constants_data[i];
84         switch (g->type) {
85             case TYPE_VECTOR: {
86                 util_debug("ASM", "vector %s %c[%f]\n", g->name,
87                     (g->elem == 0) ? 'X' :(
88                     (g->elem == 1) ? 'Y' :
89                     (g->elem == 2) ? 'Z' :' '),
90                     INT2FLT(code_globals_data[g->offset])
91                 );
92                 break;
93             }
94         }
95     }
96 }
97
98 /*
99  * Parses a type, could be global or not depending on the
100  * assembly state: global scope with assignments are constants.
101  * globals with no assignments are globals.  Function body types
102  * are locals.
103  */
104 static GMQCC_INLINE bool asm_parse_type(const char *skip, size_t line, asm_state *state) {
105     if (!(strstr(skip, "FLOAT:")  == &skip[0]) &&
106          (strstr(skip, "VECTOR:") == &skip[0]) &&
107          (strstr(skip, "ENTITY:") == &skip[0]) &&
108          (strstr(skip, "FIELD:")  == &skip[0]) &&
109          (strstr(skip, "STRING:") == &skip[0])) return false;
110
111     /* TODO: determine if constant, global, or local */
112     switch (*skip) {
113         /* VECTOR */ case 'V': {
114             float   val1;
115             float   val2;
116             float   val3;
117             globals global;
118
119             char *find = (char*)skip + 7;
120             char *name = (char*)skip + 7;
121             while (*find == ' ' || *find == '\t') find++;
122
123             /* constant? */
124             if (strchr(find, ',')) {
125                 /* strip name */
126                 *strchr((name = util_strdup(find)), ',')='\0';
127                 /* find data  */
128                 find += strlen(name) + 1;
129                 while (*find == ' ' || *find == '\t') find++;
130                 /* valid name */
131                 if (util_strupper(name) || isdigit(*name)) {
132                     printf("invalid name for vector variable\n");
133                     mem_d(name);
134                 }
135                 /*
136                  * Parse all three elements of the vector.  This will only
137                  * pass the first try if we hit a constant, otherwise it's
138                  * a global.
139                  */
140                 #define PARSE_ELEMENT(X,Y,Z)                    \
141                     if (isdigit(*X)  || *X == '-'||*X == '+') { \
142                         bool negated = (*X == '-');             \
143                         if  (negated || *X == '+')   { X++; }   \
144                         Y = (negated)?-atof(X):atof(X);         \
145                         X = strchr(X, ',');                     \
146                         Z                                       \
147                     }
148
149                 PARSE_ELEMENT(find, val1, { find ++; while (*find == ' ') { find ++; } });
150                 PARSE_ELEMENT(find, val2, { find ++; while (*find == ' ') { find ++; } });
151                 PARSE_ELEMENT(find, val3, { find ++; /* no need to do anything here */ });
152                 #undef  PARSE_ELEMENT
153                 #define BUILD_ELEMENT(X,Y)                 \
154                     global.type   = TYPE_VECTOR;           \
155                     global.name   = util_strdup(name);     \
156                     global.elem   = (X);                   \
157                     global.offset = code_globals_elements; \
158                     assembly_constants_add(global);        \
159                     code_globals_add(FLT2INT(Y))
160                 BUILD_ELEMENT(0, val1);
161                 BUILD_ELEMENT(1, val2);
162                 BUILD_ELEMENT(2, val3);
163                 #undef  BUILD_ELEMENT
164                 mem_d(name);
165             } else {
166                 /* TODO global not constant */
167             }
168             break;
169         }
170         /* ENTITY */ case 'E': {
171             const char *find = skip + 7;
172             while (*find == ' ' || *find == '\t') find++;
173             printf("found ENTITY %s\n", find);
174             break;
175         }
176         /* STRING */ case 'S': {
177             const char *find = skip + 7;
178             while (*find == ' ' || *find == '\t') find++;
179             printf("found STRING %s\n", find);
180             break;
181         }
182     }
183
184     return false;
185 }
186
187 /*
188  * Parses a function: trivial case, handles occurances of duplicated
189  * names among other things.  Ensures valid name as well, and even
190  * internal engine function selection.
191  */
192 static GMQCC_INLINE bool asm_parse_func(const char *skip, size_t line, asm_state *state) {
193     if (*state == ASM_FUNCTION)
194         return false;
195
196     if (strstr(skip, "FUNCTION:") == &skip[0]) {
197         char  *copy = util_strsws(skip+10);
198         char  *name = util_strchp(copy, strchr(copy, '\0'));
199
200         /* TODO: failure system, missing name */
201         if (!name) {
202             printf("expected name on function\n");
203             mem_d(copy);
204             mem_d(name);
205             return false;
206         }
207         /* TODO: failure system, invalid name */
208         if (!isalpha(*name) || util_strupper(name)) {
209             printf("invalid identifer for function name\n");
210             mem_d(copy);
211             mem_d(name);
212             return false;
213         }
214
215         /*
216          * Function could be internal function, look for $
217          * to determine this.
218          */
219         if (strchr(name, ',')) {
220             prog_section_function function;
221             prog_section_def      def;
222
223             char *find = strchr(name, ',') + 1;
224
225             /* skip whitespace */
226             while (*find == ' ' || *find == '\t')
227                 find++;
228
229             if (*find != '$') {
230                 printf("expected $ for internal function selection, got %s instead\n", find);
231                 mem_d(copy);
232                 mem_d(name);
233                 return false;
234             }
235             find ++;
236             if (!isdigit(*find)) {
237                 printf("invalid internal identifier, expected valid number\n");
238                 mem_d(copy);
239                 mem_d(name);
240                 return false;
241             }
242             *strchr(name, ',')='\0';
243
244             /*
245              * Now add the following items to the code system:
246              *  function
247              *  definition (optional)
248              *  global     (optional)
249              *  name
250              */
251             function.entry      = -atoi(find);
252             function.firstlocal = 0;
253             function.locals     = 0;
254             function.profile    = 0;
255             function.name       = code_chars_elements;
256             function.file       = 0;
257             function.nargs      = 0;
258             def.type            = TYPE_FUNCTION;
259             def.offset          = code_globals_elements;
260             def.name            = code_chars_elements;
261             memset(function.argsize, 0, sizeof(function.argsize));
262             code_functions_add(function);
263             code_defs_add     (def);
264             code_chars_put    (name, strlen(name));
265             code_chars_add    ('\0');
266
267             util_debug("ASM", "added internal function %s to function table\n", name);
268
269             /*
270              * Sanatize the numerical constant used to select the
271              * internal function.  Must ensure it's all numeric, since
272              * atoi can silently drop characters from a string and still
273              * produce a valid constant that would lead to runtime problems.
274              */
275             if (util_strdigit(find))
276                 util_debug("ASM", "found internal function %s, -%d\n", name, atoi(find));
277             else
278                 printf("invalid internal function identifier, must be all numeric\n");
279
280         } else {
281             /*
282              * The function isn't an internal one. Determine the name and
283              * amount of arguments the function accepts by searching for
284              * the `#` (pound sign).
285              */
286             int   args = 0;
287             int   size = 0;
288             char *find = strchr(name, '#');
289             char *peek = find;
290
291             /*
292              * Code structures for filling after determining the correct
293              * information to add to the code write system.
294              */
295             prog_section_function function;
296             prog_section_def      def;
297             if (find) {
298                 find ++;
299
300                 /* skip whitespace */
301                 if (*find == ' ' || *find == '\t')
302                     find++;
303
304                 /*
305                  * If the input is larger than eight, it's considered
306                  * invalid and shouldn't be allowed.  The QuakeC VM only
307                  * allows a maximum of eight arguments.
308                  */
309                 if (*find == '9') {
310                     printf("invalid number of arguments, must be a valid number from 0-8\n");
311                     mem_d(copy);
312                     mem_d(name);
313                     return false;
314                 }
315
316                 if (*find != '0') {
317                     /*
318                      * if we made it this far we have a valid number for the
319                      * argument count, so fall through a switch statement and
320                      * do it.
321                      */
322                     switch (*find) {
323                         case '8': args++; case '7': args++;
324                         case '6': args++; case '5': args++;
325                         case '4': args++; case '3': args++;
326                         case '2': args++; case '1': args++;
327                     }
328                 }
329                 /*
330                  * We need to parse the argument size now by determining
331                  * the argument identifer list used after the amount of
332                  * arguments.
333                  */
334                 memset(function.argsize, 0, sizeof(function.argsize));
335                 find ++; /* skip the number */
336                 while (*find == ' ' || *find == '\t') find++;
337                 while (size < args) {
338                     switch (*find) {
339                         case 'V': case 'v': function.argsize[size]=3; break;
340                         case 'S': case 's':
341                         case 'F': case 'f':
342                         case 'E': case 'e': function.argsize[size]=1; break;
343                         case '\0':
344                             printf("missing argument identifer, expected %d\n", args);
345                             return false;
346                         default:
347                             printf("error invalid function argument identifier\n");
348                             return false;
349                     }
350                     size++,find++;
351                 }
352                 while (*find == ' ' || *find == '\t') find++;
353                 if (*find != '\0') {
354                     printf("too many function argument identifers expected %d\n", args);
355                     return false;
356                 }
357             } else {
358                 printf("missing number of argument count in function %s\n", name);
359                 return false;
360             }
361
362             /*
363              * Now we need to strip the name apart into it's exact size
364              * by working in the peek buffer till we hit the name again.
365              */
366             if (*peek == '#') {
367                 peek --; /* '#'    */
368                 peek --; /* number */
369             }
370             while (*peek == ' ' || *peek == '\t') peek--;
371
372             /*
373              * We're guranteed to be exactly where we need to be in the
374              * peek buffer to null terminate and get our name from name
375              * without any garbage before or after it.
376              */
377             *++peek='\0';
378
379             /*
380              * We got valid function structure information now. Lets add
381              * the function to the code writer function table.
382              */
383             function.entry      = code_statements_elements-1;
384             function.firstlocal = 0;
385             function.locals     = 0;
386             function.profile    = 0;
387             function.name       = code_chars_elements;
388             function.file       = 0;
389             function.nargs      = args;
390             def.type            = TYPE_FUNCTION;
391             def.offset          = code_globals_elements;
392             def.name            = code_chars_elements;
393             code_functions_add(function);
394             code_globals_add(code_statements_elements);
395             code_chars_put    (name, strlen(name));
396             code_chars_add    ('\0');
397
398             /* update assembly state */
399
400             *state = ASM_FUNCTION;
401             util_debug("ASM", "added context function %s to function table\n", name);
402         }
403
404         mem_d(copy);
405         mem_d(name);
406         return true;
407     }
408     return false;
409 }
410
411 static GMQCC_INLINE bool asm_parse_stmt(const char *skip, size_t line, asm_state *state) {
412     /*
413      * This parses a valid statement in assembly and adds it to the code
414      * table to be wrote.  This needs to handle correct checking of all
415      * statements to ensure the correct amount of operands are passed to
416      * the menomic.  This must also check for valid function calls (ensure
417      * the names selected exist in the program scope) and ensure the correct
418      * CALL* is used (depending on the amount of arguments the function
419      * is expected to take)
420      */
421     char                  *c = (char*)skip;
422     prog_section_statement s;
423     size_t                 i = 0;
424
425     /*
426      * statements are only allowed when inside a function body
427      * otherwise the assembly is invalid.
428      */
429     if (*state != ASM_FUNCTION)
430         return false;
431
432     /*
433      * Skip any possible whitespace, it's not wanted we're searching
434      * for an instruction.  TODO: recrusive decent parser skip on line
435      * entry instead of pre-op.
436      */
437     while (*skip == ' ' || *skip == '\t')
438         skip++;
439
440     for (; i < sizeof(asm_instr)/sizeof(*asm_instr); i++) {
441         /*
442          * Iterate all possible instructions and check if the selected
443          * instructure in the input stream `skip` is actually a valid
444          * instruction.
445          */
446         if (!strncmp(skip, asm_instr[i].m, asm_instr[i].l)) {
447             printf("found statement %s\n", asm_instr[i].m);
448             /*
449              * Parse the operands for `i` (the instruction). The order
450              * of asm_instr is in the order of the menomic encoding so
451              * `i` == menomic encoding.
452              */
453             s.opcode = i;
454             switch (asm_instr[i].o) {
455                 /*
456                  * Each instruction can have from 0-3 operands; and can
457                  * be used with less or more operands depending on it's
458                  * selected use.
459                  *
460                  * DONE for example can use either 0 operands, or 1 (to
461                  * emulate the effect of RETURN)
462                  *
463                  * TODO: parse operands correctly figure out what it is
464                  * that the assembly is trying to do, i.e string table
465                  * lookup, function calls etc.
466                  *
467                  * This needs to have a fall state, we start from the
468                  * end of the string and work backwards.
469                  */
470                 #define OPFILL(X)                                      \
471                     do {                                               \
472                         size_t w = 0;                                  \
473                         if (!(c = strrchr(c, ','))) {                  \
474                             printf("error, expected more operands\n"); \
475                             return false;                              \
476                         }                                              \
477                         c++;                                           \
478                         w++;                                           \
479                         while (*c == ' ' || *c == '\t') {              \
480                             c++;                                       \
481                             w++;                                       \
482                         }                                              \
483                         X  = (const char*)c;                           \
484                         c -= w;                                        \
485                        *c  = '\0';                                     \
486                         c  = (char*)skip;                              \
487                     } while (0)
488
489                 case 3: {
490                     const char *data; OPFILL(data);
491                     printf("OP3: %s\n", data);
492                     s.o3.s1 = 0;
493                 }
494                 case 2: {
495                     const char *data; OPFILL(data);
496                     printf("OP2: %s\n", data);
497                     s.o2.s1 = 0;
498                 }
499                 case 1: {
500                     while (*c == ' ' || *c == '\t') c++;
501                     c += asm_instr[i].l;
502                     while (*c == ' ' || *c == '\t') c++;
503
504                     printf("OP1: %s\n", c);
505                     s.o1.s1 = 0;
506                 }
507                 #undef OPFILL
508             }
509             /* add the statement now */
510             code_statements_add(s);
511         }
512     }
513     return true;
514 }
515
516 void asm_parse(FILE *fp) {
517     char     *data  = NULL;
518     char     *skip  = NULL;
519     long      line  = 1; /* current line */
520     size_t    size  = 0; /* size of line */
521     asm_state state = ASM_NULL;
522
523     #define asm_end(x)            \
524         do {                      \
525             mem_d(data);          \
526             mem_d(copy);          \
527             line++;               \
528             util_debug("ASM", x); \
529         } while (0); continue
530
531     while ((data = asm_getline (&size, fp)) != NULL) {
532         char *copy = util_strsws(data); /* skip   whitespace */
533               skip = util_strrnl(copy); /* delete newline    */
534
535         /* TODO: statement END check */
536         if (state == ASM_FUNCTION)
537             state =  ASM_NULL;
538
539         if (asm_parse_type(skip, line, &state)){ asm_end("asm_parse_type\n"); }
540         if (asm_parse_func(skip, line, &state)){ asm_end("asm_parse_func\n"); }
541         if (asm_parse_stmt(skip, line, &state)){ asm_end("asm_parse_stmt\n"); }
542     }
543     #undef asm_end
544     asm_dumps();
545     asm_clear();
546 }