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