]> git.xonotic.org Git - xonotic/gmqcc.git/blob - asm.c
if-then-else AST node - this one is not for ternary expressions
[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             } else {
165                 /* TODO global not constant */
166             }
167             break;
168         }
169         /* ENTITY */ case 'E': {
170             const char *find = skip + 7;
171             while (*find == ' ' || *find == '\t') find++;
172             printf("found ENTITY %s\n", find);
173             break;
174         }
175         /* STRING */ case 'S': {
176             const char *find = skip + 7;
177             while (*find == ' ' || *find == '\t') find++;
178             printf("found STRING %s\n", find);
179             break;
180         }
181     }
182
183     return false;
184 }
185
186 /*
187  * Parses a function: trivial case, handles occurances of duplicated
188  * names among other things.  Ensures valid name as well, and even
189  * internal engine function selection.
190  */
191 static GMQCC_INLINE bool asm_parse_func(const char *skip, size_t line, asm_state *state) {
192     if (*state == ASM_FUNCTION && (strstr(skip, "FUNCTION:") == &skip[0]))
193         return false;
194
195     if (strstr(skip, "FUNCTION:") == &skip[0]) {
196         char  *copy = util_strsws(skip+10);
197         char  *name = util_strchp(copy, strchr(copy, '\0'));
198
199         /* TODO: failure system, missing name */
200         if (!name) {
201             printf("expected name on function\n");
202             mem_d(copy);
203             mem_d(name);
204             return false;
205         }
206         /* TODO: failure system, invalid name */
207         if (!isalpha(*name) || util_strupper(name)) {
208             printf("invalid identifer for function name\n");
209             mem_d(copy);
210             mem_d(name);
211             return false;
212         }
213
214         /*
215          * Function could be internal function, look for $
216          * to determine this.
217          */
218         if (strchr(name, ',')) {
219             prog_section_function function;
220             prog_section_def      def;
221
222             char *find = strchr(name, ',') + 1;
223
224             /* skip whitespace */
225             while (*find == ' ' || *find == '\t')
226                 find++;
227
228             if (*find != '$') {
229                 printf("expected $ for internal function selection, got %s instead\n", find);
230                 mem_d(copy);
231                 mem_d(name);
232                 return false;
233             }
234             find ++;
235             if (!isdigit(*find)) {
236                 printf("invalid internal identifier, expected valid number\n");
237                 mem_d(copy);
238                 mem_d(name);
239                 return false;
240             }
241             *strchr(name, ',')='\0';
242
243             /*
244              * Now add the following items to the code system:
245              *  function
246              *  definition (optional)
247              *  global     (optional)
248              *  name
249              */
250             function.entry      = -atoi(find);
251             function.firstlocal = 0;
252             function.profile    = 0;
253             function.name       = code_chars_elements;
254             function.file       = 0;
255             function.nargs      = 0;
256             def.type            = TYPE_FUNCTION;
257             def.offset          = code_globals_elements;
258             def.name            = code_chars_elements;
259             code_functions_add(function);
260             code_defs_add     (def);
261             code_globals_add  (code_chars_elements);
262             code_chars_put    (name, strlen(name));
263             code_chars_add    ('\0');
264
265             /*
266              * Sanatize the numerical constant used to select the
267              * internal function.  Must ensure it's all numeric, since
268              * atoi can silently drop characters from a string and still
269              * produce a valid constant that would lead to runtime problems.
270              */
271             if (util_strdigit(find))
272                 printf("found internal function %s, -%d\n", name, atoi(find));
273             else
274                 printf("invalid internal function identifier, must be all numeric\n");
275
276         } else {
277             printf("Found function %s\n", name);
278         }
279
280         mem_d(copy);
281         mem_d(name);
282         return true;
283     }
284     return false;
285 }
286
287 void asm_parse(FILE *fp) {
288     char     *data  = NULL;
289     char     *skip  = NULL;
290     long      line  = 1; /* current line */
291     size_t    size  = 0; /* size of line */
292     asm_state state = ASM_NULL;
293
294     #define asm_end(x)            \
295         do {                      \
296             mem_d(data);          \
297             mem_d(copy);          \
298             line++;               \
299             util_debug("ASM", x); \
300         } while (0); continue
301
302     while ((data = asm_getline (&size, fp)) != NULL) {
303         char *copy = util_strsws(data); /* skip   whitespace */
304               skip = util_strrnl(copy); /* delete newline    */
305
306         /* parse type */
307         if(asm_parse_type(skip, line, &state)){ asm_end("asm_parse_type\n"); }
308         /* parse func */
309         if(asm_parse_func(skip, line, &state)){ asm_end("asm_parse_func\n"); }
310
311         /* statement closure */
312         if (state == ASM_FUNCTION && (
313             (strstr(skip, "DONE")   == &skip[0])||
314             (strstr(skip, "RETURN") == &skip[0]))) state = ASM_NULL;
315
316         /* TODO: everything */
317         (void)state;
318         asm_end("asm_parse_end\n");
319     }
320     #undef asm_end
321         asm_dumps();
322     asm_clear();
323 }