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