]> de.git.xonotic.org Git - xonotic/gmqcc.git/blobdiff - asm.c
ast and ir testers - to use: compile into gmqcc and execut the functions in main()
[xonotic/gmqcc.git] / asm.c
diff --git a/asm.c b/asm.c
index ece24a2d0bd98128ba37d467fac6f109d3ad3c88..a685d1c841cdadb55c8fe2d495ddd8d5237a8271 100644 (file)
--- a/asm.c
+++ b/asm.c
  */
 #include "gmqcc.h"
 /*
- * Some assembler keywords not part of the opcodes above: these are
- * for creating functions, or constants.
+ * Following parse states:
+ *     ASM_FUNCTION -- in a function accepting input statements
+ *     ....
  */
-const char *const asm_keys[] = {
-    "FLOAT"    , /* define float  */
-    "VECTOR"   , /* define vector */
-    "ENTITY"   , /* define ent    */
-    "FIELD"    , /* define field  */
-    "STRING"   , /* define string */
-    "FUNCTION"
-};
+typedef enum {
+    ASM_NULL,
+    ASM_FUNCTION
+} asm_state;
+
+typedef struct {
+    char *name;   /* name of constant    */
+    int   offset; /* location in globals */
+} globals;
+VECTOR_MAKE(globals, assembly_constants);
 
