| 1 |
/* |
| 2 |
* Copyright © 2025 Ran Benita <[email protected]> |
| 3 |
* SPDX-License-Identifier: MIT |
| 4 |
*/ |
| 5 |
|
| 6 |
#include "config.h" |
| 7 |
|
| 8 |
#include "scanner-utils.h" |
| 9 |
|
| 10 |
struct scanner_loc |
| 11 |
scanner_token_location(struct scanner *s) |
| 12 |
{ |
| 13 |
/* |
| 14 |
* The following article and accompying code compares some algorithms: |
| 15 |
* https://lemire.me/blog/2017/02/14/how-fast-can-you-count-lines/ |
| 16 |
* https://github.com/lemire/Code-used-on-Daniel-Lemire-s-blog/blob/master/2017/02/14/newlines.c |
| 17 |
* This is the fastest portable one for me, and it's simple. |
| 18 |
* |
| 19 |
* To avoid rescanning on each call, cache the previously found position |
| 20 |
* and start from that on the next call. This is effective as long as the |
| 21 |
* tokens go forward. |
| 22 |
*/ |
| 23 |
size_t line, column; |
| 24 |
size_t line_pos = 0; |
| 25 |
if (s->cached_pos > s->token_pos) { |
| 26 |
s->cached_pos = 0; |
| 27 |
s->cached_loc.line = s->cached_loc.column = 1; |
| 28 |
} |
| 29 |
line = s->cached_loc.line; |
| 30 |
const char *ptr = s->s + s->cached_pos; |
| 31 |
const char *last = s->s + s->token_pos; |
| 32 |
while ((ptr = memchr(ptr, '\n', last - ptr))) { |
| 33 |
line++; |
| 34 |
ptr++; |
| 35 |
line_pos = ptr - s->s; |
| 36 |
} |
| 37 |
if (line == s->cached_loc.line) { |
| 38 |
column = s->cached_loc.column + (s->token_pos - s->cached_pos); |
| 39 |
} else { |
| 40 |
column = s->token_pos - line_pos + 1; |
| 41 |
} |
| 42 |
struct scanner_loc loc = {.line = line, .column = column}; |
| 43 |
s->cached_pos = s->token_pos; |
| 44 |
s->cached_loc = loc; |
| 45 |
return loc; |
| 46 |
} |