Skip to content
Myr

locfile.c

This file

Path

src/locfile.c

92 lines · 2.6 KiB · C

Last changed by

Fix syntax error assertion failure (fix #3348) (#3350)itchynybefore adoptiona587ddc

History of this file

Take it

1#include <assert.h>2#include <errno.h>3#include <stdarg.h>4#include <stdlib.h>5#include <stdio.h>6#include <string.h>7#include "jq.h"8#include "jv_alloc.h"9#include "locfile.h"10#include "util.h"1112struct locfile* locfile_init(jq_state *jq, const char *fname, const char* data, int length) {13  struct locfile* l = jv_mem_alloc(sizeof(struct locfile));14  l->jq = jq;15  l->fname = jv_string(fname);16  l->data = jv_mem_alloc(length);17  memcpy((char*)l->data,data,length);18  l->length = length;19  l->nlines = 1;20  l->refct = 1;21  for (int i=0; i<length; i++) {22    if (data[i] == '\n') l->nlines++;23  }24  l->linemap = jv_mem_calloc(l->nlines + 1, sizeof(int));25  l->linemap[0] = 0;26  int line = 1;27  for (int i=0; i<length; i++) {28    if (data[i] == '\n') {29      l->linemap[line] = i+1;   // at start of line, not of \n30      line++;31    }32  }33  l->linemap[l->nlines] = length+1;   // virtual last \n34  return l;35}3637struct locfile* locfile_retain(struct locfile* l) {38  l->refct++;39  return l;40}41void locfile_free(struct locfile* l) {42  if (--(l->refct) == 0) {43    jv_free(l->fname);44    jv_mem_free(l->linemap);45    jv_mem_free((char*)l->data);46    jv_mem_free(l);47  }48}4950int locfile_get_line(struct locfile* l, int pos) {51  assert(pos < l->length);52  int line = 1;53  while (l->linemap[line] <= pos) line++;   // == if pos at start (before, never ==, because pos never on \n)54  assert(line-1 < l->nlines);55  return line-1;56}5758static int locfile_line_length(struct locfile* l, int line) {59  assert(line < l->nlines);60  return l->linemap[line+1] - l->linemap[line] -1;   // -1 to omit \n61}6263void locfile_locate(struct locfile* l, location loc, const char* fmt, ...) {64  va_list fmtargs;65  va_start(fmtargs, fmt);6667  jv m1 = jv_string_vfmt(fmt, fmtargs);68  va_end(fmtargs);69  if (!jv_is_valid(m1)) {70    jq_report_error(l->jq, m1);71    return;72  }73  if (loc.start == -1) {74    jq_report_error(l->jq, jv_string_fmt("jq: error: %s", jv_string_value(m1)));75    jv_free(m1);76    return;77  }7879  int startline = locfile_get_line(l, loc.start);80  int offset = l->linemap[startline];81  int end = MIN(loc.end, MAX(l->linemap[startline+1] - 1, loc.start + 1));82  jv underline = jv_string_repeat(jv_string("^"), end - loc.start);83  jv m2 = jv_string_fmt("%s at %s, line %d, column %d:\n    %.*s\n    %*s",84                        jv_string_value(m1), jv_string_value(l->fname),85                        startline + 1, loc.start - offset + 1,86                        locfile_line_length(l, startline), l->data + offset,87                        end - offset, jv_string_value(underline));88  jv_free(m1);89  jv_free(underline);90  jq_report_error(l->jq, m2);91  return;92}