+/*
+ * Assembly text processing: this handles the internal collection
+ * of text to allow parsing and assemblation.
+ */
 static char *const asm_getline(size_t *byte, FILE *fp) {
     char   *line = NULL;
-    ssize_t read = util_getline(&line, byte, fp);
+    size_t  read = util_getline(&line, byte, fp);
     *byte = read;
     if (read == -1) {
         mem_d (line);
@@ -45,32 +52,18 @@ static char *const asm_getline(size_t *byte, FILE *fp) {
     return line;
 }
 
+/*
+ * Entire external interface for main.c - to perform actual assemblation
+ * of assembly files.
+ */
 void asm_init(const char *file, FILE **fp) {
     *fp = fopen(file, "r");
     code_init();
 }
-
 void asm_close(FILE *fp) {
     fclose(fp);
     code_write();
 }
-
-/*
- * Following parse states:
- *     ASM_FUNCTION -- in a function accepting input statements
- *     ....
- */
-typedef enum {
-    ASM_NULL,
-    ASM_FUNCTION
-} asm_state;
-
-typedef struct {
-    char *name;   /* name of constant    */
-    int   offset; /* location in globals */
-} globals;
-VECTOR_MAKE(globals, assembly_constants);
-
 void asm_clear() {
     size_t i = 0;
     for (; i < assembly_constants_elements; i++)
@@ -78,133 +71,203 @@ void asm_clear() {
     mem_d(assembly_constants_data);
 }
 
-int asm_parsetype(const char *key, char **skip, long line) {
-    size_t keylen = strlen(key);
-    if (!strncmp(key, *skip, keylen)) {
-        if ((*skip)[keylen] != ':'){
-            printf("%li: Missing `:` after decltype\n", line);
-            exit(1);
+/*
+ * Parses a type, could be global or not depending on the
+ * assembly state: global scope with assignments are constants.
+ * globals with no assignments are globals.  Function body types
+ * are locals.
+ */
+static inline bool asm_parse_type(const char *skip, size_t line, asm_state *state) {
+    if (!(strstr(skip, "FLOAT:")  == &skip[0]) &&
+         (strstr(skip, "VECTOR:") == &skip[0]) &&
+         (strstr(skip, "ENTITY:") == &skip[0]) &&
+         (strstr(skip, "FIELD:")  == &skip[0]) &&
+         (strstr(skip, "STRING:") == &skip[0])) return false;
+
+    /* TODO: determine if constant, global, or local */
+    switch (*skip) {
+        /* VECTOR */ case 'V': {
+            float val1;
+            float val2;
+            float val3;
+            
+            const char *find = skip + 7;
+            while (*find == ' ' || *find == '\t') find++;
+
+            /*
+             * Parse all three elements of the vector.  This will only
+             * pass the first try if we hit a constant, otherwise it's
+             * a global.
+             */
+            #define PARSE_ELEMENT(X,Y,Z)                    \
+                if (isdigit(*X)  || *X == '-'||*X == '+') { \
+                    bool negated = (*X == '-');             \
+                    if  (negated || *X == '+')   { X++; }   \
+                    Y = (negated)?-atof(X):atof(X);         \
+                    X = strchr(X, ',');                     \
+                    Z                                       \
+                }
+
+            PARSE_ELEMENT(find, val1, { if(find) { find +=3; }});
+            PARSE_ELEMENT(find, val2, { if(find) { find +=2; }});
+            PARSE_ELEMENT(find, val3, { if(find) { find +=1; }});
+            #undef PARSE_ELEMENT
+
+            printf("X:[0] = %f\n", val1);
+            printf("Y:[1] = %f\n", val2);
+            printf("Z:[2] = %f\n", val3);
+            
+            break;
         }
-        *skip += keylen+1;
-        while (**skip == ' ' || **skip == '\t')
-            (*skip)++;
-        
-        if (!isalpha(**skip)) {
-            printf("%li: Invalid identififer: %s\n", line, *skip);
-            exit(1);
-        } else {
-            assembly_constants_add((globals) {
-                .name   = util_strdup("empty"),
-                .offset = code_globals_elements
-            });
-            return 1;
+        /* ENTITY */ case 'E': {
+            const char *find = skip + 7;
+            while (*find == ' ' || *find == '\t') find++;
+            printf("found ENTITY %s\n", find);
+            break;
+        }
+        /* STRING */ case 'S': {
+            const char *find = skip + 7;
+            while (*find == ' ' || *find == '\t') find++;
+            printf("found STRING %s\n", find);
+            break;
         }
     }
-    return 0;
+    
+    return false;
 }
 
-void asm_parse(FILE *fp) {
-    char     *data  = NULL;
-    char     *skip  = NULL;
-    long      line  = 1; /* current line */
-    size_t    size  = 0; /* size of line */
-    asm_state state = ASM_NULL;
-    
-    while ((data = skip = asm_getline(&size, fp)) != NULL) {
-        /* remove any whitespace at start  */
-        while (*skip == ' ' || *skip == '\t')
-            skip++;
-        /* remove newline at end of string */
-        *(skip+*(&size)-1) = '\0';
-        
-        if (asm_parsetype(asm_keys[5], &skip, line)) {
-            if (state != ASM_NULL) {
-                printf("%li: Error unfinished function block, expected DONE or RETURN\n", line);
-                goto end;
+/*
+ * Parses a function: trivial case, handles occurances of duplicated
+ * names among other things.  Ensures valid name as well, and even
+ * internal engine function selection.
+ */
+static inline bool asm_parse_func(const char *skip, size_t line, asm_state *state) {
+    if (*state == ASM_FUNCTION && (strstr(skip, "FUNCTION:") == &skip[0]))
+        return false;
+
+    if (strstr(skip, "FUNCTION:") == &skip[0]) {
+        char  *copy = util_strsws(skip+10);
+        char  *name = util_strchp(copy, strchr(copy, '\0'));
+
+        /* TODO: failure system, missing name */
+        if (!name) {
+            printf("expected name on function\n");
+            mem_d(copy);
+            mem_d(name);
+            return false;
+        }
+        /* TODO: failure system, invalid name */
+        if (!isalpha(*name) || util_strupper(name)) {
+            printf("invalid identifer for function name\n");
+            mem_d(copy);
+            mem_d(name);
+            return false;
+        }
+
+        /*
+         * Function could be internal function, look for $
+         * to determine this.
+         */
+        if (strchr(name, ',')) {
+            char *find = strchr(name, ',') + 1;
+            
+            /* skip whitespace */
+            while (*find == ' ' || *find == '\t')
+                find++;
+            
+            if (*find != '$') {
+                printf("expected $ for internal function selection, got %s instead\n", find);
+                mem_d(copy);
+                mem_d(name);
+                return false;
             }
-            state = ASM_FUNCTION;
+            find ++;
+            if (!isdigit(*find)) {
+                printf("invalid internal identifier, expected valid number\n");
+                mem_d(copy);
+                mem_d(name);
+                return false;
+            }
+            *strchr(name, ',')='\0';
+            
+            /*
+             * Now add the following items to the code system:
+             *  function
+             *  definition (optional)
+             *  global     (optional)
+             *  name
+             */
+            code_functions_add((prog_section_function){
+                -atoi(find), /* needs to be negated */
+                 0, 0, 0,
+                .name = code_chars_elements,
+                 0, 0,{0}
+            });
             code_defs_add((prog_section_def){
-                .type   = TYPE_VOID,
+                .type   = TYPE_FUNCTION,
                 .offset = code_globals_elements,
                 .name   = code_chars_elements
             });
-            code_globals_add(code_functions_elements);
-            code_functions_add((prog_section_function) {
-                .entry      =  code_statements_elements,      
-                .firstlocal =  0,
-                .locals     =  0,
-                .profile    =  0,
-                .name       =  code_chars_elements,
-                .file       =  0,
-                .nargs      =  0,
-                .argsize    = {0}
-            });
-            code_strings_add(skip);
-        };
-
-        #if 0
-        /* if we make it this far then we have statements */
-        {
-            size_t i = 0;    /* counter   */
-            size_t o = 0;    /* operands  */
-            size_t c = 0;    /* copy      */
-            char  *t = NULL; /* token     */
+            code_globals_add(code_chars_elements);
             
+            code_chars_put(name, strlen(name));
+            code_chars_add('\0');
+
             /*
-             * Most ops a single statement can have is three.
-             * lets allocate some space for all of those here.
+             * Sanatize the numerical constant used to select the
+             * internal function.  Must ensure it's all numeric, since
+             * atoi can silently drop characters from a string and still
+             * produce a valid constant that would lead to runtime problems.
              */
-            char op[3][32768] = {{0},{0},{0}};
-            for (; i < sizeof(asm_instr)/sizeof(*asm_instr); i++) {
-                if (!strncmp(skip, asm_instr[i].m, asm_instr[i].l)) {
-                    if (state != ASM_FUNCTION) {
-                        printf("%li: Statement not inside function block\n", line);
-                        goto end;
-                    }
-                    
-                    /* update parser state */
-                    if (i == INSTR_DONE || i == INSTR_RETURN) {
-                        goto end;
-                        state = ASM_NULL;
-                    }
-                    
-                    /* parse the statement */
-                    c     = i;
-                    o     = asm_instr[i].o; /* operands         */
-                    skip += asm_instr[i].l; /* skip instruction */
-                    t     = strtok(skip, " ,");
-                    i     = 0;
-                    while (t != NULL && i < 3) {
-                        strcpy(op[i], t);
-                        t = strtok(NULL, " ,");
-                        i ++;
-                    }
-                    
-                    /* check */
-                    if (i != o) {
-                        printf("not enough operands, expected: %li, got %li\n", o, i);
-                    }
-                    
-                    /* TODO: hashtable value LOAD .... etc */
-                    code_statements_add((prog_section_statement){
-                        c,
-                        { atof(op[0]) },
-                        { atof(op[1]) },
-                        { atof(op[2]) }
-                    });
-                    goto end;
-                }
-            }
+            if (util_strdigit(find))
+                printf("found internal function %s, -%d\n", name, atoi(find));
+            else
+                printf("invalid internal function identifier, must be all numeric\n");
+                
+        } else {
+            /* TODO: function bodies */
         }
-        #endif
-        
-        /* if we made it this far something is wrong */
-        if (*skip != '\0')
-            printf("%li: Invalid statement %s, expression, or decleration\n", line, skip);
+
+        mem_d(copy);
+        mem_d(name);
+        return true;
+    }
+    return false;
+}
+
+void asm_parse(FILE *fp) {
+    char     *data  = NULL;
+    char     *skip  = NULL;
+    long      line  = 1; /* current line */
+    size_t    size  = 0; /* size of line */
+    asm_state state = ASM_NULL;
+
+    #define asm_end(x)            \
+        do {                      \
+            mem_d(data);          \
+            mem_d(copy);          \
+            line++;               \
+            util_debug("ASM", x); \
+        } while (0); continue
+    
+    while ((data = asm_getline (&size, fp)) != NULL) {
+        char *copy = util_strsws(data); /* skip   whitespace */
+              skip = util_strrnl(copy); /* delete newline    */
+
+        /* parse type */
+        if(asm_parse_type(skip, line, &state)){ asm_end("asm_parse_type\n"); }
+        /* parse func */
+        if(asm_parse_func(skip, line, &state)){ asm_end("asm_parse_func\n"); }
+
+        /* statement closure */
+        if (state == ASM_FUNCTION && (
+            (strstr(skip, "DONE")   == &skip[0])||
+            (strstr(skip, "RETURN") == &skip[0]))) state = ASM_NULL;
         
-        end:
-        mem_d(data);
-        line ++;
+        /* TODO: everything */
+        (void)state;
+        asm_end("asm_parse_end\n");
     }
+    #undef asm_end
        asm_clear();
 }