forked from cal/fishfish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.c
3641 lines (3046 loc) · 69.2 KB
/
parser.c
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
/** \file parser.c
The fish parser. Contains functions for parsing and evaluating code.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <pwd.h>
#include <dirent.h>
#include <signal.h>
#include "fallback.h"
#include "util.h"
#include "common.h"
#include "wutil.h"
#include "proc.h"
#include "parser.h"
#include "parser_keywords.h"
#include "tokenizer.h"
#include "exec.h"
#include "wildcard.h"
#include "function.h"
#include "builtin.h"
#include "env.h"
#include "expand.h"
#include "reader.h"
#include "sanity.h"
#include "env_universal.h"
#include "event.h"
#include "intern.h"
#include "parse_util.h"
#include "halloc.h"
#include "halloc_util.h"
#include "path.h"
#include "signal.h"
/**
Maximum number of block levels in code. This is not the same as
maximum recursion depth, this only has to do with how many block
levels are legal in the source code, not at evaluation.
*/
#define BLOCK_MAX_COUNT 64
/**
Maximum number of function calls, i.e. recursion depth.
*/
#define MAX_RECURSION_DEPTH 128
/**
Error message for unknown builtin
*/
#define UNKNOWN_BUILTIN_ERR_MSG _(L"Unknown builtin '%ls'")
/**
Error message for improper use of the exec builtin
*/
#define EXEC_ERR_MSG _(L"This command can not be used in a pipeline")
/**
Error message for tokenizer error. The tokenizer message is
appended to this message.
*/
#define TOK_ERR_MSG _( L"Tokenizer error: '%ls'")
/**
Error message for short circuit command error.
*/
#define COND_ERR_MSG _( L"An additional command is required" )
/**
Error message on reaching maximum recusrion depth
*/
#define RECURSION_ERR_MSG _( L"Maximum recursion depth reached. Accidental infinite loop?")
/**
Error message used when the end of a block can't be located
*/
#define BLOCK_END_ERR_MSG _( L"Could not locate end of block. The 'end' command is missing, misspelled or a ';' is missing.")
/**
Error message on reaching maximum number of block calls
*/
#define BLOCK_ERR_MSG _( L"Maximum number of nested blocks reached.")
/**
Error message when a non-string token is found when expecting a command name
*/
#define CMD_ERR_MSG _( L"Expected a command name, got token of type '%ls'")
/**
Error message when a non-string token is found when expecting a command name
*/
#define CMD_OR_ERR_MSG _( L"Expected a command name, got token of type '%ls'. Did you mean 'COMMAND; or COMMAND'? See the help section for the 'or' builtin command by typing 'help or'.")
/**
Error message when a non-string token is found when expecting a command name
*/
#define CMD_AND_ERR_MSG _( L"Expected a command name, got token of type '%ls'. Did you mean 'COMMAND; and COMMAND'? See the help section for the 'and' builtin command by typing 'help and'.")
/**
Error message when encountering an illegal command name
*/
#define ILLEGAL_CMD_ERR_MSG _( L"Illegal command name '%ls'")
/**
Error message when encountering an illegal file descriptor
*/
#define ILLEGAL_FD_ERR_MSG _( L"Illegal file descriptor '%ls'")
/**
Error message for wildcards with no matches
*/
#define WILDCARD_ERR_MSG _( L"Warning: No match for wildcard '%ls'. The command will not be executed.")
/**
Error when using case builtin outside of switch block
*/
#define INVALID_CASE_ERR_MSG _( L"'case' builtin not inside of switch block")
/**
Error when using loop control builtins (break or continue) outside of loop
*/
#define INVALID_LOOP_ERR_MSG _( L"Loop control command while not inside of loop" )
/**
Error when using return builtin outside of function definition
*/
#define INVALID_RETURN_ERR_MSG _( L"'return' builtin command outside of function definition" )
/**
Error when using else builtin outside of if block
*/
#define INVALID_ELSE_ERR_MSG _( L"'else' builtin not inside of if block" )
/**
Error when using end builtin outside of block
*/
#define INVALID_END_ERR_MSG _( L"'end' command outside of block")
/**
Error message for Posix-style assignment
*/
#define COMMAND_ASSIGN_ERR_MSG _( L"Unknown command '%ls'. Did you mean 'set %ls %ls'? For information on assigning values to variables, see the help section on the set command by typing 'help set'.")
/**
Error for invalid redirection token
*/
#define REDIRECT_TOKEN_ERR_MSG _( L"Expected redirection specification, got token of type '%ls'")
/**
Error when encountering redirection without a command
*/
#define INVALID_REDIRECTION_ERR_MSG _( L"Encountered redirection when expecting a command name. Fish does not allow a redirection operation before a command.")
/**
Error for evaluating null pointer
*/
#define EVAL_NULL_ERR_MSG _( L"Tried to evaluate null pointer." )
/**
Error for evaluating in illegal scope
*/
#define INVALID_SCOPE_ERR_MSG _( L"Tried to evaluate commands using invalid block type '%ls'" )
/**
Error for wrong token type
*/
#define UNEXPECTED_TOKEN_ERR_MSG _( L"Unexpected token of type '%ls'")
/**
While block description
*/
#define WHILE_BLOCK N_( L"'while' block" )
/**
For block description
*/
#define FOR_BLOCK N_( L"'for' block" )
/**
Breakpoint block
*/
#define BREAKPOINT_BLOCK N_( L"Block created by breakpoint" )
/**
If block description
*/
#define IF_BLOCK N_( L"'if' conditional block" )
/**
Function definition block description
*/
#define FUNCTION_DEF_BLOCK N_( L"function definition block" )
/**
Function invocation block description
*/
#define FUNCTION_CALL_BLOCK N_( L"function invocation block" )
/**
Function invocation block description
*/
#define FUNCTION_CALL_NO_SHADOW_BLOCK N_( L"function invocation block with no variable shadowing" )
/**
Switch block description
*/
#define SWITCH_BLOCK N_( L"'switch' block" )
/**
Fake block description
*/
#define FAKE_BLOCK N_( L"unexecutable block" )
/**
Top block description
*/
#define TOP_BLOCK N_( L"global root block" )
/**
Command substitution block description
*/
#define SUBST_BLOCK N_( L"command substitution block" )
/**
Begin block description
*/
#define BEGIN_BLOCK N_( L"'begin' unconditional block" )
/**
Source block description
*/
#define SOURCE_BLOCK N_( L"Block created by the . builtin" )
/**
Source block description
*/
#define EVENT_BLOCK N_( L"event handler block" )
/**
Unknown block description
*/
#define UNKNOWN_BLOCK N_( L"unknown/invalid block" )
/**
Datastructure to describe a block type, like while blocks, command substitution blocks, etc.
*/
struct block_lookup_entry
{
/**
The block type id. The legal values are defined in parser.h.
*/
int type;
/**
The name of the builtin that creates this type of block, if any.
*/
const wchar_t *name;
/**
A description of this block type
*/
const wchar_t *desc;
}
;
/**
List of all legal block types
*/
static const struct block_lookup_entry block_lookup[]=
{
{
WHILE, L"while", WHILE_BLOCK
}
,
{
FOR, L"for", FOR_BLOCK
}
,
{
IF, L"if", IF_BLOCK
}
,
{
FUNCTION_DEF, L"function", FUNCTION_DEF_BLOCK
}
,
{
FUNCTION_CALL, 0, FUNCTION_CALL_BLOCK
}
,
{
FUNCTION_CALL_NO_SHADOW, 0, FUNCTION_CALL_NO_SHADOW_BLOCK
}
,
{
SWITCH, L"switch", SWITCH_BLOCK
}
,
{
FAKE, 0, FAKE_BLOCK
}
,
{
TOP, 0, TOP_BLOCK
}
,
{
SUBST, 0, SUBST_BLOCK
}
,
{
BEGIN, L"begin", BEGIN_BLOCK
}
,
{
SOURCE, L".", SOURCE_BLOCK
}
,
{
EVENT, 0, EVENT_BLOCK
}
,
{
BREAKPOINT, L"breakpoint", BREAKPOINT_BLOCK
}
,
{
0, 0, 0
}
}
;
/** Last error code */
static int error_code;
event_block_t *global_event_block=0;
io_data_t *block_io;
/** Position of last error */
static int err_pos;
/** Description of last error */
static string_buffer_t *err_buff=0;
/** Pointer to the current tokenizer */
static tokenizer *current_tokenizer;
/** String for representing the current line */
static string_buffer_t *lineinfo=0;
/** This is the position of the beginning of the currently parsed command */
static int current_tokenizer_pos;
/** The current innermost block */
block_t *current_block=0;
/** List of called functions, used to help prevent infinite recursion */
static array_list_t *forbidden_function;
/**
String index where the current job started.
*/
static int job_start_pos;
/**
List of all profiling data
*/
static array_list_t profile_data;
/**
Keeps track of how many recursive eval calls have been made. Eval
doesn't call itself directly, recursion happens on blocks and on
command substitutions.
*/
static int eval_level=-1;
static int parse_job( process_t *p,
job_t *j,
tokenizer *tok );
/**
Struct used to keep track of profiling data for a command
*/
typedef struct
{
/**
Time spent executing the specified command, including parse time for nested blocks.
*/
int exec;
/**
Time spent parsing the specified command, including execution time for command substitutions.
*/
int parse;
/**
The block level of the specified command. nested blocks and command substitutions both increase the block level.
*/
int level;
/**
If the execution of this command was skipped.
*/
int skipped;
/**
The command string.
*/
wchar_t *cmd;
} profile_element_t;
/**
Return the current number of block nestings
*/
/*
static int block_count( block_t *b )
{
if( b==0)
return 0;
return( block_count(b->outer)+1);
}
*/
void parser_push_block( int type )
{
block_t *new = halloc( 0, sizeof( block_t ));
new->src_lineno = parser_get_lineno();
new->src_filename = parser_current_filename()?intern(parser_current_filename()):0;
new->outer = current_block;
new->type = (current_block && current_block->skip)?FAKE:type;
/*
New blocks should be skipped if the outer block is skipped,
except TOP ans SUBST block, which open up new environments. Fake
blocks should always be skipped. Rather complicated... :-(
*/
new->skip=current_block?current_block->skip:0;
/*
Type TOP and SUBST are never skipped
*/
if( type == TOP || type == SUBST )
{
new->skip = 0;
}
/*
Fake blocks and function definition blocks are never executed
*/
if( type == FAKE || type == FUNCTION_DEF )
{
new->skip = 1;
}
new->job = 0;
new->loop_status=LOOP_NORMAL;
current_block = new;
if( (new->type != FUNCTION_DEF) &&
(new->type != FAKE) &&
(new->type != TOP) )
{
env_push( type == FUNCTION_CALL );
halloc_register_function_void( current_block, &env_pop );
}
}
void parser_pop_block()
{
block_t *old = current_block;
if( !current_block )
{
debug( 1,
L"function %s called on empty block stack.",
__func__);
bugreport();
return;
}
current_block = current_block->outer;
halloc_free( old );
}
const wchar_t *parser_get_block_desc( int block )
{
int i;
for( i=0; block_lookup[i].desc; i++ )
{
if( block_lookup[i].type == block )
{
return _( block_lookup[i].desc );
}
}
return _(UNKNOWN_BLOCK);
}
/**
Returns 1 if the specified command is a builtin that may not be used in a pipeline
*/
static int parser_is_pipe_forbidden( wchar_t *word )
{
return contains( word,
L"exec",
L"case",
L"break",
L"return",
L"continue" );
}
/**
Search the text for the end of the current block
*/
static const wchar_t *parser_find_end( const wchar_t * buff )
{
tokenizer tok;
int had_cmd=0;
int count = 0;
int error=0;
int mark=0;
CHECK( buff, 0 );
for( tok_init( &tok, buff, 0 );
tok_has_next( &tok ) && !error;
tok_next( &tok ) )
{
int last_type = tok_last_type( &tok );
switch( last_type )
{
case TOK_STRING:
{
if( !had_cmd )
{
if( wcscmp(tok_last(&tok), L"end")==0)
{
count--;
}
else if( parser_keywords_is_block( tok_last(&tok) ) )
{
count++;
}
if( count < 0 )
{
error = 1;
}
had_cmd = 1;
}
break;
}
case TOK_END:
{
had_cmd = 0;
break;
}
case TOK_PIPE:
case TOK_BACKGROUND:
{
if( had_cmd )
{
had_cmd = 0;
}
else
{
error = 1;
}
break;
}
case TOK_ERROR:
error = 1;
break;
default:
break;
}
if(!count)
{
tok_next( &tok );
mark = tok_get_pos( &tok );
break;
}
}
tok_destroy( &tok );
if(!count && !error){
return buff+mark;
}
return 0;
}
void parser_forbid_function( wchar_t *function )
{
/*
if( function )
debug( 2, L"Forbid %ls\n", function );
*/
CHECK( function, );
al_push( forbidden_function, function?wcsdup(function):0 );
}
void parser_allow_function()
{
/*
if( al_peek( &forbidden_function) )
debug( 2, L"Allow %ls\n", al_peek( &forbidden_function) );
*/
free( (void *) al_pop( forbidden_function ) );
}
void error( int ec, int p, const wchar_t *str, ... )
{
va_list va;
CHECK( str, );
if( !err_buff )
err_buff = sb_halloc( global_context );
sb_clear( err_buff );
error_code = ec;
err_pos = p;
va_start( va, str );
sb_vprintf( err_buff, str, va );
va_end( va );
}
void parser_init()
{
if( profile )
{
al_init( &profile_data);
}
forbidden_function = al_new();
}
/**
Print profiling information to the specified stream
*/
static void print_profile( array_list_t *p,
int pos,
FILE *out )
{
profile_element_t *me, *prev;
int i;
int my_time;
if( pos >= al_get_count( p ) )
{
return;
}
me= (profile_element_t *)al_get( p, pos );
if( !me->skipped )
{
my_time=me->parse+me->exec;
for( i=pos+1; i<al_get_count(p); i++ )
{
prev = (profile_element_t *)al_get( p, i );
if( prev->skipped )
{
continue;
}
if( prev->level <= me->level )
{
break;
}
if( prev->level > me->level+1 )
{
continue;
}
my_time -= prev->parse;
my_time -= prev->exec;
}
if( me->cmd )
{
if( fwprintf( out, L"%d\t%d\t", my_time, me->parse+me->exec ) < 0 )
{
wperror( L"fwprintf" );
return;
}
for( i=0; i<me->level; i++ )
{
if( fwprintf( out, L"-" ) < 0 )
{
wperror( L"fwprintf" );
return;
}
}
if( fwprintf( out, L"> %ls\n", me->cmd ) < 0 )
{
wperror( L"fwprintf" );
return;
}
}
}
print_profile( p, pos+1, out );
free( me->cmd );
free( me );
}
void parser_destroy()
{
if( profile )
{
/*
Save profiling information
*/
FILE *f = fopen( profile, "w" );
if( !f )
{
debug( 1,
_(L"Could not write profiling information to file '%s'"),
profile );
}
else
{
if( fwprintf( f,
_(L"Time\tSum\tCommand\n"),
al_get_count( &profile_data ) ) < 0 )
{
wperror( L"fwprintf" );
}
else
{
print_profile( &profile_data, 0, f );
}
if( fclose( f ) )
{
wperror( L"fclose" );
}
}
al_destroy( &profile_data );
}
if( lineinfo )
{
sb_destroy( lineinfo );
free(lineinfo );
lineinfo = 0;
}
al_destroy( forbidden_function );
free( forbidden_function );
}
/**
Print error message to string_buffer_t if an error has occured while parsing
\param target the buffer to write to
\param prefix: The string token to prefix the ech line with. Usually the name of the command trying to parse something.
*/
static void print_errors( string_buffer_t *target, const wchar_t *prefix )
{
CHECK( target, );
CHECK( prefix, );
if( error_code && err_buff )
{
int tmp;
sb_printf( target, L"%ls: %ls\n", prefix, (wchar_t *)err_buff->buff );
tmp = current_tokenizer_pos;
current_tokenizer_pos = err_pos;
sb_printf( target, L"%ls", parser_current_line() );
current_tokenizer_pos=tmp;
}
}
/**
Print error message to stderr if an error has occured while parsing
*/
static void print_errors_stderr()
{
if( error_code && err_buff )
{
debug( 0, L"%ls", (wchar_t *)err_buff->buff );
int tmp;
tmp = current_tokenizer_pos;
current_tokenizer_pos = err_pos;
fwprintf( stderr, L"%ls", parser_current_line() );
current_tokenizer_pos=tmp;
}
}
int eval_args( const wchar_t *line, array_list_t *args )
{
tokenizer tok;
/*
eval_args may be called while evaulating another command, so we
save the previous tokenizer and restore it on exit
*/
tokenizer *previous_tokenizer=current_tokenizer;
int previous_pos=current_tokenizer_pos;
int do_loop=1;
CHECK( line, 1 );
CHECK( args, 1 );
proc_push_interactive(0);
current_tokenizer = &tok;
current_tokenizer_pos = 0;
tok_init( &tok, line, 0 );
error_code=0;
for(;do_loop && tok_has_next( &tok) ; tok_next( &tok ) )
{
current_tokenizer_pos = tok_get_pos( &tok );
switch(tok_last_type( &tok ) )
{
case TOK_STRING:
{
wchar_t *tmp = wcsdup(tok_last( &tok ));
if( !tmp )
{
DIE_MEM();
}
if( expand_string( 0, tmp, args, 0 ) == EXPAND_ERROR )
{
err_pos=tok_get_pos( &tok );
do_loop=0;
}
break;
}
case TOK_END:
{
break;
}
case TOK_ERROR:
{
error( SYNTAX_ERROR,
tok_get_pos( &tok ),
TOK_ERR_MSG,
tok_last(&tok) );
do_loop=0;
break;
}
default:
{
error( SYNTAX_ERROR,
tok_get_pos( &tok ),
UNEXPECTED_TOKEN_ERR_MSG,
tok_get_desc( tok_last_type(&tok)) );
do_loop=0;
break;
}
}
}
print_errors_stderr();
tok_destroy( &tok );
current_tokenizer=previous_tokenizer;
current_tokenizer_pos = previous_pos;
proc_pop_interactive();
return 1;
}
void parser_stack_trace( block_t *b, string_buffer_t *buff)
{
/*
Validate input
*/
CHECK( buff, );
/*
Check if we should end the recursion
*/
if( !b )
return;
if( b->type==EVENT )
{
/*
This is an event handler
*/
sb_printf( buff, _(L"in event handler: %ls\n"), event_get_desc( b->param1.event ));
sb_printf( buff,
L"\n" );
/*
Stop recursing at event handler. No reason to belive that
any other code is relevant.
It might make sense in the future to continue printing the
stack trace of the code that invoked the event, if this is a
programmatic event, but we can't currently detect that.
*/
return;
}
if( b->type == FUNCTION_CALL || b->type==SOURCE || b->type==SUBST)
{
/*
These types of blocks should be printed
*/
int i;
switch( b->type)
{
case SOURCE:
{
sb_printf( buff, _(L"in . (source) call of file '%ls',\n"), b->param1.source_dest );
break;
}
case FUNCTION_CALL:
{
sb_printf( buff, _(L"in function '%ls',\n"), b->param1.function_call_name );
break;
}
case SUBST:
{
sb_printf( buff, _(L"in command substitution\n") );
break;
}
}
const wchar_t *file = b->src_filename;
if( file )
{
sb_printf( buff,
_(L"\tcalled on line %d of file '%ls',\n"),
b->src_lineno,
file );
}
else
{
sb_printf( buff,
_(L"\tcalled on standard input,\n") );