-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqi-web-entry.c
More file actions
2545 lines (2347 loc) · 109 KB
/
Copy pathqi-web-entry.c
File metadata and controls
2545 lines (2347 loc) · 109 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
/*
* qi-web-entry.c -- Browser/WASM bridge for the qi query tool.
*
* NO sqlite3 linked. JS owns the DB (@sqlite.org/sqlite-wasm).
* This module builds SQL and formats qi-style output from raw result rows.
*
* Exports:
* qi_web_build(command) -> build-info string (SQL, patterns, limit)
* qi_web_format(build_info, rows_tsv, total, shown) -> formatted qi output
* qi_web_format_breakdown(tsv) -> "Results CTX Totals: ..." + Tip line
* qi_web_format_files(tsv, shown, total) -> file list + "Found N files"
* qi_web_free_result(ptr) -> free a result string
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <emscripten.h>
#include "query-index-web.h"
#include "shared/sql_builder.h"
#include "shared-web/toc-web.h"
#include "shared-web/source-render-web.h"
/* Forward declarations for sqlite3 shim (defined in query-index-web.c, linked together) */
char *sqlite3_mprintf(const char *fmt, ...);
void sqlite3_free(void *ptr);
/* Output accumulator shared with toc-web.c and source-render-web.c. */
#include "web_output.h"
/* -- Tokenizer (mirrors html/app.js tokenizeCommand) -- */
static char **tokenize(const char *input, int *out_count) {
int cap = 8;
char **tokens = malloc((size_t)cap * sizeof(char *));
if (!tokens) { *out_count = 0; return NULL; }
int count = 0;
const char *p = input;
while (*p) {
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++;
if (!*p) break;
char quote = 0;
char buf[4096];
int bi = 0;
if (*p == '"' || *p == '\'') {
quote = *p++;
}
while (*p) {
if (quote) {
if (*p == '\\' && p[1]) { buf[bi++] = p[1]; p += 2; continue; }
if (*p == quote) { p++; break; }
buf[bi++] = *p++;
} else {
if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') break;
if (*p == '\\' && p[1]) { buf[bi++] = p[1]; p += 2; continue; }
buf[bi++] = *p++;
}
if (bi >= 4095) break;
}
buf[bi] = '\0';
if (count >= cap) {
cap *= 2;
char **nt = realloc(tokens, (size_t)cap * sizeof(char *));
if (!nt) { *out_count = count; return tokens; }
tokens = nt;
}
tokens[count++] = strdup(buf);
}
*out_count = count;
return tokens;
}
static void free_tokens(char **tokens, int count) {
for (int i = 0; i < count; i++) free(tokens[i]);
free(tokens);
}
/* -- Context alias mapping (mirrors html/app.js CONTEXT_ALIASES) -- */
/* -- Command parser -- */
typedef struct {
char *values[MAX_CONTEXT_TYPES];
int count;
int show;
} WebColFilter;
typedef struct {
WebColFilter parent;
WebColFilter scope;
WebColFilter ns; /* namespace */
WebColFilter modifier;
WebColFilter clue;
WebColFilter type;
WebColFilter definition;
WebColFilter parent_type; /* virtual: --parent-type, no backing column */
} WebColFlags;
typedef struct {
char *patterns[MAX_PATTERNS];
int pattern_count;
char *includes[MAX_CONTEXT_TYPES];
int include_count;
char *excludes[MAX_CONTEXT_TYPES];
int exclude_count;
char *files[MAX_CONTEXT_TYPES];
int file_count;
int definition; /* -1=none, 0=usage, 1=def */
int limit;
int verbose;
int compact;
int debug;
char *column_names[MAX_CONTEXT_TYPES];
int column_count;
WebColFlags cf;
int line_range; /* -1=none, 0=and-same-line, >0=and-with-range */
char *within_symbols[MAX_PATTERNS]; /* --within symbols */
int within_count;
int error;
char *error_msg;
int error_msg_malloced; /* 1 if error_msg was strdup'd and must be freed */
int help; /* --help / -h: show help text */
int list_types; /* --list-types: show context-type table */
int version; /* --version: show version info */
int oom; /* set when any strdup fails during parsing */
int toc_mode;
int files_mode; /* --files: show only unique file paths */
int expand; /* -e/--expand: expand full definitions */
int context_before; /* -B / -C: lines of context before each match */
int context_after; /* -A / -C: lines of context after each match */
int raw; /* --raw: bare source only, suppress all framing */
int limit_per_file; /* --limit-per-file: max matches shown per file */
int quiet; /* -q/--quiet: drop banner/footer/rule chrome; keep header + rows */
/* First grep-style alternation split, for the educational warning (mirrors
* AltWarning in query-index.c); alt_original stays NULL if none occurred. */
char *alt_original; /* the offending term as entered, e.g. "Renew\|Session" */
char *alt_alternatives; /* its split terms re-quoted and space-joined: 'Renew' 'Session' */
const char *alt_sep; /* the separator form the user typed: "\\|" or "|" */
} WebCommand;
static void free_col_filter(WebColFilter *f) {
for (int i = 0; i < f->count; i++) free(f->values[i]);
f->count = 0;
f->show = 0;
}
/* Allocate a copy of s; on failure, mark the command as OOM and return NULL.
* Wrapped strdup calls in parse_command pass through here so a single NULL
* check at the done: label catches all allocation failures without
* littering individual NULL checks everywhere. */
static char *cmd_strdup(WebCommand *cmd, const char *s) {
char *p = strdup(s);
if (!p) cmd->oom = 1;
return p;
}
/* Set an error message on the command. error_msg_malloced tracks whether
* the pointer came from strdup and must be freed. */
#define SET_CMD_ERROR(cmd, s) do { \
(cmd)->error = 1; \
(cmd)->error_msg = strdup(s); \
(cmd)->error_msg_malloced = 1; \
} while(0)
/* Split a term on the alternation operator '|' (the grep-ism '\|' is also
* accepted). Mirrors split_alternation() in query-index.c, but allocates via
* cmd_strdup so an allocation failure marks the command OOM instead of
* exiting. 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. */
static int split_alternation_web(WebCommand *cmd, 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] = cmd_strdup(cmd, seg);
if (out[count]) count++;
}
if (*p == '\0') {
break;
}
p += sep_len;
seg_start = p;
} else {
p++;
}
}
return count;
}
/* Capture warning data for the first split term only (keep the message focused
* on one example), mirroring capture_alt_warning() in query-index.c. Echoes
* the separator form the user actually typed. */
static void capture_alt_warning_web(WebCommand *cmd, const char *original,
char *const segs[], int nseg) {
if (cmd->alt_original != NULL) {
return; /* already captured an earlier term */
}
cmd->alt_sep = strstr(original, "\\|") ? "\\|" : "|";
cmd->alt_original = cmd_strdup(cmd, original);
/* 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) {
cmd->oom = 1;
return;
}
size_t pos = 0;
for (int i = 0; i < nseg; i++) {
pos += (size_t)snprintf(buf + pos, cap - pos, "%s'%s'", i ? " " : "", segs[i]);
}
cmd->alt_alternatives = buf;
}
static void free_command(WebCommand *cmd) {
for (int i = 0; i < cmd->pattern_count; i++) free(cmd->patterns[i]);
for (int i = 0; i < cmd->include_count; i++) free(cmd->includes[i]);
for (int i = 0; i < cmd->exclude_count; i++) free(cmd->excludes[i]);
for (int i = 0; i < cmd->file_count; i++) free(cmd->files[i]);
for (int i = 0; i < cmd->column_count; i++) free(cmd->column_names[i]);
for (int i = 0; i < cmd->within_count; i++) free(cmd->within_symbols[i]);
if (cmd->error_msg_malloced) free(cmd->error_msg);
free(cmd->alt_original);
free(cmd->alt_alternatives);
free_col_filter(&cmd->cf.parent);
free_col_filter(&cmd->cf.scope);
free_col_filter(&cmd->cf.ns);
free_col_filter(&cmd->cf.modifier);
free_col_filter(&cmd->cf.clue);
free_col_filter(&cmd->cf.type);
free_col_filter(&cmd->cf.definition);
free_col_filter(&cmd->cf.parent_type);
memset(cmd, 0, sizeof(*cmd));
cmd->definition = -1;
cmd->limit = 0; /* 0 = unlimited, matching the native CLI default (limit=0) */
cmd->line_range = -1;
cmd->toc_mode = 0;
}
static int is_flag(const char *token) {
return token[0] == '-';
}
/* Parse values for a column filter flag. Always sets show=1, then
* collects any following non-flag tokens as filter values. Each value is
* split on grep-style alternation 'A|B' into separate OR'd values. */
static void parse_col_flag_values(WebColFilter *cf, char **tokens, int tc, int *i,
WebCommand *cmd) {
cf->show = 1;
while (*i + 1 < tc && !is_flag(tokens[*i + 1])) {
(*i)++;
char *fsegs[MAX_CONTEXT_TYPES];
int fnseg = split_alternation_web(cmd, tokens[*i], fsegs, MAX_CONTEXT_TYPES);
if (fnseg > 1) capture_alt_warning_web(cmd, tokens[*i], fsegs, fnseg);
for (int fs = 0; fs < fnseg; fs++) {
if (cf->count < MAX_CONTEXT_TYPES)
cf->values[cf->count++] = fsegs[fs];
else
free(fsegs[fs]);
}
}
}
/* Parse the optional NUM after -A/-B/-C: an integer in [0, MAXIMUM_CONTEXT_RANGE],
* or DEFAULT_CONTEXT_RANGE when absent (mirrors the native CLI). Consumes the
* number token when present. On an invalid/out-of-range value, sets the command
* error and returns -1. */
static int parse_context_value(char **tokens, int tc, int *i, WebCommand *cmd) {
if (*i + 1 < tc && !is_flag(tokens[*i + 1])) {
const char *arg = tokens[*i + 1];
int valid = (arg[0] != '\0');
for (int ci = 0; arg[ci]; ci++)
if (!isdigit((unsigned char)arg[ci])) { valid = 0; break; }
if (!valid) {
SET_CMD_ERROR(cmd, "context flag requires a non-negative integer (0-100).");
return -1;
}
int val = atoi(arg);
if (val > MAXIMUM_CONTEXT_RANGE) {
SET_CMD_ERROR(cmd, "context value cannot exceed 100.");
return -1;
}
(*i)++;
return val;
}
return DEFAULT_CONTEXT_RANGE;
}
static WebCommand parse_command(const char *input) {
WebCommand cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.definition = -1;
cmd.limit = 0; /* 0 = unlimited, matching the native CLI default (limit=0) */
cmd.compact = 1;
cmd.line_range = -1;
int tc = 0;
char **tokens = tokenize(input, &tc);
if (!tokens || tc == 0) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "Empty command.");
return cmd;
}
/* The leading "qi" is mandatory: the command list mirrors a real qi
* invocation, so the first token must name the program. */
if (strcmp(tokens[0], "qi") != 0 && strcmp(tokens[0], "query-index") != 0) {
SET_CMD_ERROR(&cmd, "Commands must start with 'query-index', or 'qi'. Example: qi malloc -f foo.c");
goto done;
}
int i = 1;
while (i < tc) {
const char *t = tokens[i];
if (!is_flag(t)) {
/* Split grep-style alternation 'A|B' (or 'A\|B') into separate OR'd terms. */
char *segs[MAX_PATTERNS];
int nseg = split_alternation_web(&cmd, t, segs, MAX_PATTERNS);
if (nseg > 1) capture_alt_warning_web(&cmd, t, segs, nseg);
for (int s = 0; s < nseg; s++) {
if (cmd.pattern_count >= MAX_PATTERNS) {
for (int r = s; r < nseg; r++) free(segs[r]);
cmd.error = 1;
SET_CMD_ERROR(&cmd, "Too many patterns.");
goto done;
}
cmd.patterns[cmd.pattern_count++] = segs[s];
}
i++;
continue;
}
if (strcmp(t, "--def") == 0) {
cmd.definition = 1;
cmd.cf.definition.show = 1;
i++;
continue;
}
if (strcmp(t, "--usage") == 0) {
cmd.definition = 0;
cmd.cf.definition.show = 1;
i++;
continue;
}
if (strcmp(t, "-v") == 0 || strcmp(t, "--verbose") == 0) {
cmd.verbose = 1;
i++;
continue;
}
if (strcmp(t, "--compact") == 0) {
cmd.compact = 1;
i++;
continue;
}
if (strcmp(t, "--full") == 0) {
/* --full turns off compact mode: full column headers (SYMBOL,
* CONTEXT) and full context names (FUNCTION). Mirrors native
* query-index.c, which sets compact=0 on --full. */
cmd.compact = 0;
i++;
continue;
}
if (strcmp(t, "--debug") == 0) {
cmd.debug = 1;
i++;
continue;
}
if (strcmp(t, "--toc") == 0) {
cmd.toc_mode = 1;
i++;
continue;
}
if (strcmp(t, "--files") == 0) {
cmd.files_mode = 1;
i++;
continue;
}
if (strcmp(t, "--and") == 0) {
if (cmd.pattern_count < 2) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--and requires at least 2 search patterns. Example: qi malloc free --and 10");
goto done;
}
if (i + 1 < tc && !is_flag(tokens[i + 1])) {
/* Validate the range argument is numeric */
const char *arg = tokens[i + 1];
int valid = 1;
for (int ci = 0; arg[ci]; ci++) {
if (!isdigit((unsigned char)arg[ci])) { valid = 0; break; }
}
if (!valid) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--and range must be a positive integer.");
goto done;
}
cmd.line_range = atoi(arg);
if (cmd.line_range < 0) cmd.line_range = 0;
i += 2;
} else {
cmd.line_range = 0;
i++;
}
continue;
}
if (strcmp(t, "-w") == 0 || strcmp(t, "--within") == 0) {
i++;
while (i < tc && !is_flag(tokens[i])) {
if (cmd.within_count < MAX_PATTERNS) {
cmd.within_symbols[cmd.within_count++] = cmd_strdup(&cmd, tokens[i]);
}
i++;
}
continue;
}
if (strcmp(t, "--columns") == 0) {
i++;
while (i < tc && !is_flag(tokens[i])) {
if (cmd.column_count < MAX_CONTEXT_TYPES) {
cmd.column_names[cmd.column_count++] = cmd_strdup(&cmd, tokens[i]);
}
i++;
}
continue;
}
if (strcmp(t, "--limit") == 0 || strcmp(t, "-l") == 0) {
if (i + 1 >= tc) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--limit requires a number.");
goto done;
}
{
const char *arg = tokens[i + 1];
int valid = 1;
for (int ci = 0; arg[ci]; ci++) {
if (!isdigit((unsigned char)arg[ci])) { valid = 0; break; }
}
if (!valid) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--limit must be a positive integer.");
goto done;
}
cmd.limit = atoi(arg);
}
/* limit 0 = unlimited, matching the native CLI (which accepts
* `--limit 0` and rejects only negatives). Negatives are already
* rejected above by the digit-only check, so cmd.limit >= 0 here. */
i += 2;
continue;
}
if (strcmp(t, "--limit-per-file") == 0 || strcmp(t, "-lpf") == 0) {
if (i + 1 >= tc) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--limit-per-file requires a number.");
goto done;
}
{
const char *arg = tokens[i + 1];
int valid = 1;
for (int ci = 0; arg[ci]; ci++) {
if (!isdigit((unsigned char)arg[ci])) { valid = 0; break; }
}
if (!valid || atoi(arg) <= 0) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "--limit-per-file must be a positive integer.");
goto done;
}
cmd.limit_per_file = atoi(arg);
}
i += 2;
continue;
}
if (strcmp(t, "-i") == 0 || strcmp(t, "--include-context") == 0 ||
strcmp(t, "-x") == 0 || strcmp(t, "--exclude-context") == 0 ||
strcmp(t, "-f") == 0 || strcmp(t, "--file") == 0) {
int is_include = (strcmp(t, "-i") == 0 || strcmp(t, "--include-context") == 0);
int is_exclude = (strcmp(t, "-x") == 0 || strcmp(t, "--exclude-context") == 0);
i++;
while (i < tc && !is_flag(tokens[i])) {
const char *val = tokens[i];
if (is_include || is_exclude) {
if (strcasecmp(val, "noise") == 0) {
if (is_include) {
if (cmd.include_count + 2 <= MAX_CONTEXT_TYPES) {
cmd.includes[cmd.include_count++] = cmd_strdup(&cmd, "COM");
cmd.includes[cmd.include_count++] = cmd_strdup(&cmd, "STR");
}
} else {
if (cmd.exclude_count + 2 <= MAX_CONTEXT_TYPES) {
cmd.excludes[cmd.exclude_count++] = cmd_strdup(&cmd, "COM");
cmd.excludes[cmd.exclude_count++] = cmd_strdup(&cmd, "STR");
}
}
} else {
const char *mapped = map_context_web(val);
if (!mapped) {
/* Mirrors report_invalid_context() in query-index.c;
* the pipeline prefixes "Error: " to this message. */
char errbuf[320];
snprintf(errbuf, sizeof(errbuf),
"unrecognized context type '%s' for %s.\n"
"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"
"Note: Go structs index as 'class', interfaces as 'iface'.",
val, is_include ? "-i" : "-x");
SET_CMD_ERROR(&cmd, errbuf);
goto done;
}
if (is_include) {
if (cmd.include_count < MAX_CONTEXT_TYPES)
cmd.includes[cmd.include_count++] = cmd_strdup(&cmd, mapped);
} else {
if (cmd.exclude_count < MAX_CONTEXT_TYPES)
cmd.excludes[cmd.exclude_count++] = cmd_strdup(&cmd, mapped);
}
}
} else {
if (cmd.file_count < MAX_CONTEXT_TYPES)
cmd.files[cmd.file_count++] = cmd_strdup(&cmd, val);
}
i++;
}
continue;
}
/* Column filter flags: -p/--parent, -s/--scope, -ns/--namespace,
* -m/--modifier, -c/--clue, -t/--type, -d/--definition,
* --parent-type (virtual) */
if (strcmp(t, "-p") == 0 || strcmp(t, "--parent") == 0) {
parse_col_flag_values(&cmd.cf.parent, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-s") == 0 || strcmp(t, "--scope") == 0) {
parse_col_flag_values(&cmd.cf.scope, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-ns") == 0 || strcmp(t, "--namespace") == 0) {
parse_col_flag_values(&cmd.cf.ns, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-m") == 0 || strcmp(t, "--modifier") == 0) {
parse_col_flag_values(&cmd.cf.modifier, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-c") == 0 || strcmp(t, "--clue") == 0) {
parse_col_flag_values(&cmd.cf.clue, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-t") == 0 || strcmp(t, "--type") == 0) {
parse_col_flag_values(&cmd.cf.type, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "-d") == 0 || strcmp(t, "--definition") == 0) {
parse_col_flag_values(&cmd.cf.definition, tokens, tc, &i, &cmd);
i++; continue;
}
if (strcmp(t, "--parent-type") == 0) {
parse_col_flag_values(&cmd.cf.parent_type, tokens, tc, &i, &cmd);
/* No parent_type column exists; surface the parent column
* instead, mirroring native's show_columns.parent_symbol = 1 */
cmd.cf.parent.show = 1;
i++; continue;
}
/* Source-backed flags (-e/-C/-A/-B) and --raw */
if (strcmp(t, "-e") == 0 || strcmp(t, "--expand") == 0) {
cmd.expand = 1;
i++; continue;
}
if (strcmp(t, "--raw") == 0) {
cmd.raw = 1;
i++; continue;
}
if (strcmp(t, "-q") == 0 || strcmp(t, "--quiet") == 0) {
cmd.quiet = 1;
i++; continue;
}
if (strcmp(t, "-A") == 0 || strcmp(t, "--after-context") == 0) {
int v = parse_context_value(tokens, tc, &i, &cmd);
if (cmd.error) goto done;
cmd.context_after = v;
i++; continue;
}
if (strcmp(t, "-B") == 0 || strcmp(t, "--before-context") == 0) {
int v = parse_context_value(tokens, tc, &i, &cmd);
if (cmd.error) goto done;
cmd.context_before = v;
i++; continue;
}
if (strcmp(t, "-C") == 0 || strcmp(t, "--context") == 0) {
int v = parse_context_value(tokens, tc, &i, &cmd);
if (cmd.error) goto done;
cmd.context_before = cmd.context_after = v;
i++; continue;
}
if (strcmp(t, "--help") == 0 || strcmp(t, "-h") == 0) {
cmd.help = 1;
goto done;
}
if (strcmp(t, "--list-types") == 0) {
cmd.list_types = 1;
goto done;
}
if (strcmp(t, "--version") == 0) {
cmd.version = 1;
goto done;
}
/* Unknown flag — report error instead of silently ignoring */
{
char errbuf[256];
snprintf(errbuf, sizeof(errbuf), "Unknown flag: %s", t);
errbuf[sizeof(errbuf) - 1] = '\0';
cmd.error = 1;
cmd.error_msg = strdup(errbuf);
cmd.error_msg_malloced = 1;
if (!cmd.error_msg) {
cmd.error_msg = strdup("Unknown flag.");
cmd.error_msg_malloced = 1;
}
goto done;
}
}
done:
free_tokens(tokens, tc);
if (cmd.oom) {
cmd.error = 1;
/* Literal string — not strdup'd, must not be freed */
cmd.error_msg = "out of memory";
cmd.error_msg_malloced = 0;
}
if (!cmd.error && cmd.pattern_count == 0) {
cmd.error = 1;
SET_CMD_ERROR(&cmd, "At least one search pattern is required.");
}
return cmd;
}
/* Emit the post-"Searching for:" filter header as pre-rendered "HDR|<text>"
* lines, mirroring the native CLI's header block (query-index.c main()): the
* include/exclude context types and the extensible column filters. Composed
* here (not in the format function) because this is where the parsed structures
* live; qi_web_format just echoes the HDR lines via print_hdr_lines().
*
* The "Filtering by file:" line needs a distinct-file count the JS worker owns,
* so it is emitted as a one-byte sentinel (HDR|\x01) at the right position
* (after exclude, before column filters -- matching native order); print_hdr_lines
* expands it using FILE_FILTER_COUNT from build_info.
*
* The "Within symbol(s): ... (N instances)" line is likewise a sentinel
* (HDR|\x02), emitted last (matching native order); print_hdr_lines expands it
* using WITHIN_SYMBOLS + WITHIN_COUNT from build_info. */
static void emit_header_lines(WebOutput *wo, const ContextTypeList *include,
const ContextTypeList *exclude,
const QueryFilters *filters, int definition,
int compact, int has_file_filter, int has_within) {
if (include->count > 0) {
wo_printf(wo, "\nHDR|Including context types:");
for (int j = 0; j < include->count; j++)
wo_printf(wo, " %s", context_to_string(include->types[j], compact));
}
if (exclude->count > 0) {
wo_printf(wo, "\nHDR|Excluding context types:");
for (int j = 0; j < exclude->count; j++)
wo_printf(wo, " %s", context_to_string(exclude->types[j], compact));
}
/* File-filter sentinel: print_hdr_lines replaces HDR|\x01 with the
* "Filtering by file: N file(s) matched" line (+ suggestions when 0). */
if (has_file_filter)
wo_printf(wo, "\nHDR|\x01");
/* Extensible column filters, in column_schema.def order -- same X-macro the
* native CLI uses, so the field name and ordering match exactly. */
#define COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, ...) \
if (filters->name.count > 0) { \
wo_printf(wo, "\nHDR|Filtering by " #name ":"); \
for (int j = 0; j < filters->name.count; j++) \
wo_printf(wo, " %s", filters->name.values[j]); \
}
#define INT_COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, ...) \
if (filters->name.count > 0) { \
wo_printf(wo, "\nHDR|Filtering by " #name ":"); \
for (int j = 0; j < filters->name.count; j++) \
wo_printf(wo, " %s", filters->name.values[j]); \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
/* Virtual --parent-type filter has no X-macro entry; emit its line
* explicitly, matching native's "Filtering by parent type:" wording. */
if (filters->parent_type.count > 0) {
wo_printf(wo, "\nHDR|Filtering by parent type:");
for (int j = 0; j < filters->parent_type.count; j++)
wo_printf(wo, " %s", filters->parent_type.values[j]);
}
/* --def/--usage set cmd.definition (and inject the SQL directly) rather than
* populating filters.is_definition, so emit its line explicitly when the
* X-macro above didn't already cover it. */
if (definition >= 0 && filters->is_definition.count == 0)
wo_printf(wo, "\nHDR|Filtering by is_definition: %d", definition);
/* Within sentinel: print_hdr_lines replaces HDR|\x02 with the
* "Within symbol(s): ... (N instance(s))" line, expanded from
* WITHIN_SYMBOLS + WITHIN_COUNT. Emitted last, matching native order. */
if (has_within)
wo_printf(wo, "\nHDR|\x02");
}
/* Emit FILE_FILTER_COUNT_SQL: counts distinct (directory, filename) pairs that
* match the file/context/column filters but NOT the symbol patterns -- mirroring
* native count_distinct_files (query-index.c). The "Filtering by file: N" header
* reports how many files the -f filter spans, independent of the search term. */
static void emit_file_filter_count_sql(WebOutput *wo, ContextTypeList *include,
ContextTypeList *exclude, QueryFilters *filters,
FileFilterList *file_filter, int debug) {
SqlQueryBuilder b;
if (init_sql_builder(&b) != 0) return;
if (sql_append(&b, "SELECT COUNT(*) FROM (SELECT DISTINCT directory, filename "
"FROM code_index WHERE 1=1") == 0 &&
build_common_filters_web(&b, include, exclude, filters, file_filter, NULL, debug, "") == 0 &&
sql_append(&b, ")") == 0) {
wo_printf(wo, "\nFILE_FILTER_COUNT_SQL|%s", b.sql);
}
free_sql_builder(&b);
}
/* Emit one filter-exclusion diagnostic count query (NRD_SQL_<flag_suffix>):
* the main query's match count with one filter cleared by the caller, so the
* no-results formatter can name the culprit flag (diagnose_filter_exclusion in
* query-index.c). `definition` re-applies the --def/--usage injection (-1 for
* none, or when the probe is clearing -d itself). */
static void emit_nrd_count_sql(WebOutput *wo, const char *flag_suffix,
PatternList *patterns,
ContextTypeList *include, ContextTypeList *exclude,
QueryFilters *filters, FileFilterList *file_filter,
int line_range, int definition, int debug) {
SqlQueryBuilder b;
if (init_sql_builder(&b) != 0) return;
if (sql_append(&b, "SELECT COUNT(*) FROM code_index WHERE (") == 0 &&
build_query_filters_web(&b, patterns, include, exclude, filters,
file_filter, NULL, line_range, debug) == 0 &&
(definition < 0 ||
sql_append(&b, " AND is_definition = %d", definition) == 0)) {
wo_printf(wo, "\nNRD_SQL_%s|%s", flag_suffix, b.sql);
}
free_sql_builder(&b);
}
/* Help text for the browser terminal -- mirrors native show_help_compact()
* (query-index.c) but uses wo_printf. Database flags (--db-file) and the
* config-file note are omitted; they are irrelevant in the WASM context. */
static void show_help_compact_web(WebOutput *wo) {
wo_printf(wo, "Usage: qi PATTERN [PATTERN...] [OPTIONS]\n");
wo_printf(wo, "Search indexed code symbols.\n");
wo_printf(wo, "Example: qi getUserById --def -e\n");
wo_printf(wo, "Note: qi searches identifiers and indexed symbol metadata, not arbitrary text.\n");
wo_printf(wo, "\n");
wo_printf(wo, "Quick Start:\n");
wo_printf(wo, " qi user find symbol (exact match)\n");
wo_printf(wo, " qi user%% -i func var only functions/variables (starts with user)\n");
wo_printf(wo, " qi '*user*' -x noise -C 3 skip comments/strings, show 3 lines of context (contains user)\n");
wo_printf(wo, " qi getUserById --def -e show full definition (LLMs: add --raw flag for Edit anchors)\n");
wo_printf(wo, " qi %% -f query-index.c --toc show file structure\n");
wo_printf(wo, "\n");
wo_printf(wo, "Match:\n");
wo_printf(wo, " -i, --include-context TYPE... only these contexts\n");
wo_printf(wo, " -x, --exclude-context TYPE... exclude these contexts\n");
wo_printf(wo, " -x noise exclude comments and strings\n");
wo_printf(wo, " --and [RANGE] require all patterns on same/nearby lines\n");
wo_printf(wo, "\n");
wo_printf(wo, "Filter:\n");
wo_printf(wo, " -f, --file PATTERN... filter files: database.c, .py, shared/, shared/*.c\n");
#define COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, max_len, help_desc, help_example) \
{ \
char flag_text[64]; \
snprintf(flag_text, sizeof(flag_text), "-%s, --%s PATTERN", #short_flag, #long_flag); \
wo_printf(wo, " %-30s %s\n", flag_text, help_desc); \
}
#define INT_COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, help_desc, help_example) \
{ \
char flag_text[64]; \
snprintf(flag_text, sizeof(flag_text), "-%s, --%s [0|1]", #short_flag, #long_flag); \
wo_printf(wo, " %-30s %s\n", flag_text, help_desc); \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
wo_printf(wo, " --parent-type PATTERN... filter by parent's declared type (resolves parent to its definition)\n");
wo_printf(wo, " --def definitions only\n");
wo_printf(wo, " --usage usages only\n");
wo_printf(wo, " --lines LINE|START-END filter line/range\n");
wo_printf(wo, " -w, --within SYMBOL... search inside definitions\n");
wo_printf(wo, " -l, --limit NUM limit matches\n");
wo_printf(wo, " -lpf, --limit-per-file NUM limit matches per file\n");
wo_printf(wo, "\n");
wo_printf(wo, "Display:\n");
wo_printf(wo, " -e, --expand show full definitions\n");
wo_printf(wo, " -C, --context NUM lines before and after\n");
wo_printf(wo, " -A, --after-context NUM lines after\n");
wo_printf(wo, " -B, --before-context NUM lines before\n");
wo_printf(wo, " --files list matching files only\n");
wo_printf(wo, " --toc file table of contents; use with -f\n");
wo_printf(wo, " --columns COL... choose columns (supports aliases): line sym ctx");
#define COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, ...) \
{ \
char lower[32]; \
to_lowercase_copy(#compact_name, lower, sizeof(lower)); \
wo_printf(wo, " %s", lower); \
}
#define INT_COLUMN(name, sql_type, c_type, width, full, compact_name, long_flag, short_flag, ...) \
{ \
char lower[32]; \
to_lowercase_copy(#compact_name, lower, sizeof(lower)); \
wo_printf(wo, " %s", lower); \
}
#include "shared/column_schema.def"
#undef COLUMN
#undef INT_COLUMN
wo_printf(wo, "\n");
wo_printf(wo, " -v, --verbose all columns\n");
wo_printf(wo, " --full full column names\n");
wo_printf(wo, " --raw source only; useful with -e/-A/-B\n");
wo_printf(wo, " -q, --quiet drop banner/footer/rule chrome; keep header + rows\n");
wo_printf(wo, "\n");
wo_printf(wo, " --debug show SQL\n");
wo_printf(wo, "\n");
wo_printf(wo, "Types: func call class var arg type prop com str; use --list-types for all.\n");
wo_printf(wo, "Patterns: case-insensitive, exact by default; wildcards: %% or * any chars, _ or . one char (* needs shell quoting).\n");
wo_printf(wo, "Filters: case-insensitive, fuzzy by default.\n");
wo_printf(wo, "\n");
wo_printf(wo, "Configuration:\n");
wo_printf(wo, " Config file: ./.smconfig or ~/.smconfig. CLI flags override config\n");
wo_printf(wo, " Format: [qi] section header, then one flag per line. Example: --db-file /dev/shm/index.db\n");
wo_printf(wo, "\n");
wo_printf(wo, "Please email bug reports to bugs@sourceminder.org.\n");
}
EMSCRIPTEN_KEEPALIVE
char *qi_web_help(void) {
WebOutput wo;
if (wo_init(&wo) != 0) return strdup("Error: out of memory.");
show_help_compact_web(&wo);
{ char *r = wo_steal(&wo); return r ? r : strdup("Error: out of memory."); }
}
/* Context-type table for --list-types -- verbatim twin of native
* print_context_types() (query-index.c). The native table is hardcoded (not
* generated from column_schema.def), so keep this in sync by hand if the CLI
* list changes. */
EMSCRIPTEN_KEEPALIVE
char *qi_web_list_types(void) {
WebOutput wo;
if (wo_init(&wo) != 0) return strdup("Error: out of memory.");
wo_printf(&wo, "Context Types (use full or abbreviated forms, case insensitive):\n");
wo_printf(&wo, " %-12s %-9s %s\n", "Full Name", "Short", "Description");
wo_printf(&wo, " %-12s %-9s %s\n", "------------", "-----", "-----------");
wo_printf(&wo, " %-12s %-9s %s\n", "argument", "arg", "Function parameters");
wo_printf(&wo, " %-12s %-9s %s\n", "call", "-", "Function/method calls");
wo_printf(&wo, " %-12s %-9s %s\n", "case", "-", "Enum values/cases");
wo_printf(&wo, " %-12s %-9s %s\n", "class", "-", "Class definitions");
wo_printf(&wo, " %-12s %-9s %s\n", "comment", "com", "Words from comments");
wo_printf(&wo, " %-12s %-9s %s\n", "enum", "-", "Enum type definitions");
wo_printf(&wo, " %-12s %-9s %s\n", "exception", "exc", "Exception classes");
wo_printf(&wo, " %-12s %-9s %s\n", "export", "exp", "Export statements");
wo_printf(&wo, " %-12s %-9s %s\n", "filename", "file", "Filename without extension");
wo_printf(&wo, " %-12s %-9s %s\n", "function", "func", "Function/method definitions");
wo_printf(&wo, " %-12s %-9s %s\n", "goto", "-", "Goto statements (C)");
wo_printf(&wo, " %-12s %-9s %s\n", "import", "imp", "Import/include statements");
wo_printf(&wo, " %-12s %-9s %s\n", "interface", "iface", "Interface definitions");
wo_printf(&wo, " %-12s %-9s %s\n", "label", "-", "Labels (for goto in C)");
wo_printf(&wo, " %-12s %-9s %s\n", "lambda", "lam", "Lambda/arrow functions");
wo_printf(&wo, " %-12s %-9s %s\n", "macro", "-", "Preprocessor macros");
wo_printf(&wo, " %-12s %-9s %s\n", "namespace", "ns", "Namespace/package declarations");
wo_printf(&wo, " %-12s %-9s %s\n", "property", "prop", "Class/struct fields");
wo_printf(&wo, " %-12s %-9s %s\n", "string", "str", "Words from string literals");
wo_printf(&wo, " %-12s %-9s %s\n", "trait", "-", "Trait definitions (PHP)");
wo_printf(&wo, " %-12s %-9s %s\n", "type", "-", "Type definitions (struct, enum, etc.)");
wo_printf(&wo, " %-12s %-9s %s\n", "variable", "var", "Variables and constants");
wo_printf(&wo, "\n");
wo_printf(&wo, " Examples: -i func, -i function, -i FUNC all work the same\n");
wo_printf(&wo, " Special: -x noise expands to -x comment string\n");
{ char *r = wo_steal(&wo); return r ? r : strdup("Error: out of memory."); }
}
/* Version info for --version. VERSION is the shared build version (constants.h);
* the "(WASM)" suffix marks this as the WebAssembly port. The SQLite version is
* appended by the JS pipeline from the live sqlite-wasm connection
* (SELECT sqlite_version()) since sqlite3 is not linked into this module. No
* tree-sitter line: the port queries pre-indexed DBs and never parses source. */
EMSCRIPTEN_KEEPALIVE
char *qi_web_version(void) {
WebOutput wo;
if (wo_init(&wo) != 0) return strdup("Error: out of memory.");
wo_printf(&wo, "%s (WASM)\n", VERSION);
{ char *r = wo_steal(&wo); return r ? r : strdup("Error: out of memory."); }
}
/* =================================================================
* Exported API 1: build SQL from command text
* Returns: "PATTERNS|p1 p2\nSQL|...\nLIMIT|20\nERROR|OK"
* or: "ERROR|message"
* ================================================================= */
EMSCRIPTEN_KEEPALIVE
char *qi_web_build(const char *command) {
WebOutput wo;
if (wo_init(&wo) != 0) return strdup("ERROR|out of memory");
if (!command || !command[0]) {
wo_free(&wo);
return strdup("ERROR|Empty command.");
}
WebCommand cmd = parse_command(command);
/* In TOC mode patterns are optional symbol filters -- override the
* "no patterns" error from parse_command. */
if (cmd.toc_mode && cmd.error && cmd.error_msg &&
strcmp(cmd.error_msg, "At least one search pattern is required.") == 0) {
if (cmd.error_msg_malloced) { free(cmd.error_msg); cmd.error_msg_malloced = 0; }
cmd.error_msg = NULL;
cmd.error = 0;
}
/* Help mode needs no patterns -- override the same error. */
if (cmd.help && cmd.error && cmd.error_msg &&
strcmp(cmd.error_msg, "At least one search pattern is required.") == 0) {
if (cmd.error_msg_malloced) { free(cmd.error_msg); cmd.error_msg_malloced = 0; }
cmd.error_msg = NULL;
cmd.error = 0;
}
/* --list-types needs no patterns -- override the same error. */
if (cmd.list_types && cmd.error && cmd.error_msg &&
strcmp(cmd.error_msg, "At least one search pattern is required.") == 0) {
if (cmd.error_msg_malloced) { free(cmd.error_msg); cmd.error_msg_malloced = 0; }
cmd.error_msg = NULL;
cmd.error = 0;
}
/* --version needs no patterns -- override the same error. */
if (cmd.version && cmd.error && cmd.error_msg &&
strcmp(cmd.error_msg, "At least one search pattern is required.") == 0) {
if (cmd.error_msg_malloced) { free(cmd.error_msg); cmd.error_msg_malloced = 0; }
cmd.error_msg = NULL;
cmd.error = 0;
}
if (cmd.error) {
wo_printf(&wo, "ERROR|%s", cmd.error_msg);
free_command(&cmd);
{ char *r = wo_steal(&wo); return r ? r : strdup("ERROR|out of memory"); }
}
/* Cross-mode metadata, emitted first so every mode's build_info carries it