如果将源代码加载到char
数组中,则可以考虑编写一个int get_token(const char *s, int *token_len)
函数,该函数返回令牌类型并将令牌长度存储到*token_len
.根据令牌类型,您可以使用以下命令输出相应的 colored颜色 和令牌源:
#include <stdio.h>
enum tokenType {
END, WHITESPACE, NEWLINE, COMMENT, PREPROCESSOR,
KEYWORD, IDENTIFIER, STRING, CHARCONST, NUMBER, OPERATOR,
OTHER
};
struct parse_context {
const char *filename;
const char *source;
size_t source_pos;
int line_number;
int column_number;
int at_bol;
...
};
const char *colors[] = {
[END] = ...,
[WHITESPACE] = ...,
[NEWLINE] = ...,
[COMMENT] = ...,
[PREPROCESSOR] = ...,
[KEYWORD] = ...,
[IDENTIFIER] = ...,
[STRING] = ...,
[CHARCONST] = ...,
[NUMBER] = ...,
[OPERATOR] = ...,
[OTHER] = ...,
};
enum tokenType get_token(struct parse_context *pc, const char *s, int *token_len) {
...
}
void my_func(const char *filename, const char *s) {
struct parse_context ctx = {
filename, s, 0, 1, 1, 1,
};
enum tokenType last_token = END;
for (;;) {
int len;
enum tokenType tok_type = get_token(&ctx, s, &len);
if (tok_type != last_token) {
printf("%s", colors[tok_type]);
last_token = tok_type;
}
if (tok_type == END) {
break;
} else {
printf("%.*s", len, s);
s += len;
}
}
}