Post

Improve error message

对上一节的error作一些改进,tokenize时输出错误位置

知识点

输出空格

1
fprintf(stderr, "%*s", n, ""); 

如何定位到出错处

在Token构造时直接将 tok->str指向相应字符位置,通过这个指针 - 分析符串指针就得到位移,而分析要的字符串是不换行的所以可以通过%*s输空格来定位到指定的错误。

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// reports an error location and exit.
void error_at(char *loc,char *fmt,...){
    va_list ap;
    va_start(ap,fmt);
    int pos=loc - user_input;
    fprintf(stderr,"%s\n",user_input);
    fprintf(stderr, "%*s", pos, ""); // print pos spaces.
    vprintf(stderr,"^ ");
    vfprintf(stderr,fmt,ap);
    fprintf(stderr,"\n");
    va_end(ap);
    exit(1);
}

This post is licensed under CC BY 4.0 by the author.