Track line number for error reports

This commit is contained in:
Eric Fischer 2014-02-06 20:44:39 -08:00
parent 46120e84c4
commit a74444af28
3 changed files with 19 additions and 9 deletions

View File

@ -88,7 +88,7 @@ void process(FILE *f) {
} }
if (jp->error != NULL) { if (jp->error != NULL) {
fprintf(stderr, "%s\n", jp->error); fprintf(stderr, "%d: %s\n", jp->line, jp->error);
} }
} }

View File

@ -9,19 +9,24 @@ typedef enum json_expect {
JSON_ITEM, JSON_COMMA, JSON_COLON, JSON_KEY, JSON_VALUE, JSON_ITEM, JSON_COMMA, JSON_COLON, JSON_KEY, JSON_VALUE,
} json_expect; } json_expect;
static int read_file(json_pull *p) { static int read_file(json_pull *j) {
return fgetc(p->source); int c = fgetc(j->source);
if (c == '\n') {
j->line++;
}
return c;
} }
static int peek_file(json_pull *p) { static int peek_file(json_pull *j) {
int c = getc(p->source); int c = getc(j->source);
ungetc(c, p->source); ungetc(c, j->source);
return c; return c;
} }
json_pull *json_begin_file(FILE *f) { json_pull *json_begin_file(FILE *f) {
json_pull *j = malloc(sizeof(json_pull)); json_pull *j = malloc(sizeof(json_pull));
j->container = NULL; j->container = NULL;
j->line = 1;
j->read = read_file; j->read = read_file;
j->peek = peek_file; j->peek = peek_file;
@ -30,14 +35,17 @@ json_pull *json_begin_file(FILE *f) {
return j; return j;
} }
static int read_string(json_pull *p) { static int read_string(json_pull *j) {
char *cp = p->source; char *cp = j->source;
if (*cp == '\0') { if (*cp == '\0') {
return EOF; return EOF;
} }
int c = (unsigned char) *cp; int c = (unsigned char) *cp;
cp++; cp++;
p->source = cp; j->source = cp;
if (c == '\n') {
j->line++;
}
return c; return c;
} }
@ -52,6 +60,7 @@ static int peek_string(json_pull *p) {
json_pull *json_begin_string(char *s) { json_pull *json_begin_string(char *s) {
json_pull *j = malloc(sizeof(json_pull)); json_pull *j = malloc(sizeof(json_pull));
j->container = NULL; j->container = NULL;
j->line = 1;
j->read = read_string; j->read = read_string;
j->peek = peek_string; j->peek = peek_string;

View File

@ -24,6 +24,7 @@ struct json_pull {
int (*read)(struct json_pull *); int (*read)(struct json_pull *);
int (*peek)(struct json_pull *); int (*peek)(struct json_pull *);
void *source; void *source;
int line;
}; };
typedef struct json_pull json_pull; typedef struct json_pull json_pull;