分享

修正上一篇c语言写一个Python的编译器

 山峰云绕 2023-03-10 发布于贵州

经过一,上篇简单是是表达式的,并表达式,并输入,并输入则则运算见谅

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INPUT 256

#define TYPE_INT 1
#define TYPE_STRING 2
#define TYPE_LIST 3

typedef struct {
    int type;
    union {
        int i;
        char *s;
        struct {
            void **data;
            int size;
        } l;
    } value;
} Object;

Object *new_object(int type) {
    Object *obj = (Object *)malloc(sizeof(Object));
    obj->type = type;
    return obj;
}

void free_object(Object *obj) {
    if (obj->type == TYPE_STRING) {
        free(obj->value.s);
    } else if (obj->type == TYPE_LIST) {
        for (int i = 0; i < obj->value.l.size; i++) {
            free_object((Object *)obj->value.l.data[i]);
        }
        free(obj->value.l.data);
    }
    free(obj);
}

Object *parse_expression(char *input) {
    // TODO: 解析表达式并返回计算结果
    return NULL;
}

int main() {
    char input[MAX_INPUT];
    Object *result;

    while (1) {
        printf(">> ");
        fgets(input, MAX_INPUT, stdin);

        if (strcmp(input, "exit\n") == 0) {
            exit(0);
        } else {
            result = parse_expression(input);
            if (result != NULL) {
                if (result->type == TYPE_INT) {
                    printf("%d\n", result->value.i);
                } else if (result->type == TYPE_STRING) {
                    printf("%s\n", result->value.s);
                } else if (result->type == TYPE_LIST) {
                    printf("[");
                    for (int i = 0; i < result->value.l.size; i++) {
                        Object *item = (Object *)result->value.l.data[i];
                        if (item->type == TYPE_INT) {
                            printf("%d", item->value.i);
                        } else if (item->type == TYPE_STRING) {
                            printf("'%s'", item->value.s);
                        }
                        if (i != result->value.l.size - 1) {
                            printf(", ");
                        }
                    }
                    printf("]\n");
                }
                free_object(result);
            } else {
                printf("Invalid input\n");
            }
        }
    }

    return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约