-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.c
More file actions
732 lines (616 loc) · 17.8 KB
/
Copy pathmain.c
File metadata and controls
732 lines (616 loc) · 17.8 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
/*
* Copyright (c) 2012 Alex Hornung <alex@alexhornung.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <dirent.h>
#include <signal.h>
#include <assert.h>
#include <ctype.h>
#include <gmp.h>
#include <mpfr.h>
#include "linenoise.h"
#include "hashtable.h"
#include "optype.h"
#include "num.h"
#include "var.h"
#include "ast.h"
#include "calc.h"
#include "func.h"
#include "safe_mem.h"
#include "calc.tab.h"
#include "lex.yy.h"
static
char *
filename_in_home(const char *fname)
{
static char p[4096];
struct passwd *pw = getpwuid(getuid());
snprintf(p, sizeof(p)-1, "%s/%s", pw->pw_dir, fname);
return p;
}
void
yyxerror(const char *s, ...)
{
va_list ap;
va_start(ap, s);
fprintf(stderr, "%d: error: ", 0 /* XXX: HACK! */);
vfprintf(stderr, s, ap);
fprintf(stderr, "\n");
//nesting = 0;
/* XXX: hack ^ */
}
static
char *
prompt(struct parse_ctx *ctx)
{
static char buf[1024];
int i;
if (ctx->nesting || ctx->linecont) {
snprintf(buf, sizeof(buf), "..");
for (i = 0; i < ctx->nesting; i++)
strcat(buf, "..");
strcat(buf, " ");
} else {
snprintf(buf, sizeof(buf), "-> ");
}
return buf;
}
struct comp_helper {
void *priv;
const char *filter;
size_t filter_len;
};
/* Hints callback: show remaining argument names as ghost text when the
* cursor is inside a function call. Examples:
* atan2( -> y, x)
* atan2(0.5, -> x)
* sqrt( -> a)
* Also completes variable names as ghost text:
* foobar_ -> x (if foobar_x is the only match)
* fo -> o (longest common prefix among foo, foobar, foobaz)
*/
static char hint_buf[256];
struct hint_var_ctx {
const char *prefix;
int prefix_len;
char common[256];
int common_len;
int count;
};
static void
_collect_var_hint(void *priv, const char *name)
{
struct hint_var_ctx *ctx = priv;
if (strncmp(name, ctx->prefix, ctx->prefix_len) != 0)
return;
const char *suffix = name + ctx->prefix_len;
int slen = (int)strlen(suffix);
if (ctx->count == 0) {
/* First match: seed common with full suffix. */
strncpy(ctx->common, suffix, sizeof(ctx->common) - 1);
ctx->common[sizeof(ctx->common) - 1] = '\0';
ctx->common_len = slen;
} else {
/* Subsequent matches: trim common to longest shared prefix. */
int i = 0;
while (i < ctx->common_len && i < slen && ctx->common[i] == suffix[i])
i++;
ctx->common_len = i;
ctx->common[i] = '\0';
}
ctx->count++;
}
static char *
linenoise_hints(const char *buf, int *color, int *bold)
{
int len = (int)strlen(buf);
int depth = 0, paren_pos = -1, i, h;
/* Find the innermost unclosed '(' scanning right-to-left. */
for (i = len - 1; i >= 0; i--) {
if (buf[i] == ')') depth++;
else if (buf[i] == '(') {
if (depth == 0) { paren_pos = i; break; }
depth--;
}
}
if (paren_pos < 0) {
/* Not inside a function call — try variable name completion hint.
* Extract the word being typed at the end of the buffer. */
int word_end = len;
int word_start = word_end;
while (word_start > 0 &&
(isalnum((unsigned char)buf[word_start-1]) || buf[word_start-1] == '_'))
word_start--;
/* Need at least one character and must start with a letter/underscore. */
if (word_start >= word_end ||
(!isalpha((unsigned char)buf[word_start]) && buf[word_start] != '_'))
return NULL;
char word[128];
int wlen = word_end - word_start;
if (wlen >= (int)sizeof(word)) return NULL;
memcpy(word, buf + word_start, wlen);
word[wlen] = '\0';
struct hint_var_ctx ctx;
ctx.prefix = word;
ctx.prefix_len = wlen;
ctx.common[0] = '\0';
ctx.common_len = 0;
ctx.count = 0;
var_iterate(&ctx, _collect_var_hint);
fun_iterate(&ctx, _collect_var_hint);
if (ctx.count == 0 || ctx.common_len == 0)
return NULL;
/* Build the hint: common suffix, then '(' if the completed
* name is a known function. */
strncpy(hint_buf, ctx.common, sizeof(hint_buf) - 2);
hint_buf[sizeof(hint_buf) - 2] = '\0';
int hlen = (int)strlen(hint_buf);
/* Check if prefix + common resolves to a function name. */
char full[256];
if (wlen + ctx.common_len < (int)sizeof(full)) {
memcpy(full, word, wlen);
memcpy(full + wlen, ctx.common, ctx.common_len);
full[wlen + ctx.common_len] = '\0';
if (funlookup(full, 0) != NULL)
hint_buf[hlen++] = '(';
}
hint_buf[hlen] = '\0';
*color = -1; /* no specific colour: let dim do the work */
*bold = 2; /* SGR 2 = dim/faint, adapts to light and dark backgrounds */
return hint_buf;
}
/* Extract function name immediately before the paren. */
int name_end = paren_pos;
int name_start = name_end;
while (name_start > 0 &&
(isalnum((unsigned char)buf[name_start-1]) || buf[name_start-1] == '_'))
name_start--;
if (name_start >= name_end || !isalpha((unsigned char)buf[name_start]))
return NULL;
int fname_len = name_end - name_start;
char fname[128];
if (fname_len >= (int)sizeof(fname)) return NULL;
memcpy(fname, buf + name_start, fname_len);
fname[fname_len] = '\0';
func_t fn = funlookup(fname, 0);
if (fn == NULL) return NULL;
/* Count commas at depth 0 inside the opening paren -> current arg index. */
int arg_idx = 0;
depth = 0;
for (i = paren_pos + 1; i < len; i++) {
if (buf[i] == '(' || buf[i] == '[') depth++;
else if (buf[i] == ')' || buf[i] == ']') depth--;
else if (buf[i] == ',' && depth == 0) arg_idx++;
}
/* Are we at the START of the current arg slot (nothing typed for it yet)?
* Yes if the last non-space char at/after the opening paren is '(' or ','. */
int at_start = 1;
{
int j = len - 1;
while (j > paren_pos && buf[j] == ' ') j--;
at_start = (j == paren_pos) || (buf[j] == ',');
}
h = 0;
hint_buf[0] = '\0';
if (!fn->builtin && fn->namelist != NULL) {
/* User-defined function: walk to the right namelist position. */
namelist_t p = fn->namelist;
int skip = at_start ? arg_idx : arg_idx + 1;
for (i = 0; i < skip && p != NULL; i++)
p = p->next;
/* Past all args: just need closing paren. */
if (p == NULL) { hint_buf[0] = ')'; hint_buf[1] = '\0'; goto done; }
if (!at_start) { hint_buf[h++] = ','; hint_buf[h++] = ' '; }
int first = 1;
for (; p != NULL && h < (int)sizeof(hint_buf) - 4; p = p->next) {
if (!first) { hint_buf[h++] = ','; hint_buf[h++] = ' '; }
first = 0;
size_t nlen = strlen(p->name);
if (h + (int)nlen >= (int)sizeof(hint_buf) - 4) break;
memcpy(hint_buf + h, p->name, nlen);
h += nlen;
}
} else {
/* Builtin: generic arg names a, b, c, ... */
static const char *generic[] = {"a","b","c","d","e","f","g","h"};
int maxargs = fn->maxargs;
/* For variadic functions use minargs as the required-arg count;
* we always append '...' after. */
int nargs = (maxargs < 1000) ? maxargs : fn->minargs;
int start = at_start ? arg_idx : arg_idx + 1;
/* Past all required args and non-variadic: just need closing paren. */
if (start >= nargs && maxargs < 1000) {
hint_buf[0] = ')'; hint_buf[1] = '\0'; goto done;
}
if (!at_start) { hint_buf[h++] = ','; hint_buf[h++] = ' '; }
int first = 1;
for (i = start; i < nargs && h < (int)sizeof(hint_buf) - 8; i++) {
if (!first) { hint_buf[h++] = ','; hint_buf[h++] = ' '; }
first = 0;
hint_buf[h++] = (i < 8) ? *generic[i] : ('a' + i % 26);
}
if (maxargs >= 1000) {
/* Append '...' — add separator only if something came before
* and doesn't already end with a space. */
if (h > 0 && hint_buf[h-1] != ' ') {
hint_buf[h++] = ','; hint_buf[h++] = ' ';
}
hint_buf[h++] = '.'; hint_buf[h++] = '.'; hint_buf[h++] = '.';
}
}
hint_buf[h++] = ')';
hint_buf[h] = '\0';
done:
*color = -1; /* no specific colour */
*bold = 2; /* SGR 2 = dim/faint */
return hint_buf;
}
static
void
_var_completion_filter(void *priv, const char *var_name)
{
struct comp_helper *ph = priv;
if (strncmp(var_name, ph->filter, ph->filter_len) == 0) {
linenoiseAddCompletion(ph->priv, var_name);
}
}
static
void
_fun_completion_filter(void *priv, const char *fun_name)
{
struct comp_helper *ph = priv;
if (strncmp(fun_name, ph->filter, ph->filter_len) == 0) {
char with_paren[256];
snprintf(with_paren, sizeof(with_paren), "%s(", fun_name);
linenoiseAddCompletion(ph->priv, with_paren);
}
}
static
void
linenoise_completion(const char *buf, linenoiseCompletions *lc) {
struct comp_helper h;
if (buf[0] == '\0') {
linenoiseAddCompletion(lc, "ans ");
} else {
h.priv = lc;
h.filter = buf;
h.filter_len = strlen(buf);
var_iterate(&h, _var_completion_filter);
fun_iterate(&h, _fun_completion_filter);
}
}
int
yywrap(void *scanner)
{
struct parse_ctx *ctx;
char *line;
int len;
ctx = yyget_extra(scanner);
if (ctx->interactive) {
if (ctx->nesting || ctx->linecont) {
if ((line = linenoise(prompt(ctx))) != NULL) {
linenoiseHistoryAdd(line);
len = strlen(line);
line = realloc(line, len+2);
line[len] = '\n';
line[len+1] = '\0';
yy_scan_string(line, scanner);
free(line);
return 0;
} else {
fprintf(stderr, "Interrupted, exiting.\n");
graceful_exit();
}
}
}
return 1;
}
// TODO: join line continuations together before saving into history
void
graceful_exit(void)
{
int error;
if (isatty(fileno(stdin))) {
if ((error = linenoiseHistorySave(HISTORY_FILE)) == 0) {
printf("Saved command history to %s\n", HISTORY_FILE);
} else {
fprintf(stderr, "Couldn't save command history!\n");
}
}
exit(0);
}
static
void
sig_handler(int sig)
{
switch (sig) {
case SIGTERM:
fprintf(stderr, "Caught SIGTERM, exiting.\n");
graceful_exit();
break;
case SIGQUIT:
fprintf(stderr, "Caught SIGQUIT, exiting.\n");
graceful_exit();
break;
default:
fprintf(stderr, "Caught unexpected signal=%d\n", sig);
}
}
static
int
require_fd(FILE *fp, const char *fname, int silent)
{
struct parse_ctx ctx;
ctx.interactive = 0;
ctx.silent = silent;
ctx.linecont = ctx.nesting = 0;
ctx.filename = fname;
yylex_init(&ctx.scanner);
yyset_extra(&ctx, ctx.scanner);
yyset_in(fp, ctx.scanner);
yyparse(&ctx);
yylex_destroy(ctx.scanner);
return 0;
}
int
require_file(const char *file, int silent)
{
FILE *fp;
int error;
if ((fp = fopen(file, "r")) == NULL)
return -1;
error = require_fd(fp, file, silent);
if (isatty(fileno(stdin))) {
if (error)
printf("Error loading file: %s\n", file);
else
printf("Loaded file: %s\n", file);
}
fclose(fp);
return error;
}
static
int
dot_filter(const struct dirent *de)
{
if (de->d_name[0] == '.')
return 0;
return 1;
}
static
void
load_rc(void)
{
struct dirent **namelist;
char p[4096];
int n;
/* Load rc file, if it exists */
require_file(RC_FILE, 1);
/* Load each file, in order, in the rc directory */
if ((n = scandir(RC_DIRECTORY, &namelist, dot_filter, alphasort)) >= 0) {
for (int i = 0; i < n; i++) {
snprintf(p, sizeof(p)-1, "%s/%s", RC_DIRECTORY, namelist[i]->d_name);
require_file(p, 1);
free(namelist[i]);
}
free(namelist);
}
}
int
main(int argc, char *argv[])
{
struct parse_ctx ctx;
char *progname = argv[0];
char *line;
int len;
int error;
varinit();
num_init();
funinit();
signal(SIGTERM, sig_handler);
signal(SIGQUIT, sig_handler);
linenoiseHistorySetMaxLen(MAX_HIST_LEN);
linenoiseSetCompletionCallback(linenoise_completion);
linenoiseSetHintsCallback(linenoise_hints);
if (isatty(fileno(stdin))) {
printf("ascalc %d.%d - A Simple Console Calculator\n",
MAJ_VER, MIN_VER);
printf("Copyright (c) 2012-2026 Alex Hornung\n\n");
load_rc();
if ((error = linenoiseHistoryLoad(HISTORY_FILE)) == 0) {
printf("Loaded previous command history from %s\n\n", HISTORY_FILE);
}
printf("Type 'help' for available commands\n");
printf("\n");
ctx.interactive = 1;
ctx.silent = 0;
ctx.linecont = ctx.nesting = 0;
ctx.filename = "<stdin>";
yylex_init(&ctx.scanner);
yyset_extra(&ctx, ctx.scanner);
while ((line = linenoise(prompt(&ctx))) != NULL) {
linenoiseHistoryAdd(line);
len = strlen(line);
line = realloc(line, len + 2);
line[len] = '\n';
line[len+1] = '\0';
yy_scan_string(line, ctx.scanner);
free(line);
yyparse(&ctx);
}
fprintf(stderr, "Interrupted, exiting.\n");
graceful_exit();
} else {
load_rc();
require_fd(stdin, "<stdin>", 0);
}
return 0;
}
static char mode = 'd';
mpfr_rnd_t round_mode = MPFR_RNDN;
static int scientific_mode = 0;
void
mode_switch(char new_mode)
{
mode = new_mode;
round_mode = (new_mode == 'd' || new_mode == 's') ? MPFR_RNDN : MPFR_RNDZ;
mpfr_set_default_rounding_mode(round_mode);
scientific_mode = (new_mode == 's');
}
void
num_print(num_t n)
{
const char *prefix = "";
char *s;
num_t a;
int base;
switch (mode) {
case 'b': base = 2; prefix = "0b"; break;
case 'd': base = 10; prefix = ""; break;
case 'x':
case 'h': base = 16; prefix = "0x"; break;
case 'o': base = 8; prefix = "0"; break;
default: base = 10; prefix = "";
}
if (base != 10 && n->num_type != NUM_INT)
a = num_new_z(N_TEMP, n);
else
a = n;
if (a->num_type == NUM_INT) {
if ((s = mpz_get_str(NULL, base, Z(a))) == NULL) {
yyxerror("ENOMEM");
exit(1);
}
mpfr_printf("%s%s\n", prefix, s);
free(s);
} else if (a->num_type == NUM_FP) {
if (scientific_mode) {
mpfr_printf("%.6R*G\n", round_mode, F(a));
} else if (mpfr_integer_p(F(a))) {
mpfr_printf("%.0R*f\n", round_mode, F(a));
} else {
mpfr_printf("%.6R*g\n", round_mode, F(a));
}
} else {
printf("invalid!\n");
}
}
int
num_snprint(char *s, size_t sz, int w, num_t n)
{
const char *prefix = "";
char *str;
num_t a;
int base;
int r = 0;
switch (mode) {
case 'b': base = 2; prefix = "0b"; break;
case 'd': base = 10; prefix = ""; break;
case 'x':
case 'h': base = 16; prefix = "0x"; break;
case 'o': base = 8; prefix = "0"; break;
default: base = 10; prefix = "";
}
if (base != 10 && n->num_type != NUM_INT)
a = num_new_z(N_TEMP, n);
else
a = n;
if (a->num_type == NUM_INT) {
if ((str = mpz_get_str(NULL, base, Z(a))) == NULL) {
yyxerror("ENOMEM");
exit(1);
}
switch (mode) {
case 'b': r = gmp_snprintf(s, sz, "%s%s", prefix, str); break;
case 'x':
case 'h': r = gmp_snprintf(s, sz, "%s%*Zx", prefix, w, Z(a)); break;
case 'o': r = gmp_snprintf(s, sz, "%s%*Zo", prefix, w, Z(a)); break;
case 'd':
default: r = gmp_snprintf(s, sz, "%s%*Zd", prefix, w, Z(a)); break;
}
free(str);
} else if (a->num_type == NUM_FP) {
if (scientific_mode) {
r = mpfr_snprintf(s, sz, "%*.6R*G", w, round_mode, F(a));
} else if (mpfr_integer_p(F(a))) {
r = mpfr_snprintf(s, sz, "%*.0R*f", w, round_mode, F(a));
} else {
r = mpfr_snprintf(s, sz, "%*.6R*f", w, round_mode, F(a));
}
} else {
r = snprintf(s, sz, "invalid!");
}
return r;
}
extern int nallocations;
void
go(struct parse_ctx *ctx, ast_t a)
{
var_t var;
num_t ans, old_ans = NULL;
//printf("Allocations: %d\n", nallocations);
ans = eval(a, NULL);
if (ans == NULL)
return;
if (!ctx->silent) {
if (isatty(fileno(stdin)))
printf("ans = ");
num_print(ans);
}
var = varlookup("ans", 1);
if (var->v != NULL)
old_ans = var->v;
var->v = num_new_fp(0, ans);
if (old_ans != NULL)
num_delete(old_ans);
num_delete_temp();
ast_delete(a);
//printf("Allocations: %d\n", nallocations);
}
void
help(void)
{
printf("Commands:\n");
printf("\tls\t\t- Lists all variables\n\n");
printf("\tlsfn\t\t- Lists all functions\n\n");
printf("\thelp\t\t- Lists available commands\n\n");
printf("\thelp <name>\t- Show help for a function\n\n");
printf("\tm <MODE>\t- Same as 'mode'\n\n");
printf("\tmode <MODE>\t- Switches to <MODE>, where mode is one\n");
printf("\t\t\t of the following: b,d,s,h,o,x - for binary, decimal, \n");
printf("\t\t\t scientific decimal, hexadecimal, octal, hexadecimal, \n");
printf("\t\t\t output\n\n");
printf("\tquit\t\t- Exits the program\n\n");
printf("\texit\t\t- Exits the program\n\n");
}