-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery-index.c
More file actions
4199 lines (3780 loc) · 174 KB
/
Copy pathquery-index.c
File metadata and controls
4199 lines (3780 loc) · 174 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SourceMinder
* Copyright 2025 Eli Bird
*
* This file is part of SourceMinder.
*
* SourceMinder is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* SourceMinder is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with SourceMinder. If not, see <https://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <sys/stat.h>
#if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
/* Windows/MinGW: provide POSIX compatibility */
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
/* strndup is not available on Windows */
static char *strndup(const char *s, size_t n) {
size_t len = strnlen(s, n);
char *new_str = malloc(len + 1);
if (new_str) {
memcpy(new_str, s, len);
new_str[len] = '\0';
}
return new_str;
}
#else
#include <strings.h>
#endif
#include <regex.h>
#include "shared/database.h"
#include "shared/constants.h"
#include "shared/file_opener.h"
#include "shared/file_utils.h"
#include "shared/string_utils.h"
#include "shared/extensions.h"
#include "shared/filter.h"
#include "shared/paths.h"
#include "shared/toc.h"
#include "shared/version.h"
#include "shared/sql_builder.h"
typedef struct {
ContextType types[MAX_CONTEXT_TYPES];
int count;
} ContextTypeList;
typedef struct {
char *patterns[MAX_PATTERNS];
int count;
} PatternList;
/* Generic string list for extensible column filters */
typedef struct {
char *values[MAX_CONTEXT_TYPES];
int count;
} StringList;
/* File pattern with separate directory and filename parts */
typedef struct {
char *directory; /* NULL if no directory part */
char *filename; /* Always present */
} FilePattern;
/* List of file patterns for filtering */
typedef struct {
FilePattern patterns[MAX_CONTEXT_TYPES];
int count;
} FileFilterList;
/* Query filters structure with X-Macro generated fields */
typedef struct {
/* Traditional context filters */
ContextTypeList include;
ContextTypeList exclude;
/* Line range filter */
int line_start; /* -1 = not set */
int line_end; /* -1 = not set */
/* X-Macro: Extensible filterable column filters */
#define COLUMN(name, ...) StringList name;
#define INT_COLUMN(name, ...) StringList name;
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
/* Virtual filter (no backing column): --parent-type resolves
* parent_symbol to its same-file definition and matches that
* definition's declared type */
StringList parent_type;
} QueryFilters;
/* Within filter - stores symbol names for --within flag */
typedef struct {
char *symbols[MAX_PATTERNS]; /* Array of symbol names to look up */
int count; /* Number of symbols */
} WithinFilter;
/* Within ranges - stores per-file line ranges from definition lookup */
typedef struct {
char directory[DIRECTORY_MAX_LENGTH];
char filename[FILENAME_MAX_LENGTH];
int line_start;
int line_end;
} WithinRange;
typedef struct {
WithinRange ranges[MAX_PATTERNS]; /* Max 32 ranges */
int count;
} WithinRangeList;
/* Show column flags structure with X-Macro generated fields */
typedef struct {
#define COLUMN(name, ...) int name;
#define INT_COLUMN(name, ...) int name;
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
} ShowColumns;
/* Row data structure - holds all column values */
typedef struct {
/* Internal/core columns (always present from database) */
const char *directory;
const char *filename;
const char *source_location;
const char *symbol; /* lowercase 'symbol' from database */
int line;
const char *context;
const char *full_symbol;
/* X-Macro: Extensible filterable columns */
#define COLUMN(name, ...) const char *name;
#define INT_COLUMN(name, ...) int name;
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
} RowData;
/* Column type for proper serialization */
typedef enum {
COL_TYPE_INT,
COL_TYPE_STRING
} ColumnType;
/* Column getter function - extracts data from RowData */
typedef const void* (*ColumnGetter)(RowData *data);
/* Column specification with getter function */
typedef struct {
const char *name; /* CLI name: "line", "context", etc. */
const char *header; /* Display header (full name) */
const char *header_compact; /* Display header (compact name) */
int width; /* Column width (0 = variable) */
ColumnType type; /* Data type */
ColumnGetter getter; /* Function to extract this column's data */
} ColumnSpec;
/* Active column instance */
typedef struct {
ColumnSpec *spec;
int enabled;
} ActiveColumn;
/* Convert context type string between compact and full form */
static const char* display_context(const char *context_type, int compact) {
/* Database now stores compact form, so if compact mode, return as-is */
if (compact) return context_type;
/* Convert compact to full: convert string to enum and back with full flag */
char upper[CONTEXT_TYPE_MAX_LENGTH];
snprintf(upper, sizeof(upper), "%s", context_type);
to_upper(upper);
ContextType type = string_to_context(upper);
return context_to_string(type, 0);
}
/* Print an "unrecognized context type" error with the accepted names, for a
* bad -i/-x argument. `flag` is "-i" or "-x"; `given` is the user's raw arg. */
static void report_invalid_context(const char *flag, const char *given) {
fprintf(stderr, "Error: unrecognized context type '%s' for %s.\n", given, flag);
fprintf(stderr, "Valid types: class iface func arg var exc type prop com str file "
"imp exp call ns enum case trait lam label goto macro\n");
fprintf(stderr, "Note: Go structs index as 'class', interfaces as 'iface'.\n");
}
/* Flag presence bits */
typedef enum {
FLAG_COLUMNS = 1 << 0,
FLAG_VERBOSE = 1 << 1,
FLAG_LIMIT = 1 << 2,
FLAG_INCLUDE = 1 << 3,
FLAG_EXCLUDE = 1 << 4,
FLAG_COMPACT = 1 << 5,
FLAG_FILE = 1 << 6,
FLAG_SAME_LINE = 1 << 7,
FLAG_CONTEXT_AFTER = 1 << 8,
FLAG_CONTEXT_BEFORE = 1 << 9,
FLAG_CONTEXT_BOTH = 1 << 10,
FLAG_FILES_ONLY = 1 << 11,
FLAG_DB_FILE = 1 << 12,
/* X-Macro: Generate FLAG bits for extensible columns */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
FLAG_##long_flag = 1 << (__COUNTER__ + 13),
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
FLAG_##long_flag = 1 << (__COUNTER__ + 13),
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
FLAG_LAST /* Sentinel */
} CliFlags;
/* Check which flags are present in CLI args */
static int scan_cli_flags(int argc, char *argv[]) {
int flags = 0;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--columns") == 0) flags |= FLAG_COLUMNS;
else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) flags |= FLAG_VERBOSE;
else if (strcmp(argv[i], "--limit") == 0 || strcmp(argv[i], "-l") == 0) flags |= FLAG_LIMIT;
else if (strcmp(argv[i], "--files") == 0) flags |= FLAG_FILES_ONLY;
else if (strcmp(argv[i], "--db-file") == 0) flags |= FLAG_DB_FILE;
else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--include-context") == 0) flags |= FLAG_INCLUDE;
else if (strcmp(argv[i], "-x") == 0 || strcmp(argv[i], "--exclude-context") == 0) flags |= FLAG_EXCLUDE;
else if (strcmp(argv[i], "--compact") == 0) flags |= FLAG_COMPACT;
else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) flags |= FLAG_FILE;
else if (strcmp(argv[i], "--and") == 0 || strcmp(argv[i], "--same-line") == 0) flags |= FLAG_SAME_LINE;
else if (strcmp(argv[i], "-A") == 0) flags |= FLAG_CONTEXT_AFTER;
else if (strcmp(argv[i], "-B") == 0) flags |= FLAG_CONTEXT_BEFORE;
else if (strcmp(argv[i], "-C") == 0) flags |= FLAG_CONTEXT_BOTH;
/* X-Macro: Check for extensible column flags */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
else if (strcmp(argv[i], "--" #long_flag) == 0 || strcmp(argv[i], "-" #short_flag) == 0) flags |= FLAG_##long_flag;
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
else if (strcmp(argv[i], "--" #long_flag) == 0 || strcmp(argv[i], "-" #short_flag) == 0) flags |= FLAG_##long_flag;
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
}
return flags;
}
/* Check if config line should be skipped based on CLI flags */
static int should_skip_config_line(const char *line, int cli_flags) {
if ((cli_flags & FLAG_COLUMNS) && strstr(line, "--columns") == line) return 1;
if ((cli_flags & FLAG_VERBOSE) && (strstr(line, "-v") == line || strstr(line, "--verbose") == line)) return 1;
if ((cli_flags & FLAG_LIMIT) && (strstr(line, "--limit") == line || strstr(line, "-l") == line)) return 1;
if ((cli_flags & FLAG_FILES_ONLY) && strstr(line, "--files") == line) return 1;
if ((cli_flags & FLAG_DB_FILE) && strstr(line, "--db-file") == line) return 1;
if ((cli_flags & FLAG_INCLUDE) && (strstr(line, "-i") == line || strstr(line, "--include-context") == line)) return 1;
if ((cli_flags & FLAG_EXCLUDE) && (strstr(line, "-x") == line || strstr(line, "--exclude-context") == line)) return 1;
if ((cli_flags & FLAG_COMPACT) && strstr(line, "--compact") == line) return 1;
if ((cli_flags & FLAG_FILE) && (strstr(line, "-f") == line || strstr(line, "--file") == line)) return 1;
if ((cli_flags & FLAG_SAME_LINE) && (strstr(line, "--and") == line || strstr(line, "--same-line") == line)) return 1;
if ((cli_flags & FLAG_CONTEXT_AFTER) && strstr(line, "-A") == line) return 1;
if ((cli_flags & FLAG_CONTEXT_BEFORE) && strstr(line, "-B") == line) return 1;
if ((cli_flags & FLAG_CONTEXT_BOTH) && strstr(line, "-C") == line) return 1;
/* X-Macro: Skip config lines for extensible column flags */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if ((cli_flags & FLAG_##long_flag) && (strstr(line, "-" #short_flag) == line || strstr(line, "--" #long_flag) == line)) return 1;
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if ((cli_flags & FLAG_##long_flag) && (strstr(line, "-" #short_flag) == line || strstr(line, "--" #long_flag) == line)) return 1;
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
return 0;
}
/* Load .smconfig (./.smconfig preferred, else ~/.smconfig) and append its args
* to argv (config args go after the CLI args, so CLI flags take precedence). */
/* HOST_ONLY: reads CLI defaults from the cwd/HOME and the local filesystem. */
static int load_config_file(int *argc_ptr, char ***argv_ptr, int cli_flags) {
/* Security note: We trust HOME environment variable for config file location.
* If an attacker can set HOME, they can already execute arbitrary code in this
* process context. Config file is optional and only affects query defaults. */
char config_path[PATH_MAX_LENGTH];
if (!resolve_smconfig_path(config_path, sizeof(config_path))) return 0;
FILE *f = safe_fopen(config_path, "r", 1);
if (!f) return 0; /* No config file is fine */
/* Count lines and allocate space for new argv */
char line[LINE_BUFFER_MEDIUM];
int config_arg_count = 0;
char *config_args[MAX_PATTERNS * 2]; /* Max config arguments */
/* Track if we're in the [qi] section */
int in_qi_section = 0;
/* Parse config file */
while (fgets(line, sizeof(line), f)) {
/* Remove trailing newline */
size_t len = strnlength(line, sizeof(line));
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
line[--len] = '\0';
}
/* Skip empty lines and comments */
char *trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') trimmed++;
if (*trimmed == '\0' || *trimmed == '#') continue;
/* Check for section headers */
if (*trimmed == '[') {
in_qi_section = (strcmp(trimmed, "[qi]") == 0);
continue;
}
/* Only process lines in the [qi] section */
if (!in_qi_section) continue;
/* Skip lines for flags present in CLI */
if (should_skip_config_line(trimmed, cli_flags)) continue;
/* Parse line as space-separated arguments (use strtok_r for thread safety) */
char *saveptr;
char *token = strtok_r(trimmed, " \t", &saveptr);
while (token != NULL && config_arg_count < MAX_PATTERNS * 2) {
config_args[config_arg_count] = try_strdup_ctx(token, "Failed to allocate memory for config argument");
if (!config_args[config_arg_count]) {
/* Cleanup already allocated config args */
for (int j = 0; j < config_arg_count; j++) {
free(config_args[j]);
}
fclose(f);
return -1;
}
config_arg_count++;
token = strtok_r(NULL, " \t", &saveptr);
}
}
fclose(f);
if (config_arg_count == 0) return 0;
/* Create new argv with: [program name] + [original CLI args] + [config args] */
int old_argc = *argc_ptr;
char **old_argv = *argv_ptr;
int new_argc = old_argc + config_arg_count;
char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(new_argc + 1));
if (!new_argv) {
fprintf(stderr, "Error: Failed to allocate memory for config args\n");
/* Cleanup config args */
for (int j = 0; j < config_arg_count; j++) {
free(config_args[j]);
}
return -1;
}
/* Copy program name and original CLI args */
for (int i = 0; i < old_argc; i++) {
new_argv[i] = old_argv[i];
}
/* Append config args */
for (int i = 0; i < config_arg_count; i++) {
new_argv[old_argc + i] = config_args[i];
}
new_argv[new_argc] = NULL;
/* Update argc and argv */
*argc_ptr = new_argc;
*argv_ptr = new_argv;
return 0;
}
/* Check if a word (case-insensitive) exists in a filter file */
/*
static int is_in_filter_file(const char *word, const char *filepath) {
FILE *f = safe_fopen(filepath, "r", 1);
if (!f) {
return 0;
}
char line[LINE_BUFFER_MEDIUM];
char lowercase_word[LINE_BUFFER_MEDIUM];
snprintf(lowercase_word, sizeof(lowercase_word), "%s", word);
to_lower(lowercase_word);
while (fgets(line, sizeof(line), f)) {
// Remove trailing newline/whitespace
size_t len = strnlength(line, sizeof(line));
while (len > 0 && isspace(line[len - 1])) {
line[--len] = '\0';
}
// Skip empty lines
if (len == 0) continue;
// Convert to lowercase for comparison
to_lower(line);
if (strcmp(line, lowercase_word) == 0) {
fclose(f);
return 1;
}
}
fclose(f);
return 0;
}
*/
/* Check if pattern contains unescaped wildcards (% or _) */
static int has_wildcards(const char *pattern) {
for (size_t i = 0; pattern[i]; i++) {
/* Check if this is an escaped character */
if (pattern[i] == '\\' && (pattern[i+1] == '%' || pattern[i+1] == '_' ||
pattern[i+1] == '*' || pattern[i+1] == '.' ||
pattern[i+1] == '\\')) {
i++; /* Skip the escaped character */
continue;
}
/* Check for unescaped wildcards (SQL LIKE % and _, or shell-style * and .) */
if (pattern[i] == '%' || pattern[i] == '_' || pattern[i] == '*' || pattern[i] == '.') {
return 1;
}
}
return 0;
}
/* Remove escape sequences from pattern for filter checking */
static void unescape_pattern(const char *pattern, char *output, size_t output_size) {
size_t j = 0;
for (size_t i = 0; pattern[i] && j < output_size - 1; i++) {
if (pattern[i] == '\\' && (pattern[i+1] == '%' || pattern[i+1] == '_' || pattern[i+1] == '\\')) {
output[j++] = pattern[i+1]; /* Copy the escaped character */
i++; /* Skip the backslash */
} else {
output[j++] = pattern[i];
}
}
output[j] = '\0';
}
/* Convert shell-style wildcards (*) to SQL LIKE wildcards (%)
* Also handles escaped characters to preserve \*, \%, \_, \\
*/
static void convert_wildcards(const char *pattern, char *output, size_t output_size) {
size_t j = 0;
for (size_t i = 0; pattern[i] && j < output_size - 1; i++) {
/* Check if this is an escaped character */
if (pattern[i] == '\\' && (pattern[i+1] == '*' || pattern[i+1] == '.' ||
pattern[i+1] == '%' || pattern[i+1] == '_' ||
pattern[i+1] == '\\')) {
/* Handle escaped characters:
* \* and \. -> just the literal character (no escaping needed in SQL)
* \%, \_, \\ -> keep the backslash (SQL ESCAPE clause handles these) */
if (pattern[i+1] == '*' || pattern[i+1] == '.') {
/* Drop the backslash, just copy the literal character */
output[j++] = pattern[i+1];
} else {
/* Keep backslash for SQL wildcards and backslash itself */
output[j++] = '\\';
if (j < output_size - 1) {
output[j++] = pattern[i+1];
}
}
i++; /* Skip the escaped character */
} else if (pattern[i] == '*') {
/* Convert unescaped * to % (SQL multi-char wildcard) */
output[j++] = '%';
} else if (pattern[i] == '.') {
/* Convert unescaped . to _ (SQL single-char wildcard) */
output[j++] = '_';
} else {
/* Copy everything else as-is */
output[j++] = pattern[i];
}
}
output[j] = '\0';
}
/* Split a term on the alternation operator '|' (the grep-ism '\|' is also
* accepted). Writes up to max_out newly-allocated segments into out[] and
* returns the count; empty segments produced by a leading, trailing, or
* doubled separator are dropped. The caller owns and must free each segment.
* '|' is never a valid identifier character or a qi wildcard, so the split is
* unambiguous. */
static int split_alternation(const char *term, char *out[], int max_out) {
int count = 0;
const char *seg_start = term;
const char *p = term;
while (count < max_out) {
int sep_len = 0;
if (p[0] == '\\' && p[1] == '|') {
sep_len = 2;
} else if (p[0] == '|') {
sep_len = 1;
}
if (sep_len > 0 || *p == '\0') {
size_t len = (size_t)(p - seg_start);
if (len > 0) {
char seg[SYMBOL_MAX_LENGTH];
if (len >= sizeof(seg)) {
len = sizeof(seg) - 1;
}
memcpy(seg, seg_start, len);
seg[len] = '\0';
out[count++] = safe_strdup_ctx(seg,
"Failed to allocate memory for alternation segment");
}
if (*p == '\0') {
break;
}
p += sep_len;
seg_start = p;
} else {
p++;
}
}
return count;
}
/* Records the first grep-style alternation that was split, so a single warning
* can be emitted (with the user's actual terms) after all args are parsed. */
typedef struct {
char *original; /* the offending term as entered, e.g. "Renew\|Session" */
char *alternatives; /* its split terms re-quoted and space-joined: 'Renew' 'Session' */
const char *sep; /* the separator form the user typed: "\\|" or "|" */
} AltWarning;
/* Records a dotted qualified name (e.g. "Some.function") captured from the
* ORIGINAL argv token at parse time -- before convert_wildcards rewrites '.'
* to the '_' LIKE wildcard, which would be indistinguishable from a snake_case
* symbol. Drives the qualified-name auto-retry / Tip in print_results_by_file. */
typedef struct {
int active; /* a dotted qualified name was captured */
char original[SYMBOL_MAX_LENGTH]; /* the token as entered, e.g. "Some.function" */
char qualifier[SYMBOL_MAX_LENGTH]; /* before the last dot, e.g. "Some" */
char symbol[SYMBOL_MAX_LENGTH]; /* after the last dot, e.g. "function" */
} QualifiedName;
/* Capture warning data for the first split term only (keep the message focused
* on one example). `original` is the term as entered; `segs`/`nseg` are its raw
* split alternatives. Echoes the separator form the user actually used. */
static void capture_alt_warning(const char *original, char *const segs[], int nseg,
AltWarning *w) {
if (w->original != NULL) {
return; /* already captured an earlier term */
}
w->sep = strstr(original, "\\|") ? "\\|" : "|";
w->original = safe_strdup_ctx(original,
"Failed to allocate memory for alternation warning");
/* Build "'seg0' 'seg1' ...": two quotes per term, a space between, plus NUL. */
size_t cap = 1;
for (int i = 0; i < nseg; i++) {
cap += strlen(segs[i]) + 3;
}
char *buf = malloc(cap);
if (!buf) {
fprintf(stderr, "Failed to allocate memory for alternation warning\n");
exit(1);
}
size_t pos = 0;
for (int i = 0; i < nseg; i++) {
pos += (size_t)snprintf(buf + pos, cap - pos, "%s'%s'", i ? " " : "", segs[i]);
}
w->alternatives = buf;
}
/* Check if a word matches any regex pattern in the regex-patterns file */
/*
static int matches_regex_filter(const char *word, const char *filepath) {
FILE *f = safe_fopen(filepath, "r", 1);
if (!f) {
return 0;
}
char line[LINE_BUFFER_MEDIUM];
regex_t regex;
int matched = 0;
while (fgets(line, sizeof(line), f)) {
// Remove trailing newline
line[strcspn(line, "\n")] = '\0';
// Skip empty lines and comments
if (line[0] == '\0' || line[0] == '#') {
continue;
}
// Compile and test the regex pattern
int ret = regcomp(®ex, line, REG_EXTENDED | REG_NOSUB);
if (ret == 0) {
if (regexec(®ex, word, 0, NULL, 0) == 0) {
matched = 1;
regfree(®ex);
break;
}
regfree(®ex);
}
}
fclose(f);
return matched;
}
*/
/* Column getter functions - extract data from RowData */
static const void* get_line_col(RowData *data) {
return &data->line;
}
static const void* get_context_col(RowData *data) {
return data->context;
}
static const void* get_symbol_col(RowData *data) {
return data->full_symbol;
}
/* X-Macro: Generate getter functions for extensible columns */
#define COLUMN(name, ...) \
static const void* get_##name##_col(RowData *data) { \
return data->name; \
}
#define INT_COLUMN(name, ...) \
static const void* get_##name##_col(RowData *data) { \
return &data->name; \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
/* Column registry - all available columns */
static ColumnSpec column_registry[] = {
/* Core columns (traditional) */
{"line", "LINE", "LINE", 4, COL_TYPE_INT, get_line_col},
{"context", "CONTEXT", "CTX", 7, COL_TYPE_STRING, get_context_col},
{"symbol", "SYMBOL", "SYM", 0, COL_TYPE_STRING, get_symbol_col},
/* X-Macro: Extensible filterable columns */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
{#long_flag, full, compact, width, c_type, get_##name##_col},
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
{#long_flag, full, compact, width, c_type, get_##name##_col},
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
{NULL, NULL, NULL, 0, 0, NULL} /* sentinel */
};
/* Active columns - what will be displayed */
static ActiveColumn active_columns[MAX_CONTEXT_TYPES];
static int num_active_columns = 0;
/* Find column by name (supports aliases from compact column names) */
static ColumnSpec* find_column_by_name(const char *name) {
/* Check for compact name aliases using X-Macro (case-insensitive) */
const char *full_name = name;
#define COLUMN(db_name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if (strcasecmp(name, compact) == 0) { \
full_name = #long_flag; \
}
#define INT_COLUMN(db_name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if (strcasecmp(name, compact) == 0) { \
full_name = #long_flag; \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
/* Also check common abbreviations for core columns */
if (strcasecmp(name, "sym") == 0) full_name = "symbol";
else if (strcasecmp(name, "ctx") == 0) full_name = "context";
/* Look up in registry */
for (int i = 0; column_registry[i].name != NULL; i++) {
if (strcmp(column_registry[i].name, full_name) == 0) {
return &column_registry[i];
}
}
return NULL;
}
/* Add a column by name (used when parsing --columns) */
static int add_column_by_name(const char *name) {
ColumnSpec *spec = find_column_by_name(name);
if (spec) {
if (num_active_columns < MAX_CONTEXT_TYPES) {
active_columns[num_active_columns++] = (ActiveColumn){spec, 1};
return 1;
}
} else {
fprintf(stderr, "Warning: unknown column '%s' (available: line, context, parent, scope, modifier, clue, namespace, type, definition, symbol)\n", name);
}
return 0;
}
/* Setup default columns based on flags */
static void setup_default_columns(int verbose, QueryFilters *filters, ShowColumns *show_columns) {
num_active_columns = 0;
/* Always: line, symbol */
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name("line"), 1};
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name("symbol"), 1};
/* Verbose: all extensible columns */
if (verbose) {
/* X-Macro: Add all extensible columns in verbose mode */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name(#long_flag), 1};
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name(#long_flag), 1};
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
} else if (filters || show_columns) {
/* Non-verbose: Add columns that have active filters OR show flags */
/* X-Macro: Add columns with active filters or show flags */
#define COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if ((filters && filters->name.count > 0) || (show_columns && show_columns->name)) { \
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name(#long_flag), 1}; \
}
#define INT_COLUMN(name, sql_type, c_type, width, full, compact, long_flag, short_flag, ...) \
if ((filters && filters->name.count > 0) || (show_columns && show_columns->name)) { \
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name(#long_flag), 1}; \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
}
/* Always: context */
active_columns[num_active_columns++] = (ActiveColumn){find_column_by_name("context"), 1};
}
static void print_table_header(int compact, int quiet) {
if (!quiet) printf("\n");
/* Print header row */
for (int i = 0; i < num_active_columns; i++) {
if (!active_columns[i].enabled) continue;
if (i > 0) printf(" | ");
ColumnSpec *spec = active_columns[i].spec;
if (!spec) continue;
const char *header = compact ? spec->header_compact : spec->header;
if (spec->width > 0) {
printf("%-*s", spec->width, header);
} else {
printf("%s", header);
}
}
printf("\n");
/* Print separator line (decoration; suppressed in quiet mode) */
if (!quiet) {
for (int i = 0; i < num_active_columns; i++) {
if (!active_columns[i].enabled) continue;
if (i > 0) printf("-+-");
ColumnSpec *spec = active_columns[i].spec;
if (!spec) continue;
int width = spec->width > 0 ? spec->width : 24; /* default width for variable columns */
for (int j = 0; j < width; j++) {
printf("-");
}
}
printf("\n");
}
}
static void print_table_row(RowData *data, int compact) {
for (int i = 0; i < num_active_columns; i++) {
if (!active_columns[i].enabled) continue;
if (i > 0) printf(" | ");
ColumnSpec *spec = active_columns[i].spec;
if (!spec) continue;
const void *value = spec->getter(data);
if (spec->type == COL_TYPE_INT) {
printf("%-*d", spec->width, *(const int*)value);
} else { /* COL_TYPE_STRING */
const char *str = (const char*)value;
/* Apply compact display for context column */
if (strcmp(spec->name, "context") == 0 && str) {
str = display_context(str, compact);
}
if (spec->width > 0) {
printf("%-*s", spec->width, str ? str : "");
} else {
printf("%s", str ? str : "");
}
}
}
printf("\n");
}
/* Print header for all-columns mode */
static void print_all_columns_header(int quiet) {
if (!quiet) printf("\n");
/* Print internal column headers */
printf("%-24s | %-16s | %-4s | %-20s | %-3s | %-24s | %-20s",
"DIRECTORY", "FILENAME", "LINE", "SYMBOL", "CTX", "FULL_SYMBOL", "SOURCE_LOCATION");
/* Print extensible column headers */
for (int i = 0; column_registry[i].name != NULL; i++) {
printf(" | %-12s", column_registry[i].header_compact);
}
printf("\n");
/* Print separator line (decoration; suppressed in quiet mode) */
if (!quiet) {
printf("------------------------+------------------+------+----------------------+-----+--------------------------+----------------------");
for (int i = 0; column_registry[i].name != NULL; i++) {
printf("+-------------");
}
printf("\n");
}
}
/* Print all columns (internal + extensible) - used for --columns all */
static void print_all_columns_row(RowData *data) {
/* Print internal/core columns in fixed order with proper formatting */
printf("%-24s | %-16s | %-4d | %-20s | %-3s | %-24s | %-20s",
data->directory ? data->directory : "",
data->filename ? data->filename : "",
data->line,
data->symbol ? data->symbol : "",
data->context ? data->context : "",
data->full_symbol ? data->full_symbol : "",
data->source_location ? data->source_location : "");
/* Print extensible columns from registry with proper formatting */
for (int i = 0; column_registry[i].name != NULL; i++) {
ColumnSpec *spec = &column_registry[i];
const void *value = spec->getter(data);
printf(" | ");
if (spec->type == COL_TYPE_INT) {
int int_val = *(const int*)value;
printf("%-12d", int_val);
} else { /* COL_TYPE_STRING */
const char *str = (const char*)value;
printf("%-12s", str ? str : "");
}
}
printf("\n");
}
/* Process file pattern into directory and filename parts with %/ boundary matching
* Returns: 0 on success, -1 on allocation failure */
/* WEB_SAFE: normalizes file-pattern filters without requiring host services. */
static int process_file_pattern(const char *input, char **dir_out, char **file_out) {
/* Handle extension shorthand BEFORE wildcard conversion: .c → %.c, .h → %.h, etc.
* Must use raw input so '.' stays literal rather than becoming '_' (LIKE wildcard). */
if (input[0] == '.' && input[1] != '/' && input[1] != '.') {
size_t pattern_len = strlen(input) + 2; /* % + extension + \0 */
char *expanded = malloc(pattern_len);
if (!expanded) {
fprintf(stderr, "Error: Failed to allocate memory for file pattern\n");
*dir_out = NULL;
*file_out = NULL;
return -1;
}
snprintf(expanded, pattern_len, "%%%s", input);
*dir_out = NULL;
*file_out = expanded;
return 0;
}
/* Convert shell-style wildcards (*) to SQL LIKE wildcards (%) */
char converted_input[PATH_MAX_LENGTH];
convert_wildcards(input, converted_input, sizeof(converted_input));
const char *last_slash = strrchr(converted_input, '/');
if (!last_slash) {
/* No slash - filename only */
*dir_out = NULL;
*file_out = try_strdup_ctx(converted_input, "Failed to allocate memory for filename");
if (!*file_out) {
return -1;
}
return 0;
}
/* Split on last slash */
size_t dir_len = (size_t)(last_slash - converted_input);
char *dir_part = strndup(converted_input, dir_len);
if (!dir_part) {
fprintf(stderr, "Error: Failed to allocate memory for directory part\n");
return -1;
}
const char *file_after_slash = last_slash + 1;
/* If empty filename (trailing slash), use % wildcard for all files */
char *file_part = strlen(file_after_slash) > 0 ?
try_strdup_ctx(file_after_slash, "Failed to allocate memory for file part") :
try_strdup_ctx("%", "Failed to allocate memory for file part");
if (!file_part) {
free(dir_part);
return -1;
}
/* Normalize directory part */
int needs_prefix = 1;
/* Check if starts with ./ or ../ or / (absolute) */
if (dir_part[0] == '.' && (dir_part[1] == '/' ||
(dir_part[1] == '.' && dir_part[2] == '/'))) {
needs_prefix = 0; /* Explicit relative path */
} else if (dir_part[0] == '/') {
needs_prefix = 0; /* Absolute path */
}
/* Add prefix for boundary matching.
* Single-component names (e.g. "perl") use %/ to avoid matching "myperl/".
* Multi-component paths (e.g. "tools/sources/perl") use % only — the path
* is already specific enough, and %/ would require a character before the
* first component, failing to match top-level relative paths. */
if (needs_prefix) {
int is_multi = (strchr(dir_part, '/') != NULL);
size_t new_len = strlen(dir_part) + 4; /* %/ + / + \0 */
char *prefixed = malloc(new_len);
if (!prefixed) {
fprintf(stderr, "Error: Failed to allocate memory for directory prefix\n");
free(dir_part);
free(file_part);
return -1;
}
snprintf(prefixed, new_len, is_multi ? "%%%s/" : "%%/%s/", dir_part);
free(dir_part);
dir_part = prefixed;
} else {
/* Add trailing slash to explicit paths too */
size_t new_len = strlen(dir_part) + 2; /* / + \0 */
char *with_slash = malloc(new_len);
if (!with_slash) {
fprintf(stderr, "Error: Failed to allocate memory for directory slash\n");
free(dir_part);
free(file_part);
return -1;
}
snprintf(with_slash, new_len, "%s/", dir_part);
free(dir_part);
dir_part = with_slash;
}
*dir_out = dir_part;
*file_out = file_part;
return 0;
}
/* Helper function to build common filter clauses (file, context type, extensible columns)
* Returns: 0 on success, -1 on error (buffer overflow or allocation failure)
*/
/* WEB_SAFE: builds SQL filter clauses over indexed metadata only. */
static int build_common_filters(SqlQueryBuilder *builder,
ContextTypeList *include, ContextTypeList *exclude,
QueryFilters *filters, FileFilterList *file_filter,
WithinRangeList *within_ranges, int debug) {
/* Add file filter (directory + filename) */
if (file_filter && file_filter->count > 0) {
if (sql_append(builder, " AND (") != 0) return -1;
for (int i = 0; i < file_filter->count; i++) {
if (i > 0) {
if (sql_append(builder, " OR ") != 0) return -1;
}
if (file_filter->patterns[i].directory != NULL) {
/* Has directory part - filter both columns */
char *escaped_dir = sqlite3_mprintf("%q", file_filter->patterns[i].directory);
char *escaped_file = sqlite3_mprintf("%q", file_filter->patterns[i].filename);
int ret = sql_append(builder,
"(directory LIKE '%s' ESCAPE '\\' AND filename LIKE '%s' ESCAPE '\\')",
escaped_dir, escaped_file);
sqlite3_free(escaped_dir);
sqlite3_free(escaped_file);
if (ret != 0) return -1;
} else {
/* No directory part - filter filename only */
char *escaped_file = sqlite3_mprintf("%q", file_filter->patterns[i].filename);
int ret = sql_append(builder,
"filename LIKE '%s' ESCAPE '\\'",
escaped_file);
sqlite3_free(escaped_file);