]> git.xonotic.org Git - xonotic/gmqcc.git/blob - asm.c
More function parsing for assembler
[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             char *find = strchr(name, '#');
288             char *peek = find;
289             
290             /*
291              * Code structures for filling after determining the correct
292              * information to add to the code write system.
293              */
294             prog_section_function function;
295             prog_section_def      def;
296             if (find) {
297                 find ++;
298
299                 /* skip whitespace */
300                 if (*find == ' ' || *find == '\t')
301                     find++;
302
303                 /*
304                  * If the input is larger than eight, it's considered
305                  * invalid and shouldn't be allowed.  The QuakeC VM only
306                  * allows a maximum of eight arguments.
307                  */
308                 if (strlen(find) > 1 || *find == '9') {
309                     printf("invalid number of arguments, must be a valid number from 0-8\n");
310                     mem_d(copy);
311                     mem_d(name);
312                     return false;
313                 }
314
315                 if (*find != '0') {
316                     /*
317                      * if we made it this far we have a valid number for the
318                      * argument count, so fall through a switch statement and
319                      * do it.
320                      */
321                     switch (*find) {
322                         case '8': args++; case '7': args++;
323                         case '6': args++; case '5': args++;
324                         case '4': args++; case '3': args++;
325                         case '2': args++; case '1': args++;
326                     }
327                 }
328             } else {
329                 printf("missing number of argument count in function %s\n", name);
330             }
331
332             /*
333              * Now we need to strip the name apart into it's exact size
334              * by working in the peek buffer till we hit the name again.
335              */
336             if (*peek == '#') {
337                 peek --; /* '#'    */
338                 peek --; /* number */
339             }
340             while (*peek == ' ' || *peek == '\t') peek--;
341
342             /*
343              * We're guranteed to be exactly where we need to be in the
344              * peek buffer to null terminate and get our name from name
345              * without any garbage before or after it.
346              */
347             *++peek='\0';
348
349             /*
350              * We got valid function structure information now. Lets add
351              * the function to the code writer function table.
352              */
353             function.entry      = code_statements_elements-1;
354             function.firstlocal = 0;
355             function.locals     = 0;
356             function.profile    = 0;
357             function.name       = code_chars_elements;
358             function.file       = 0;
359             function.nargs      = args;
360             def.type            = TYPE_FUNCTION;
361             def.offset          = code_globals_elements;
362             def.name            = code_chars_elements;
363             memset(function.argsize, 0, sizeof(function.argsize));
364             code_functions_add(function);
365             code_globals_add(code_statements_elements);
366             code_chars_put    (name, strlen(name));
367             code_chars_add    ('\0');
368
369             /* update assembly state */
370             
371             *state = ASM_FUNCTION;
372             util_debug("ASM", "added context function %s to function table\n", name);
373         }
374         
375         mem_d(copy);
376         mem_d(name);
377         return true;
378     }
379     return false;
380 }
381
382 static GMQCC_INLINE bool asm_parse_stmt(const char *skip, size_t line, asm_state *state) {
383     /*
384      * This parses a valid statement in assembly and adds it to the code
385      * table to be wrote.  This needs to handle correct checking of all
386      * statements to ensure the correct amount of operands are passed to
387      * the menomic.  This must also check for valid function calls (ensure
388      * the names selected exist in the program scope) and ensure the correct
389      * CALL* is used (depending on the amount of arguments the function
390      * is expected to take)
391      */
392     char                  *c = (char*)skip;
393     prog_section_statement s;
394     size_t                 i = 0;
395
396     /*
397      * statements are only allowed when inside a function body
398      * otherwise the assembly is invalid.
399      */
400     if (*state != ASM_FUNCTION)
401         return false;
402
403     /*
404      * Skip any possible whitespace, it's not wanted we're searching
405      * for an instruction.  TODO: recrusive decent parser skip on line
406      * entry instead of pre-op.
407      */
408     while (*skip == ' ' || *skip == '\t')
409         skip++;
410     
411     for (; i < sizeof(asm_instr)/sizeof(*asm_instr); i++) {
412         /*
413          * Iterate all possible instructions and check if the selected
414          * instructure in the input stream `skip` is actually a valid
415          * instruction.
416          */
417         if (!strncmp(skip, asm_instr[i].m, asm_instr[i].l)) {
418             printf("found statement %s\n", asm_instr[i].m);
419             /*
420              * Parse the operands for `i` (the instruction). The order
421              * of asm_instr is in the order of the menomic encoding so
422              * `i` == menomic encoding.
423              */
424             s.opcode = i;
425             switch (asm_instr[i].o) {
426                 /*
427                  * Each instruction can have from 0-3 operands; and can
428                  * be used with less or more operands depending on it's
429                  * selected use.
430                  * 
431                  * DONE for example can use either 0 operands, or 1 (to
432                  * emulate the effect of RETURN)
433                  *
434                  * TODO: parse operands correctly figure out what it is
435                  * that the assembly is trying to do, i.e string table
436                  * lookup, function calls etc.
437                  *
438                  * This needs to have a fall state, we start from the
439                  * end of the string and work backwards.
440                  */
441                 #define OPFILL(X)                                      \
442                     do {                                               \
443                         size_t w = 0;                                  \
444                         if (!(c = strrchr(c, ','))) {                  \
445                             printf("error, expected more operands\n"); \
446                             return false;                              \
447                         }                                              \
448                         c++;                                           \
449                         w++;                                           \
450                         while (*c == ' ' || *c == '\t') {              \
451                             c++;                                       \
452                             w++;                                       \
453                         }                                              \
454                         X  = (const char*)c;                           \
455                         c -= w;                                        \
456                        *c  = '\0';                                     \
457                         c  = (char*)skip;                              \
458                     } while (0)
459                     
460                 case 3: {
461                     const char *data; OPFILL(data);
462                     printf("OP3: %s\n", data);
463                     s.o3.s1 = 0;
464                 }
465                 case 2: {
466                     const char *data; OPFILL(data);
467                     printf("OP2: %s\n", data);
468                     s.o2.s1 = 0;
469                 }
470                 case 1: {
471                     while (*c == ' ' || *c == '\t') c++;
472                     c += asm_instr[i].l;
473                     while (*c == ' ' || *c == '\t') c++;
474                     
475                     printf("OP1: %s\n", c);
476                     s.o1.s1 = 0;
477                 }
478                 #undef OPFILL
479             }
480             /* add the statement now */
481             code_statements_add(s);
482         }
483     }
484     return true;
485 }
486
487 void asm_parse(FILE *fp) {
488     char     *data  = NULL;
489     char     *skip  = NULL;
490     long      line  = 1; /* current line */
491     size_t    size  = 0; /* size of line */
492     asm_state state = ASM_NULL;
493
494     #define asm_end(x)            \
495         do {                      \
496             mem_d(data);          \
497             mem_d(copy);          \
498             line++;               \
499             util_debug("ASM", x); \
500         } while (0); continue
501
502     while ((data = asm_getline (&size, fp)) != NULL) {
503         char *copy = util_strsws(data); /* skip   whitespace */
504               skip = util_strrnl(copy); /* delete newline    */
505
506         /* TODO: statement END check */
507         if (state == ASM_FUNCTION)
508             state =  ASM_NULL;
509
510         if (asm_parse_type(skip, line, &state)){ asm_end("asm_parse_type\n"); }
511         if (asm_parse_func(skip, line, &state)){ asm_end("asm_parse_func\n"); }
512         if (asm_parse_stmt(skip, line, &state)){ asm_end("asm_parse_stmt\n"); }
513     }
514     #undef asm_end
515     asm_dumps();
516     asm_clear();
517 }