-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrackets-code.c
More file actions
3452 lines (3204 loc) · 158 KB
/
Copy pathbrackets-code.c
File metadata and controls
3452 lines (3204 loc) · 158 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
/*
* This file brackets-code.c is part of L1vm.
*
* (c) Copyright Stefan Pietzonke (info@midnight-coding.de), 2026
*
* L1vm 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.
*
* L1vm 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 L1vm. If not, see <http://www.gnu.org/licenses/>.
*/
// brackets-code.c
// Brackets Code Generator - CLI tool for generating Brackets (L1VM) code
// Generated with opencode: Big Pickle
//
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <math.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include "brackets-code.h"
#include "dsl.h"
#ifdef HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
int validate_flag = 0;
int retry_seed = 0;
int verbose_flag = 0;
int dry_run_flag = 0;
int use_color = 1;
char out_dir[512] = "";
char l1vm_root[512] = "";
#define MAX_ARGS 1024
#define MAX_LINE_LEN 4096
#define MAX_VARS_CAP 64
#define INIT_VARS_CAP 8
#define INIT_BODY_CAP 4096
#define INIT_FUNCS_CAP 4
#define INIT_INCLUDES_CAP 4
#define MAX_LEARNED 4096
#define MAX_PROMPT 8192
#define MAX_CODE 65536
#define MAX_OUTPUT 4096
#define PATH_BUF_SIZE 512
#define WORD_BUF_SIZE 256
#define FULLPATH_BUF_SIZE 1024
#define ANSI_RESET "\033[0m"
#define ANSI_RED "\033[31m"
#define ANSI_GREEN "\033[32m"
#define ANSI_YELLOW "\033[33m"
#define ANSI_CYAN "\033[36m"
#define ANSI_BOLD "\033[1m"
#define MAX_EXAMPLES 512
#define TEMPERATURE 0.8
#define MAX_STEPS 32
#define NUM_EMITTERS 166
#define EMBED_DIM 32
#define VOCAB_SIZE 72
#define MAX_LEARNED 4096
#define LEARNED_DIR ".brackets-code/learned"
#define MAX_NUMS 8
#define INIT_VARS_CAP 8
#define INIT_BODY_CAP 4096
#define INIT_FUNCS_CAP 4
#define INIT_INCLUDES_CAP 4
#define MAX_EXAMPLES 512
#define MAX_TOP_K 10
#define EXAMPLE_DIR "l1vm-example-code"
#define EXAMPLE_SUBDIRS 3
#define EXAMPLE_EXTS 3
#define MAX_NUMS 8
#define MAX_ARGS 1024
#define MAX_LINE_LEN 4096
#define MAX_VARS_CAP 64
#define INIT_VARS_CAP 8
#define INIT_BODY_CAP 4096
#define INIT_FUNCS_CAP 4
#define INIT_INCLUDES_CAP 4
#define MAX_LEARNED 4096
#define MAX_PROMPT 8192
#define MAX_CODE 65536
#define MAX_OUTPUT 4096
#define PATH_BUF_SIZE 512
#define WORD_BUF_SIZE 256
#define FULLPATH_BUF_SIZE 1024
LearnedPattern learned_patterns[MAX_LEARNED];
int num_learned = 0;
int learned_loaded = 0;
static int resize_vars(L1vmFunctionf, int new_cap) {
Variable *p = realloc(f->vars, (size_t)new_cap * sizeof(Variable));
if (!p) return 0;
f->vars = p;
if (new_cap > f->vars_cap)
memset(&f->vars[f->vars_cap], 0, (size_t)(new_cap - f->vars_cap) * sizeof(Variable));
f->vars_cap = new_cap;
return 1;
}
int ensure_vars_cap(L1vmFunctionf, int needed) {
if (needed <= f->vars_cap) return 1;
if (f->vars_cap > INT_MAX / 2) return 0;
int new_cap = f->vars_cap ? f->vars_cap * 2 : INIT_VARS_CAP;
while (new_cap < needed) {
if (new_cap > INT_MAX / 2) return 0;
new_cap *= 2;
}
return resize_vars(f, new_cap);
}
static int resize_body(L1vmFunctionf, int new_cap) {
char *p = realloc(f->body, (size_t)new_cap);
if (!p) return 0;
f->body = p;
if (new_cap > f->body_cap)
memset(&f->body[f->body_cap], 0, (size_t)(new_cap - f->body_cap));
f->body_cap = new_cap;
return 1;
}
int ensure_body_cap(L1vmFunctionf, int needed) {
if (needed <= f->body_cap) return 1;
if (f->body_cap > INT_MAX / 2) return 0;
int new_cap = f->body_cap ? f->body_cap * 2 : INIT_BODY_CAP;
while (new_cap < needed) {
if (new_cap > INT_MAX / 2) return 0;
new_cap *= 2;
}
return resize_body(f, new_cap);
}
int init_function(L1vmFunctionf) {
memset(f, 0, sizeof(L1vmFunction));
f->vars = NULL; f->vars_cap = 0;
f->body = NULL; f->body_cap = 0;
if (!resize_vars(f, INIT_VARS_CAP)) return 0;
if (!resize_body(f, INIT_BODY_CAP)) {
free(f->vars); f->vars = NULL; f->vars_cap = 0;
return 0;
}
f->body[0] = '\0';
return 1;
}
void free_function(L1vmFunctionf) {
free(f->vars); f->vars = NULL; f->vars_cap = 0;
free(f->body); f->body = NULL; f->body_cap = 0;
f->num_vars = 0;
}
static int resize_funcs_array(L1vmFunction **pfuncs, int *cap, int new_cap) {
L1vmFunction *p = realloc(*pfuncs, (size_t)new_cap * sizeof(L1vmFunction));
if (!p) return 0;
*pfuncs = p;
if (new_cap > *cap) {
for (int i = *cap; i < new_cap; i++) {
if (!init_function(&(*pfuncs)[i])) {
for (int j = *cap; j < i; j++) free_function(&(*pfuncs)[j]);
return 0;
}
}
}
*cap = new_cap;
return 1;
}
int ensure_funcs_cap(L1vmFunction **pfuncs, int *cap, int needed) {
if (needed <= *cap) return 1;
if (*cap > INT_MAX / 2) return 0;
int new_cap = *cap ? *cap * 2 : INIT_FUNCS_CAP;
while (new_cap < needed) {
if (new_cap > INT_MAX / 2) return 0;
new_cap *= 2;
}
return resize_funcs_array(pfuncs, cap, new_cap);
}
static int resize_includes_arr(char (**pinc)[256], int *cap, int new_cap) {
char (*p)[256] = realloc(*pinc, (size_t)new_cap * sizeof(char[256]));
if (!p) return 0;
*pinc = p;
if (new_cap > *cap)
memset(&(*pinc)[*cap], 0, (size_t)(new_cap - *cap) * sizeof(char[256]));
*cap = new_cap;
return 1;
}
int ensure_includes_cap(char (**pinc)[256], int *cap, int needed) {
if (needed <= *cap) return 1;
if (*cap > INT_MAX / 2) return 0;
int new_cap = *cap ? *cap * 2 : INIT_INCLUDES_CAP;
while (new_cap < needed) {
if (new_cap > INT_MAX / 2) return 0;
new_cap *= 2;
}
return resize_includes_arr(pinc, cap, new_cap);
}
int init_program(Program *prog) {
memset(prog, 0, sizeof(Program));
if (!resize_funcs_array(&prog->funcs, &prog->funcs_cap, INIT_FUNCS_CAP)) return 0;
if (!resize_includes_arr(&prog->includes, &prog->includes_cap, INIT_INCLUDES_CAP)) {
for (int i = 0; i < prog->funcs_cap; i++) free_function(&prog->funcs[i]);
free(prog->funcs); prog->funcs = NULL; prog->funcs_cap = 0;
return 0;
}
if (!resize_includes_arr(&prog->includes_post, &prog->includes_post_cap, INIT_INCLUDES_CAP)) {
for (int i = 0; i < prog->funcs_cap; i++) free_function(&prog->funcs[i]);
free(prog->funcs); prog->funcs = NULL; prog->funcs_cap = 0;
free(prog->includes); prog->includes = NULL; prog->includes_cap = 0;
return 0;
}
return 1;
}
void free_program(Program *prog) {
for (int i = 0; i < prog->funcs_cap; i++)
free_function(&prog->funcs[i]);
free(prog->funcs); prog->funcs = NULL; prog->funcs_cap = 0;
free(prog->includes); prog->includes = NULL; prog->includes_cap = 0;
free(prog->includes_post); prog->includes_post = NULL; prog->includes_post_cap = 0;
}
int init_learned_pattern(LearnedPattern *lp) {
memset(lp, 0, sizeof(LearnedPattern));
if (!resize_includes_arr(&lp->includes, &lp->includes_cap, INIT_INCLUDES_CAP)) return 0;
if (!resize_funcs_array(&lp->funcs, &lp->funcs_cap, INIT_FUNCS_CAP)) {
free(lp->includes); lp->includes = NULL; lp->includes_cap = 0;
return 0;
}
return 1;
}
void free_learned_pattern(LearnedPattern *lp) {
for (int i = 0; i < lp->funcs_cap; i++)
free_function(&lp->funcs[i]);
free(lp->funcs); lp->funcs = NULL; lp->funcs_cap = 0;
free(lp->includes); lp->includes = NULL; lp->includes_cap = 0;
}
void trim(char *s) {
char *p = s;
int l = strlen(p);
if (l == 0) return;
while (isspace((unsigned char)p[l-1])) p[--l] = 0;
while (*p && isspace((unsigned char)*p)) ++p;
memmove(s, p, l - (p - s) + 1);
}
int str_contains_word(const char *str, const char *word) {
char buf[MAX_LINE];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", str);
char *p = buf;
while (*p) {
while (*p && !isalpha((unsigned char)*p)) p++;
if (!*p) break;
char *start = p;
while (*p && isalpha((unsigned char)*p)) p++;
char saved = *p;
*p = '\0';
if (strcasecmp(start, word) == 0) { *p = saved; return 1; }
*p = saved;
}
return 0;
}
void to_lowercase(char *s) {
for (; *s; s++) *s = (char)tolower((unsigned char)*s);
}
void add_include(Program *prog, const char *inc) {
for (int i = 0; i < prog->num_includes; i++)
if (strcmp(prog->includes[i], inc) == 0) return;
if (!ensure_includes_cap(&prog->includes, &prog->includes_cap, prog->num_includes + 1)) return;
SNPRINTF_CHECK(prog->includes[prog->num_includes], sizeof(prog->includes[0]), "%s", inc);
prog->num_includes++;
}
void add_include_post(Program *prog, const char *inc) {
for (int i = 0; i < prog->num_includes_post; i++)
if (strcmp(prog->includes_post[i], inc) == 0) return;
if (!ensure_includes_cap(&prog->includes_post, &prog->includes_post_cap, prog->num_includes_post + 1)) return;
SNPRINTF_CHECK(prog->includes_post[prog->num_includes_post], sizeof(prog->includes_post[0]), "%s", inc);
prog->num_includes_post++;
}
void add_func(Program *prog, const char *name) {
for (int i = 0; i < prog->num_funcs; i++)
if (strcmp(prog->funcs[i].name, name) == 0) return;
if (!ensure_funcs_cap(&prog->funcs, &prog->funcs_cap, prog->num_funcs + 1)) return;
L1vmFunctionf = &prog->funcs[prog->num_funcs];
init_function(f);
SNPRINTF_CHECK(f->name, sizeof(f->name), "%s", name);
f->is_local = 0;
f->has_vars = 0;
f->has_vardef = 0;
f->num_vars = 0;
f->body[0] = '\0';
prog->num_funcs++;
}
void add_var_to_func(L1vmFunctionf, const char *type, const char *name, int count, const char **values, int num_values) {
// Skip if variable with same name already exists (prevents duplicate declarations)
for (int i = 0; i < f->num_vars; i++)
if (strcmp(f->vars[i].name, name) == 0) return;
if (!ensure_vars_cap(f, f->num_vars + 1)) return;
Variable *v = &f->vars[f->num_vars++];
SNPRINTF_CHECK(v->name, sizeof(v->name), "%s", name);
SNPRINTF_CHECK(v->type, sizeof(v->type), "%s", type);
v->count = count;
v->num_values = num_values;
for (int i = 0; i < num_values && i < MAX_VALUES; i++)
SNPRINTF_CHECK(v->values[i], sizeof(v->values[i]), "%s", values[i]);
}
void func_append(L1vmFunctionf, const char *line) {
size_t needed = strlen(f->body) + strlen(line) + 2;
if (!ensure_body_cap(f, (int)needed + 1)) return;
strncat(f->body, line, (size_t)f->body_cap - strlen(f->body) - 1);
strncat(f->body, "\n", (size_t)f->body_cap - strlen(f->body) - 1);
}
void func_vardef(L1vmFunctionf, const char *scope) {
if (f->has_vardef) return;
f->has_vardef = 1;
f->is_local = 1;
SNPRINTF_CHECK(f->vardef_name, sizeof(f->vardef_name), "%s", scope);
}
int prompt_to_filename(const char *prompt, char *out, int max) {
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", prompt);
to_lowercase(buf);
for (int i = 0; buf[i]; i++)
if (!isalnum(buf[i])) buf[i] = '_';
while (buf[0] == '_') memmove(buf, buf+1, strlen(buf));
char *p = buf + strlen(buf) - 1;
while (p > buf && *p == '_') *p-- = '\0';
SNPRINTF_CHECK(out, max, "%s.l1com", buf);
return 1;
}
int is_question(const char *prompt) {
const char *qwords[] = {"was", "wie", "wer", "wo", "warum", "wann", "welche", "what", "how", "why", "where", "when", "can", "does", "is", "are", NULL};
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", prompt);
to_lowercase(buf);
if (strchr(buf, '?')) return 1;
for (int i = 0; qwords[i]; i++) {
size_t len = strlen(qwords[i]);
if (strncmp(buf, qwords[i], len) == 0) {
char c = buf[len];
if (c == ' ' || c == '\0' || c == '?' || c == ',' || c == '.') return 1;
}
}
return 0;
}
void answer_question(const char *prompt) {
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", prompt);
to_lowercase(buf);
printf("\n");
if (strstr(buf, "pointer") || strstr(buf, "zeiger") || strstr(buf, "speicher") || strstr(buf, "adresse")) {
printf("Pointers in Brackets: Use the `pointer` keyword to get a variable's address.\n");
printf(" (x Px pointer) - get pointer to x -> Px\n");
printf(" (Px [ offset ] val =) - read value at pointer+offset into val\n");
printf(" (val Px [ offset ] =) - write val to pointer+offset\n");
} else if (strstr(buf, "for") || strstr(buf, "loop") || strstr(buf, "schleife")) {
printf("For-loop pattern in Brackets:\n");
printf(" (for-loop)\n");
printf(" (((i max <) f :=) f for)\n");
printf(" // loop body\n");
printf(" (i + one i :=)\n");
printf(" (next)\n");
} else if (strstr(buf, "if") || strstr(buf, "bedingung") || strstr(buf, "condition")) {
printf("If/else pattern in Brackets:\n");
printf(" (((x y <) f :=) f if) - if (x < y)\n");
printf(" // true branch\n");
printf(" (endif)\n");
printf(" Use (if+) and (else) for if-else chains.\n");
} else if (strstr(buf, "array") || strstr(buf, "feld") || strstr(buf, "liste")) {
printf("Array access in Brackets uses pointer arithmetic:\n");
printf(" (set int64 5 arr 10 20 30 40 50) - declare array\n");
printf(" (i * int64_size realind :=) - calculate offset\n");
printf(" (arr [ realind ] val =) - read element\n");
printf(" (val arr [ realind ] =) - write element\n");
} else if (strstr(buf, "function") || strstr(buf, "funktion") || strstr(buf, "sub") || strstr(buf, "unter")) {
printf(" L1vmFunction definition in Brackets:\n");
printf(" (myfunc func)\n");
printf(" #var ~ myfunc - local scope\n");
printf(" (set int64 1 x~ 0) - local variable\n");
printf(" (arg1~ stpop) - pop argument from stack\n");
printf(" ...\n");
printf(" (retval~ stpush) - push return value\n");
printf(" (return)\n");
printf(" (funcend)\n");
printf(" Call: (arg :myfunc !) (ret stpop)\n");
} else if (strstr(buf, "struct") || strstr(buf, "dotted") || strstr(buf, "punkt")) {
printf("Struct/dotted variables in Brackets:\n");
printf(" (set int64 1 person.age 0) - dotted name acts like struct field\n");
printf(" (person.age :print_i !)\n");
} else if (strstr(buf, "string") || strstr(buf, "zeichen") || strstr(buf, "text")) {
printf("String handling in Brackets:\n");
printf(" (set const-string s msg \"Hello\") - immutable string\n");
printf(" (set string 256 buf \"\") - mutable buffer\n");
printf(" (msg :print_s !) - print string\n");
printf(" (dest src :string_copy !) - copy string\n");
} else if (strstr(buf, "stack") || strstr(buf, "stapel") || strstr(buf, "push") || strstr(buf, "pop")) {
printf("Stack operations in Brackets:\n");
printf(" stpush - push variable to stack\n");
printf(" stpop - pop from stack into variable\n");
printf(" (val :func !) - call function, args pushed before call\n");
printf(" (ret stpop) - get return value after call\n");
} else if (strstr(buf, "exit") || strstr(buf, "beenden")) {
printf("To exit a Brackets program:\n");
printf(" (zero :exit !) - exit with status code in variable\n");
printf(" zero should be (set const-int64 1 zero 0)\n");
} else if (strstr(buf, "brackets") || strstr(buf, "l1vm") || strstr(buf, "l1com") || strstr(buf, "was ist")) {
printf("Brackets %s (L1VM) is a stack-based virtual machine and assembly language.\n", VERSION_TXT);
printf("Code is written in .l1com files using S-expressions (parentheses).\n");
printf("Key concepts: (func), (set), (if), (for-loop), pointer access, local scoping via #var ~\n");
} else {
printf("I'm a Brackets %s (L1VM) code generator. Ask me about:\n", VERSION_TXT);
printf("- How to write loops, if/else, functions\n");
printf("- Pointers, arrays, structs, strings\n");
printf("- Stack operations, math, exit\n");
printf("Or give me a code request like \"Create code that adds two numbers\".\n");
}
printf("\n");
}
typedef struct {
const char *op;
const char *rpn_op;
} OpMap;
static const OpMap ops[] = {
{"+", "add"},
{"plus", "add"},
{"add", "add"},
{"addiere", "add"},
{"sum", "add"},
{"-", "sub"},
{"minus", "sub"},
{"subtract", "sub"},
{"subtrahiere", "sub"},
{"zieh", "sub"},
{"differenz", "sub"},
{"*", "mul"},
{"mal", "mul"},
{"multiply", "mul"},
{"multipliziere", "mul"},
{"product", "mul"},
{"/", "div"},
{"geteilt", "div"},
{"divide", "div"},
{"dividiere", "div"},
{"quotient", "div"},
{"%", "mod"},
{"modulo", "mod"},
{"mod", "mod"},
{"rest", "mod"},
};
static const char* find_operation(const char *buf) {
const char *best = NULL;
int best_len = 0;
for (int i = 0; i < (int)(sizeof(ops)/sizeof(ops[0])); i++) {
const char *hit = strstr(buf, ops[i].op);
if (hit) {
int oplen = (int)strlen(ops[i].op);
if (oplen > best_len) {
best_len = oplen;
best = ops[i].rpn_op;
}
}
}
return best;
}
// ==================== FUZZY SYNONYM MATCHING ====================
#define SYNONYM_FILE "synonyms.txt"
#define SYNONYM_DIR ".config/brackets-code"
#define MAX_DYN_SYNONYMS 1024
static Synonym dyn_synonyms[MAX_DYN_SYNONYMS];
static int num_dyn_synonyms = 0;
static int synonyms_loaded = 0;
static FILE *open_synonym_file(void) {
FILE *f = fopen(SYNONYM_FILE, "r");
if (f) return f;
const char *home = getenv("HOME");
if (home) {
char path[FULLPATH_BUF_SIZE];
SNPRINTF_CHECK(path, sizeof(path), "%s/%s/%s", home, SYNONYM_DIR, SYNONYM_FILE);
f = fopen(path, "r");
if (f) return f;
}
// Try next to the executable
char self_path[FULLPATH_BUF_SIZE];
ssize_t len = readlink("/proc/self/exe", self_path, sizeof(self_path) - 1);
if (len > 0) {
self_path[len] = '\0';
char *slash = strrchr(self_path, '/');
if (slash) {
SNPRINTF_CHECK(slash + 1, sizeof(self_path) - (size_t)(slash - self_path + 1), "%s", SYNONYM_FILE);
f = fopen(self_path, "r");
if (f) return f;
}
}
return NULL;
}
void load_synonyms(void) {
if (synonyms_loaded) return;
synonyms_loaded = 1;
FILE *f = open_synonym_file();
if (!f) return;
char line[WORD_BUF_SIZE];
while (fgets(line, sizeof(line), f) && num_dyn_synonyms < MAX_DYN_SYNONYMS) {
trim(line);
if (line[0] == '#' || line[0] == '\0') continue;
char *colon = strchr(line, ':');
if (!colon) continue;
*colon = '\0';
char *word = line;
char *canonical = colon + 1;
trim(word);
trim(canonical);
if (strlen(word) > 0 && strlen(canonical) > 0) {
SNPRINTF_CHECK(dyn_synonyms[num_dyn_synonyms].word, sizeof(dyn_synonyms[0].word), "%s", word);
SNPRINTF_CHECK(dyn_synonyms[num_dyn_synonyms].canonical, sizeof(dyn_synonyms[0].canonical), "%s", canonical);
num_dyn_synonyms++;
}
}
fclose(f);
}
typedef struct { char word[40]; char canonical[40]; } SynonymEntry;
static const SynonymEntry SYNONYM_TABLE[] = {
{"accumulate", "sum"}, {"addiere", "add"}, {"addieren", "add"}, {"addition", "add"},
{"aggregate", "sum"}, {"arrange", "sort"}, {"aufaddieren", "sum"}, {"aufrechnen", "sum"},
{"aufsummieren", "sum"}, {"berechnen", "sum"}, {"berechne", "sum"}, {"bubble sort", "sort"},
{"bubblesort", "sort"}, {"calculate", "sum"}, {"calculation", "sum"}, {"classify", "sort"},
{"collect", "input"}, {"compute", "sum"}, {"count up", "sum"}, {"deduct", "sub"},
{"differenz", "sub"}, {"divide", "div"}, {"dividieren", "div"}, {"enumeration", "print"},
{"enumerate", "print"}, {"evaluate", "sum"}, {"figure out", "sum"}, {"gather", "input"},
{"group", "sort"}, {"herabsetzen", "sub"}, {"increment", "add"}, {"iteration", "loop"},
{"iterate", "loop"}, {"merge sort", "sort"}, {"minus", "sub"}, {"multipliziere", "mul"}, {"multiplizieren", "mul"},
{"order", "sort"}, {"ordnen", "sort"}, {"organize", "sort"}, {"plus", "add"},
{"produkt", "mul"}, {"product", "mul"}, {"quotient", "div"}, {"quick sort", "sort"},
{"rechnen", "sum"}, {"reduce", "sub"}, {"zieh", "sub"}, {"subtrahiere", "sub"}, {"remainder", "mod"}, {"reorder", "sort"},
{"repeat", "loop"}, {"rest", "mod"}, {"series", "loop"}, {"sortieren", "sort"},
{"sortiert", "sort"}, {"subtrahieren", "sub"}, {"subtraktion", "sub"}, {"tally", "sum"},
{"total", "sum"}, {"vermindern", "sub"}, {"zusammenzaehlen", "sum"}, {"zusammenzählen", "sum"},
{"auffangen", "input"}, {"capture", "input"}, {"eingabe", "input"},
{"einlesen", "read"}, {"erfassen", "input"}, {"erfasse", "input"}, {"erhalten", "input"},
{"fetch", "read"}, {"gib ein", "input"}, {"import", "read"},
{"importieren", "read"}, {"laden", "read"}, {"lade", "read"}, {"load", "read"},
{"obtain", "input"}, {"oeffnen", "read"}, {"öffnen", "read"}, {"prompt", "input"},
{"receive", "input"}, {"retrieve", "read"}, {"take", "input"}, {"uebernehmen", "input"},
{"übernehmen", "input"}, {"anzeigen", "print"}, {"auflisten", "print"}, {"ausgabe", "print"},
{"ausgeben", "print"}, {"ausspucken", "print"}, {"chart", "print"}, {"darstellen", "print"},
{"display", "print"}, {"drucke", "print"}, {"drucken", "print"}, {"export", "write"},
{"herausgeben", "print"}, {"indicate", "print"}, {"list", "print"}, {"output", "print"},
{"present", "print"}, {"produce", "print"}, {"publish", "print"}, {"report", "print"},
{"show", "print"}, {"speichern", "write"}, {"speicher", "write"}, {"save", "write"},
{"sichern", "write"}, {"store", "write"}, {"veroeffentlichen", "print"}, {"veröffentlichen", "print"},
{"visualize", "print"}, {"zeigen", "print"}, {"append", "assign"}, {"catalogue", "array"},
{"catalog", "array"}, {"data set", "array"}, {"dataset", "array"}, {"element", "array"},
{"feld", "array"}, {"index", "array"}, {"insert", "assign"}, {"liste", "array"},
{"list", "array"}, {"push", "assign"}, {"sequence", "array"}, {"tabulate", "array"},
{"table", "array"}, {"tabelle", "array"}, {"buchstabe", "string"}, {"buchstaben", "string"},
{"character", "string"}, {"combine", "concat"}, {"concatenate", "concat"}, {"join", "concat"},
{"merge", "concat"}, {"text", "string"}, {"verbinden", "concat"}, {"verbinde", "concat"},
{"verketten", "concat"}, {"verkette", "concat"}, {"wort", "string"}, {"wörter", "string"},
{"woerter", "string"}, {"zeichenkette", "string"}, {"dokument", "file"}, {"document", "file"},
{"datei", "file"}, {"auffinden", "find"}, {"bestimmen", "find"}, {"determine", "find"},
{"discover", "find"}, {"entdecken", "find"}, {"ermitteln", "find"}, {"extract", "find"},
{"herausfinden", "find"}, {"identify", "find"}, {"isolate", "find"}, {"locate", "find"},
{"lokalisieren", "find"}, {"pick", "find"}, {"search", "find"}, {"select", "find"},
{"suche", "find"}, {"suchen", "find"}, {"backwards", "reverse"}, {"flip", "reverse"},
{"invert", "reverse"}, {"mirror", "reverse"}, {"rueckwaerts", "reverse"}, {"rückwärts", "reverse"},
{"spiegeln", "reverse"}, {"umdrehen", "reverse"}, {"umkehren", "reverse"}, {"turn around", "reverse"},
{"biggest", "max"}, {"bottom", "min"}, {"choose", "max"}, {"greatest", "max"},
{"highest", "max"}, {"hoehe", "max"}, {"höhe", "max"}, {"kleinste", "min"},
{"largest", "max"}, {"least", "min"}, {"lowest", "min"}, {"maximal", "max"},
{"minimal", "min"}, {"niedrigste", "min"}, {"peak", "max"}, {"smallest", "min"},
{"top", "max"}, {"tiefste", "min"}, {"center", "median"}, {"central", "median"},
{"durchschnittlich", "average"}, {"middle", "median"}, {"midpoint", "median"}, {"mitte", "median"},
{"mittel", "median"}, {"mittelwert", "average"}, {"normal", "average"}, {"standard", "average"},
{"typical", "average"}, {"typisch", "average"}, {"zentral", "median"}, {"zentrum", "median"},
{"bedingung", "if"}, {"condition", "if"}, {"falls", "if"}, {"repeat", "loop"},
{"repetition", "for"}, {"schleife", "loop"}, {"wenn", "if"}, {"byte", "byte"},
{"count", "number"}, {"decimal", "double"}, {"floating point", "double"}, {"ganzzahl", "int64"},
{"integer", "int64"}, {"kommazahl", "double"}, {"natuerlich", "int64"}, {"natürlich", "int64"},
{"quantity", "number"}, {"real", "double"}, {"size", "number"}, {"zaehle", "number"},
{"zählen", "number"}, {"zähle", "number"}, {"aendern", "convert"}, {"ändern", "convert"},
{"cast", "convert"}, {"change", "convert"}, {"coerce", "convert"}, {"konvertieren", "convert"},
{"konvertiere", "convert"}, {"transforms", "convert"}, {"transform", "convert"},
{"translate", "convert"}, {"turn", "convert"}, {"umrechnen", "convert"}, {"umwandeln", "convert"},
{"wandle", "convert"}, {"wechseln", "convert"}, {"benchmark", "timer"}, {"chrono", "timer"},
{"dauer", "timer"}, {"delay", "timer"}, {"duration", "timer"}, {"elapsed", "timer"},
{"execution", "timer"}, {"how long", "timer"}, {"lauf", "timer"}, {"laufzeit", "timer"},
{"measure", "timer"}, {"messen", "timer"}, {"mess", "timer"}, {"performance", "timer"},
{"profile", "timer"}, {"speed", "timer"}, {"stopwatch", "timer"}, {"time", "timer"},
{"wait", "timer"}, {"argument", "shell"}, {"args", "shell"}, {"command line", "shell"},
{"commandline", "shell"}, {"cmd", "shell"}, {"kommando", "shell"}, {"kommandozeile", "shell"},
{"parameter", "shell"}, {"sys", "shell"}, {"system", "shell"}, {"bonjour", "hello"},
{"greet", "hello"}, {"greeting", "hello"}, {"grusse", "hello"}, {"grüße", "hello"},
{"grüss", "hello"}, {"grüß", "hello"}, {"hi", "hello"}, {"salut", "hello"},
{"salutation", "hello"}, {"willkommen", "hello"}, {"welcome", "hello"}, {"begruessen", "hello"},
{"begrüßen", "hello"}, {"allocate", "pointer"}, {"address", "pointer"}, {"adresse", "pointer"},
{"memory", "pointer"}, {"mem", "pointer"}, {"referenz", "pointer"}, {"reference", "pointer"},
{"zeiger", "pointer"}, {"dotted", "struct"}, {"object", "struct"}, {"punkt", "struct"},
{"record", "struct"}, {"struktur", "struct"}, {"structure", "struct"}, {"unterprogramm", "function"},
{"funktion", "function"}, {"func", "function"}, {"method", "function"}, {"prozedur", "function"},
{"procedure", "function"}, {"routine", "function"}, {"subroutine", "function"},
{"binaer", "binary"}, {"binär", "binary"}, {"hexadezimal", "hex"}, {"hexadecimal", "hex"},
{"oct", "hex"}, {"octal", "hex"}, {"fakultaet", "factorial"}, {"fakultät", "factorial"},
{"fib", "fib"}, {"fibonacci", "fib"}, {"prime number", "prime"}, {"primzahl", "prime"},
{"prime", "prime"}, {"erraten", "guess"}, {"guess", "guess"}, {"rate", "guess"},
{"raten", "guess"}, {"fizz", "fizzbuzz"},
{"fizz buzz", "fizzbuzz"}, {"fizzbuzz", "fizzbuzz"}, {"gerade", "even"}, {"odd", "odd"},
{"ungerade", "odd"}, {"einmaleins", "multiplication"}, {"multiplikation", "multiplication"},
{"multiplication", "multiplication"}, {"1x1", "multiplication"}, {"mal reihe", "multiplication"},
{"exponent", "power"}, {"hoch", "power"}, {"potenz", "power"}, {"power", "power"},
{"square", "power"}, {"squared", "power"}, {"quadrat", "power"}, {"quadrieren", "power"},
{"cubic", "power"}, {"cube", "power"}, {"gemeinsamer", "gcd"}, {"ggt", "gcd"},
{"greatest common", "gcd"}, {"gcm", "gcd"}, {"gcd", "gcd"}, {"countdown", "countdown"},
{"herunter", "countdown"}, {"herunterzaehlen", "countdown"}, {"herunterzählen", "countdown"},
{"runterzaehlen", "countdown"}, {"runterzählen", "countdown"}, {"runterz", "countdown"},
{"timer", "countdown"}, {"zuweisen", "assign"}, {"zuweisung", "assign"}, {"schreiben", "write"},
{"schreib", "write"},
{"primes", "prime"}, {"numbers", "num"}, {"values", "value"},
{"demo", "show"}, {"example", "show"},
{"benchmark", "timer"}, {"clock", "timer"}, {"performance", "timer"},
{"network", "data"}, {"crypto", "data"}, {"encrypt", "data"},
{"json", "data"}, {"config", "data"},
{"graphics", "show"}, {"render", "show"},
{"game", "guess"}, {"play", "guess"},
{"float", "num"}, {"bignum", "num"}, {"big", "num"},
{"include", "file"}, {"header", "file"},
{"vector", "array"}, {"collection", "array"},
{"lookup", "find"},
{"copy", "assign"}, {"duplicate", "assign"}, {"clone", "assign"},
{"delete", "remove"}, {"clear", "remove"}, {"erase", "remove"},
{"pop", "remove"}, {"extract", "remove"},
{"call", "run"}, {"invoke", "run"}, {"execute", "run"},
{"word", "string"},
{"fann", "fann"}, {"neural", "fann"}, {"netz", "fann"}, {"network", "data"},
{"neuronal", "fann"}, {"neuron", "fann"}, {"ki", "fann"}, {"ai", "fann"},
{"machine learning", "fann"}, {"deep", "fann"}, {"training", "train"},
{"trainieren", "train"}, {"trainiere", "train"}, {"lernen", "train"},
{"learn", "train"}, {"inferenz", "run"}, {"inference", "run"},
{"vorhersage", "run"}, {"predict", "run"}, {"prediction", "run"},
{"vorhersagen", "run"}, {"klassifikation", "run"}, {"classification", "run"},
};
static const int NUM_SYNONYMS = sizeof(SYNONYM_TABLE) / sizeof(SYNONYM_TABLE[0]);
const char* resolve_synonym(const char *word) {
for (int i = 0; i < num_dyn_synonyms; i++)
if (strcmp(word, dyn_synonyms[i].word) == 0)
return dyn_synonyms[i].canonical;
for (int i = 0; i < NUM_SYNONYMS; i++)
if (strcmp(word, SYNONYM_TABLE[i].word) == 0)
return SYNONYM_TABLE[i].canonical;
return NULL;
}
void expand_query(const char *query, char *expanded, int max_len) {
SNPRINTF_CHECK(expanded, max_len, "%s", query);
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", query);
to_lowercase(buf);
char *p = buf;
while (*p) {
while (*p && !isalpha((unsigned char)*p)) p++;
if (!*p) break;
char *start = p;
while (*p && isalpha((unsigned char)*p)) p++;
char saved = *p;
*p = '\0';
const char *canonical = resolve_synonym(start);
if (canonical && strcmp(start, canonical) != 0) {
strncat(expanded, " ", max_len - strlen(expanded) - 1);
strncat(expanded, canonical, max_len - strlen(expanded) - 1);
}
*p = saved;
}
}
static int _has_word_lowered(const char *lowered_text, const char *keyword);
int has_word_fuzzy(const char *text, const char *keyword) {
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", text);
to_lowercase(buf);
return _has_word_lowered(buf, keyword);
}
static int _has_word_lowered(const char *lowered_text, const char *keyword) {
int kwlen = strlen(keyword);
const char *p = lowered_text;
while ((p = strstr(p, keyword)) != NULL) {
int at_start = (p == lowered_text);
int at_end = (p[kwlen] == '\0');
int before_ok = at_start || !isalpha((unsigned char)*(p - 1));
int after_ok = at_end || !isalpha((unsigned char)p[kwlen]);
if (before_ok && after_ok) return 1;
p++;
}
p = lowered_text;
while (*p) {
while (*p && !isalpha((unsigned char)*p)) p++;
if (!*p) break;
const char *start = p;
while (*p && isalpha((unsigned char)*p)) p++;
int len = (int)(p - start);
if (len >= WORD_BUF_SIZE) len = WORD_BUF_SIZE - 1;
char word_buf[WORD_BUF_SIZE];
memcpy(word_buf, start, len);
word_buf[len] = '\0';
const char *canonical = resolve_synonym(word_buf);
if (canonical != NULL && strcmp(canonical, keyword) == 0) return 1;
}
return 0;
}
int has_word(const char *prompt, const char *word) {
return has_word_fuzzy(prompt, word);
}
static int _is_negated_lowered(const char *lowered_text, const char *keyword) {
int kwlen = strlen(keyword);
const char *p = lowered_text;
static const char *negations[] = {
"not", "don't", "dont", "doesn't", "doesnt", "isn't", "isnt",
"won't", "wont", "can't", "cant", "no", "without", "kein",
"nicht", "keine", "keinen", "keinem", "never", "niemals",
"weder", "nor", "neither", NULL
};
while ((p = strstr(p, keyword)) != NULL) {
int at_start = (p == lowered_text);
int before_ok = at_start || !isalpha((unsigned char)*(p - 1));
int after_ok = (p[kwlen] == '\0') || !isalpha((unsigned char)p[kwlen]);
if (before_ok && after_ok) {
const char *scan = p - 1;
int words_back = 0;
while (scan >= lowered_text && words_back < 5) {
while (scan >= lowered_text && isspace((unsigned char)*scan)) scan--;
if (scan < lowered_text) break;
const char *word_end = scan;
while (scan >= lowered_text && isalpha((unsigned char)*scan)) scan--;
const char *word_start = scan + 1;
int wlen = word_end - word_start + 1;
if (wlen > 0 && wlen < 32) {
char wbuf[32];
memcpy(wbuf, word_start, wlen);
wbuf[wlen] = '\0';
for (int ni = 0; negations[ni]; ni++) {
if (strcmp(wbuf, negations[ni]) == 0) return 1;
}
words_back++;
}
if (scan >= lowered_text) scan--;
}
return 0;
}
p++;
}
return 0;
}
// ==================== TASK PROFILE ====================
static int word_to_num(const char *word);
static int extract_numbers(const char *prompt, int *nums, int max_nums) {
char buf[MAX_PROMPT];
SNPRINTF_CHECK(buf, sizeof(buf), "%s", prompt);
to_lowercase(buf);
int count = 0;
char *p = buf;
while (*p && count < max_nums) {
if (isalpha((unsigned char)*p)) {
char word[32]; int wi = 0;
while (*p && isalpha((unsigned char)*p) && wi < 31) word[wi++] = *p++;
word[wi] = '\0';
int n = word_to_num(word);
if (n >= 0) nums[count++] = n;
continue;
}
p++;
}
p = buf;
while (*p && count < max_nums) {
if (isdigit((unsigned char)*p)) {
char *prev = p - 1;
while (prev >= buf && (isalpha((unsigned char)*prev) || *prev == '_')) prev--;
prev++;
if (prev < p) {
char prefix[16]; int pi = 0;
while (prev < p && pi < 15) prefix[pi++] = *prev++;
prefix[pi] = '\0';
if (prefix[0] == 'i' && prefix[1] == 'n' && prefix[2] == 't') {
while (*p && isdigit((unsigned char)*p)) p++;
continue;
}
if (strcmp(prefix, "const") == 0) {
while (*p && isdigit((unsigned char)*p)) p++;
continue;
}
}
char *endptr = NULL;
long val = strtol(p, &endptr, 10);
if (endptr != p && val >= INT_MIN && val <= INT_MAX)
nums[count++] = (int)val;
while (*p && isdigit((unsigned char)*p)) p++;
continue;
}
p++;
}
return count;
}
// Forward declarations for plan-based generator
/* ── parse_task helpers ─────────────────────────────────────────────────── */
static void parse_task_detect_type(const char *buf, TaskProfile *task) {
if (strstr(buf, "byte") || strstr(buf, "int8")) SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "byte");
else if (strstr(buf, "int16") || strstr(buf, "short")) SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "int16");
else if (strstr(buf, "int32")) SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "int32");
else if (strstr(buf, "int64") || _has_word_lowered(buf, "int") || strstr(buf, "long")) SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "int64");
else if (strstr(buf, "double") || strstr(buf, "float") || strstr(buf, "real") || strstr(buf, "komma")) SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "double");
}
static void parse_task_detect_literals(const char *prompt, const char *buf, TaskProfile *task) {
task->num_literals = extract_numbers(prompt, task->literals, MAX_NUMS);
int has_decimals = 0;
for (int di = 0; di < task->num_literals && di < MAX_NUMS; di++)
task->double_literals[di] = (double)task->literals[di];
{
char dscan[MAX_PROMPT];
SNPRINTF_CHECK(dscan, sizeof(dscan), "%s", buf);
char *dp = dscan;
int di = 0;
while (*dp && di < MAX_NUMS) {
if (isdigit((unsigned char)*dp)) {
char *start = dp;
while (*dp && (isdigit((unsigned char)*dp) || *dp == '.')) dp++;
if (strchr(start, '.') != NULL) {
char *endptr_d = NULL;
task->double_literals[di] = strtod(start, &endptr_d);
if (endptr_d == start) task->double_literals[di] = 0.0;
has_decimals = 1;
} else {
task->double_literals[di] = (double)task->literals[di];
}
di++;
continue;
}
dp++;
}
if (has_decimals) {
task->num_literals = di;
SNPRINTF_CHECK(task->type, sizeof(task->type), "%s", "double");
}
}
if (task->num_literals > 0) TF_SET(task, FLAG_literals); else TF_CLR(task, FLAG_literals);
}
static void parse_task_detect_io(char *buf, TaskProfile *task) {
/* count detection: word before "numbers/werte/zahlen/values" */
char *p = buf;
while (*p) {
if (strncmp(p, "numbers", 7) == 0 || strncmp(p, "werte", 5) == 0 || strncmp(p, "zahlen", 6) == 0 || strncmp(p, "values", 6) == 0) {
char *q = p - 1;
while (q >= buf && isspace((unsigned char)*q)) q--;
while (q >= buf && isdigit((unsigned char)*q)) q--;
q++;
if (q < p && isdigit((unsigned char)*q)) {
task->input_count = (int)strtol(q, NULL, 10);
TF_SET(task, FLAG_input);
} else {
q = p - 1;
while (q >= buf && isspace((unsigned char)*q)) q--;
char *end = q + 1;
while (q >= buf && isalpha((unsigned char)*q)) q--;
q++;
if (q < end) {
char w[32]; int wi = 0;
while (q < end && wi < 31) w[wi++] = *q++;
w[wi] = '\0';
int n = word_to_num(w);
if (n > 0) { task->input_count = n; TF_SET(task, FLAG_input); }
}
}
break;
}
p++;
}
/* detect input keywords */
if (_has_word_lowered(buf, "lies") || _has_word_lowered(buf, "lese") || _has_word_lowered(buf, "read") || _has_word_lowered(buf, "input")
|| _has_word_lowered(buf, "gib") || _has_word_lowered(buf, "enter") || _has_word_lowered(buf, "erfasse")
|| _has_word_lowered(buf, "collect") || _has_word_lowered(buf, "eingabe") || _has_word_lowered(buf, "einlesen"))
TF_SET(task, FLAG_input);
/* detect output */
if (_has_word_lowered(buf, "print") || _has_word_lowered(buf, "druck") || _has_word_lowered(buf, "ausg")
|| _has_word_lowered(buf, "show") || _has_word_lowered(buf, "display") || _has_word_lowered(buf, "zeig")
|| _has_word_lowered(buf, "output") || _has_word_lowered(buf, "schreib"))
TF_SET(task, FLAG_output);
/* detect print variable */
if (TF_ISSET(task, FLAG_output) && strstr(buf, "variable"))
TF_SET(task, FLAG_print_var);
/* detect operation */
const char *op = find_operation(buf);
if (op) {
TF_SET(task, FLAG_operation);
SNPRINTF_CHECK(task->op, sizeof(task->op), "%s", op);
if (strcmp(op, "add") == 0) TF_SET(task, FLAG_add);
else if (strcmp(op, "sub") == 0) TF_SET(task, FLAG_sub);
else if (strcmp(op, "mul") == 0) TF_SET(task, FLAG_mul);
else if (strcmp(op, "div") == 0) TF_SET(task, FLAG_div);
}
for (int oi = 0; oi < (int)(sizeof(ops)/sizeof(ops[0])); oi++) {
if (strstr(buf, ops[oi].op)) {
if (strcmp(ops[oi].rpn_op, "add") == 0) TF_SET(task, FLAG_add);
else if (strcmp(ops[oi].rpn_op, "sub") == 0) TF_SET(task, FLAG_sub);
else if (strcmp(ops[oi].rpn_op, "mul") == 0) TF_SET(task, FLAG_mul);
else if (strcmp(ops[oi].rpn_op, "div") == 0) TF_SET(task, FLAG_div);
}
}
/* build operation sequence in prompt order */
task->num_ops = 0;
{
int found_ops = 0;
int op_positions[32];
char op_names[32][64];
for (int oi = 0; oi < (int)(sizeof(ops)/sizeof(ops[0])); oi++) {
char *pp = buf;
while ((pp = strstr(pp, ops[oi].op)) != NULL && found_ops < 32) {
int at_start = (pp == buf);
int before_ok = at_start || !isalpha((unsigned char)*(pp - 1));
if (before_ok) {
int pos = (int)(pp - buf);
int dup = 0;
for (int di = 0; di < found_ops; di++) {
if (op_positions[di] == pos) { dup = 1; break; }
}
if (!dup) {
op_positions[found_ops] = pos;
SNPRINTF_CHECK(op_names[found_ops], sizeof(op_names[0]), "%s", ops[oi].rpn_op);
found_ops++;
}
}
pp++;
}
}
for (int i = 0; i < found_ops - 1; i++) {
for (int j = i + 1; j < found_ops; j++) {
if (op_positions[j] < op_positions[i]) {
int tp = op_positions[i]; op_positions[i] = op_positions[j]; op_positions[j] = tp;
char tn[64]; memcpy(tn, op_names[i], sizeof(tn));
memcpy(op_names[i], op_names[j], sizeof(op_names[i]));
memcpy(op_names[j], tn, sizeof(op_names[j]));