codec cleanup
[platform/upstream/boost-jam.git] / compile.c
1 /*
2  * Copyright 1993, 2000 Christopher Seiwald.
3  *
4  * This file is part of Jam - see jam.c for Copyright information.
5  */
6
7 /*  This file is ALSO:
8  *  Copyright 2001-2004 David Abrahams.
9  *  Distributed under the Boost Software License, Version 1.0.
10  *  (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
11  */
12
13 # include "jam.h"
14
15 # include "lists.h"
16 # include "parse.h"
17 # include "compile.h"
18 # include "variable.h"
19 # include "expand.h"
20 # include "rules.h"
21 # include "newstr.h"
22 # include "make.h"
23 # include "search.h"
24 # include "hdrmacro.h"
25 # include "hash.h"
26 # include "modules.h"
27 # include "strings.h"
28 # include "builtins.h"
29 # include "class.h"
30
31 # include <assert.h>
32 # include <string.h>
33 # include <stdarg.h>
34
35 /*
36  * compile.c - compile parsed jam statements
37  *
38  * External routines:
39  *
40  *  compile_append() - append list results of two statements
41  *  compile_eval() - evaluate if to determine which leg to compile
42  *  compile_foreach() - compile the "for x in y" statement
43  *  compile_if() - compile 'if' rule
44  *  compile_while() - compile 'while' rule
45  *  compile_include() - support for 'include' - call include() on file
46  *  compile_list() - expand and return a list
47  *  compile_local() - declare (and set) local variables
48  *  compile_null() - do nothing -- a stub for parsing
49  *  compile_on() - run rule under influence of on-target variables
50  *  compile_rule() - compile a single user defined rule
51  *  compile_rules() - compile a chain of rules
52  *  compile_set() - compile the "set variable" statement
53  *  compile_setcomp() - support for `rule` - save parse tree
54  *  compile_setexec() - support for `actions` - save execution string
55  *  compile_settings() - compile the "on =" (set variable on exec) statement
56  *  compile_switch() - compile 'switch' rule
57  *
58  * Internal routines:
59  *
60  *  debug_compile() - printf with indent to show rule expansion.
61  *  evaluate_rule() - execute a rule invocation
62  *
63  *  builtin_depends() - DEPENDS/INCLUDES rule
64  *  builtin_echo() - ECHO rule
65  *  builtin_exit() - EXIT rule
66  *  builtin_flags() - NOCARE, NOTFILE, TEMPORARY rule
67  *
68  * 02/03/94 (seiwald) - Changed trace output to read "setting" instead of
69  *          the awkward sounding "settings".
70  * 04/12/94 (seiwald) - Combined build_depends() with build_includes().
71  * 04/12/94 (seiwald) - actionlist() now just appends a single action.
72  * 04/13/94 (seiwald) - added shorthand L0 for null list pointer
73  * 05/13/94 (seiwald) - include files are now bound as targets, and thus
74  *          can make use of $(SEARCH)
75  * 06/01/94 (seiwald) - new 'actions existing' does existing sources
76  * 08/23/94 (seiwald) - Support for '+=' (append to variable)
77  * 12/20/94 (seiwald) - NOTIME renamed NOTFILE.
78  * 01/22/95 (seiwald) - Exit rule.
79  * 02/02/95 (seiwald) - Always rule; LEAVES rule.
80  * 02/14/95 (seiwald) - NoUpdate rule.
81  * 09/11/00 (seiwald) - new evaluate_rule() for headers().
82  * 09/11/00 (seiwald) - compile_xxx() now return LIST *.
83  *          New compile_append() and compile_list() in
84  *          support of building lists here, rather than
85  *          in jamgram.yy.
86  * 01/10/00 (seiwald) - built-ins split out to builtin.c.
87  */
88
89 static void debug_compile( int which, char *s, FRAME* frame );
90 int glob( char *s, char *c );
91 /* Internal functions from builtins.c */
92 void backtrace( FRAME *frame );
93 void backtrace_line( FRAME *frame );
94 void print_source_line( PARSE* p );
95
96 struct frame * frame_before_python_call;
97
98 void frame_init( FRAME* frame )
99 {
100     frame->prev = 0;
101     frame->prev_user = 0;
102     lol_init(frame->args);
103     frame->module = root_module();
104     frame->rulename = "module scope";
105     frame->procedure = 0;
106 }
107
108
109 void frame_free( FRAME* frame )
110 {
111     lol_free( frame->args );
112 }
113
114
115 /*
116  * compile_append() - append list results of two statements
117  *
118  *  parse->left more compile_append() by left-recursion
119  *  parse->right    single rule
120  */
121
122 LIST * compile_append( PARSE * parse, FRAME * frame )
123 {
124     /* Append right to left. */
125     return list_append(
126         parse_evaluate( parse->left, frame ),
127         parse_evaluate( parse->right, frame ) );
128 }
129
130
131 /*
132  * compile_eval() - evaluate if to determine which leg to compile
133  *
134  * Returns:
135  *  list    if expression true - compile 'then' clause
136  *  L0  if expression false - compile 'else' clause
137  */
138
139 static int lcmp( LIST * t, LIST * s )
140 {
141     int status = 0;
142
143     while ( !status && ( t || s ) )
144     {
145         char *st = t ? t->string : "";
146         char *ss = s ? s->string : "";
147
148         status = strcmp( st, ss );
149
150         t = t ? list_next( t ) : t;
151         s = s ? list_next( s ) : s;
152     }
153
154     return status;
155 }
156
157 LIST * compile_eval( PARSE * parse, FRAME * frame )
158 {
159     LIST * ll;
160     LIST * lr;
161     LIST * s;
162     LIST * t;
163     int status = 0;
164
165     /* Short circuit lr eval for &&, ||, and 'in'. */
166
167     ll = parse_evaluate( parse->left, frame );
168     lr = 0;
169
170     switch ( parse->num )
171     {
172         case EXPR_AND:
173         case EXPR_IN : if ( ll ) goto eval; break;
174         case EXPR_OR : if ( !ll ) goto eval; break;
175         default: eval: lr = parse_evaluate( parse->right, frame );
176     }
177
178     /* Now eval. */
179     switch ( parse->num )
180     {
181     case EXPR_NOT: if ( !ll      ) status = 1; break;
182     case EXPR_AND: if ( ll && lr ) status = 1; break;
183     case EXPR_OR : if ( ll || lr ) status = 1; break;
184
185     case EXPR_IN:
186         /* "a in b": make sure each of ll is equal to something in lr. */
187         for ( t = ll; t; t = list_next( t ) )
188         {
189             for ( s = lr; s; s = list_next( s ) )
190             if ( !strcmp( t->string, s->string ) )
191                 break;
192             if ( !s ) break;
193         }
194         /* No more ll? Success. */
195         if ( !t ) status = 1;
196         break;
197
198     case EXPR_EXISTS: if ( lcmp( ll, L0 ) != 0 ) status = 1; break;
199     case EXPR_EQUALS: if ( lcmp( ll, lr ) == 0 ) status = 1; break;
200     case EXPR_NOTEQ : if ( lcmp( ll, lr ) != 0 ) status = 1; break;
201     case EXPR_LESS  : if ( lcmp( ll, lr ) < 0  ) status = 1; break;
202     case EXPR_LESSEQ: if ( lcmp( ll, lr ) <= 0 ) status = 1; break;
203     case EXPR_MORE  : if ( lcmp( ll, lr ) > 0  ) status = 1; break;
204     case EXPR_MOREEQ: if ( lcmp( ll, lr ) >= 0 ) status = 1; break;
205     }
206
207     if ( DEBUG_IF )
208     {
209         debug_compile( 0, "if", frame );
210         list_print( ll );
211         printf( "(%d) ", status );
212         list_print( lr );
213         printf( "\n" );
214     }
215
216     /* Find something to return. */
217     /* In odd circumstances (like "" = "") */
218     /* we'll have to return a new string. */
219
220     if ( !status ) t = 0;
221     else if ( ll ) t = ll, ll = 0;
222     else if ( lr ) t = lr, lr = 0;
223     else t = list_new( L0, newstr( "1" ) );
224
225     if ( ll ) list_free( ll );
226     if ( lr ) list_free( lr );
227     return t;
228 }
229
230
231 /*
232  * compile_foreach() - compile the "for x in y" statement
233  *
234  * Compile_foreach() resets the given variable name to each specified
235  * value, executing the commands enclosed in braces for each iteration.
236  *
237  *  parse->string   index variable
238  *  parse->left variable values
239  *  parse->right    rule to compile
240  */
241
242 LIST * compile_foreach( PARSE * parse, FRAME * frame )
243 {
244     LIST     * nv = parse_evaluate( parse->left, frame );
245     LIST     * l;
246     SETTINGS * s = 0;
247
248     if ( parse->num )
249     {
250         s = addsettings( s, VAR_SET, parse->string, L0 );
251         pushsettings( s );
252     }
253
254     /* Call var_set to reset $(parse->string) for each val. */
255
256     for ( l = nv; l; l = list_next( l ) )
257     {
258         LIST * val = list_new( L0, copystr( l->string ) );
259         var_set( parse->string, val, VAR_SET );
260         list_free( parse_evaluate( parse->right, frame ) );
261     }
262
263     if ( parse->num )
264     {
265         popsettings( s );
266         freesettings( s );
267     }
268
269     list_free( nv );
270
271     return L0;
272 }
273
274 /*
275  * compile_if() - compile 'if' rule
276  *
277  *  parse->left     condition tree
278  *  parse->right        then tree
279  *  parse->third        else tree
280  */
281
282 LIST * compile_if( PARSE * p, FRAME * frame )
283 {
284     LIST * l = parse_evaluate( p->left, frame );
285     if ( l )
286     {
287         list_free( l );
288         return parse_evaluate( p->right, frame );
289     }
290     return parse_evaluate( p->third, frame );
291 }
292
293
294 LIST * compile_while( PARSE * p, FRAME * frame )
295 {
296     LIST * r = 0;
297     LIST * l;
298     while ( ( l = parse_evaluate( p->left, frame ) ) )
299     {
300         list_free( l );
301         if ( r ) list_free( r );
302         r = parse_evaluate( p->right, frame );
303     }
304     return r;
305 }
306
307
308 /*
309  * compile_include() - support for 'include' - call include() on file
310  *
311  *  parse->left list of files to include (can only do 1)
312  */
313
314 LIST * compile_include( PARSE * parse, FRAME * frame )
315 {
316     LIST * nt = parse_evaluate( parse->left, frame );
317
318     if ( DEBUG_COMPILE )
319     {
320         debug_compile( 0, "include", frame);
321         list_print( nt );
322         printf( "\n" );
323     }
324
325     if ( nt )
326     {
327         TARGET * t = bindtarget( nt->string );
328
329         /* DWA 2001/10/22 - Perforce Jam cleared the arguments here, which
330          * prevents an included file from being treated as part of the body of a
331          * rule. I did not see any reason to do that, so I lifted the
332          * restriction.
333          */
334
335         /* Bind the include file under the influence of */
336         /* "on-target" variables.  Though they are targets, */
337         /* include files are not built with make(). */
338
339         pushsettings( t->settings );
340         /* We don't expect that file to be included is generated by some
341            action. Therefore, pass 0 as third argument.
342            If the name resolves to directory, let it error out.  */
343         t->boundname = search( t->name, &t->time, 0, 0 );
344         popsettings( t->settings );
345
346         parse_file( t->boundname, frame );
347     }
348
349     list_free( nt );
350
351     return L0;
352 }
353
354 static LIST* evaluate_in_module ( char* module_name, PARSE * p, FRAME* frame)
355 {
356     LIST* result;
357
358     module_t* outer_module = frame->module;
359     frame->module = module_name ? bindmodule( module_name ) : root_module();
360
361     if ( outer_module != frame->module )
362     {
363         exit_module( outer_module );
364         enter_module( frame->module );
365     }
366
367     result = parse_evaluate( p, frame );
368
369     if ( outer_module != frame->module )
370     {
371         exit_module( frame->module );
372         enter_module( outer_module );
373         frame->module = outer_module;
374     }
375
376     return result;
377 }
378
379
380 LIST * compile_module( PARSE * p, FRAME * frame )
381 {
382     /* Here we are entering a module declaration block. */
383     LIST * module_name = parse_evaluate( p->left, frame );
384     LIST * result = evaluate_in_module( module_name ? module_name->string : 0,
385                                        p->right, frame );
386     list_free( module_name );
387     return result;
388 }
389
390
391 LIST * compile_class( PARSE * p, FRAME * frame )
392 {
393     /** Todo: check for empty class name.
394         Check for class redeclaration. */
395
396     char * class_module = 0;
397
398     LIST * name = parse_evaluate( p->left->right, frame );
399     LIST * bases = 0;
400
401     if ( p->left->left )
402         bases = parse_evaluate( p->left->left->right, frame );
403
404     class_module = make_class_module( name, bases, frame );
405     evaluate_in_module( class_module, p->right, frame );
406
407     return L0;
408 }
409
410
411 /*
412  * compile_list() - expand and return a list.
413  *
414  *  parse->string - character string to expand.
415  */
416
417 LIST * compile_list( PARSE * parse, FRAME * frame )
418 {
419     /* s is a copyable string */
420     char * s = parse->string;
421     return var_expand( L0, s, s + strlen( s ), frame->args, 1 );
422 }
423
424
425 /*
426  * compile_local() - declare (and set) local variables.
427  *
428  *  parse->left    list of variables
429  *  parse->right   list of values
430  *  parse->third   rules to execute
431  */
432
433 LIST * compile_local( PARSE * parse, FRAME * frame )
434 {
435     LIST * l;
436     SETTINGS * s = 0;
437     LIST     * nt = parse_evaluate( parse->left, frame );
438     LIST     * ns = parse_evaluate( parse->right, frame );
439     LIST     * result;
440
441     if ( DEBUG_COMPILE )
442     {
443         debug_compile( 0, "local", frame );
444         list_print( nt );
445         printf( " = " );
446         list_print( ns );
447         printf( "\n" );
448     }
449
450     /* Initial value is ns. */
451     for ( l = nt; l; l = list_next( l ) )
452         s = addsettings( s, VAR_SET, l->string, list_copy( (LIST *)0, ns ) );
453
454     list_free( ns );
455     list_free( nt );
456
457     /* Note that callees of the current context get this "local" variable,
458      * making it not so much local as layered.
459      */
460
461     pushsettings( s );
462     result = parse_evaluate( parse->third, frame );
463     popsettings( s );
464
465     freesettings( s );
466
467     return result;
468 }
469
470
471 /*
472  * compile_null() - do nothing -- a stub for parsing.
473  */
474
475 LIST * compile_null( PARSE * parse, FRAME * frame )
476 {
477     return L0;
478 }
479
480
481 /*
482  * compile_on() - run rule under influence of on-target variables
483  *
484  *  parse->left    list of files to include (can only do 1).
485  *  parse->right   rule to run.
486  *
487  * EXPERIMENTAL!
488  */
489
490 LIST * compile_on( PARSE * parse, FRAME * frame )
491 {
492     LIST * nt = parse_evaluate( parse->left, frame );
493     LIST * result = 0;
494
495     if ( DEBUG_COMPILE )
496     {
497         debug_compile( 0, "on", frame );
498         list_print( nt );
499         printf( "\n" );
500     }
501
502     if ( nt )
503     {
504         TARGET * t = bindtarget( nt->string );
505         pushsettings( t->settings );
506         result = parse_evaluate( parse->right, frame );
507         popsettings( t->settings );
508     }
509
510     list_free( nt );
511
512     return result;
513 }
514
515
516 /*
517  * compile_rule() - compile a single user defined rule.
518  *
519  *  parse->string   name of user defined rule.
520  *  parse->left     parameters (list of lists) to rule, recursing left.
521  *
522  * Wrapped around evaluate_rule() so that headers() can share it.
523  */
524
525 LIST * compile_rule( PARSE * parse, FRAME * frame )
526 {
527     FRAME   inner[ 1 ];
528     LIST  * result;
529     PARSE * p;
530
531     /* Build up the list of arg lists. */
532     frame_init( inner );
533     inner->prev = frame;
534     inner->prev_user = frame->module->user_module ? frame : frame->prev_user;
535     inner->module = frame->module;  /* This gets fixed up in evaluate_rule(), below. */
536     inner->procedure = parse;
537     /* Special-case LOL of length 1 where the first list is totally empty.
538        This is created when calling functions with no parameters, due to
539        the way jam grammar is written. This is OK when one jam function
540        calls another, but really not good when Jam function calls Python.  */
541     if ( parse->left->left == NULL && parse->left->right->func == compile_null)
542         ;
543     else
544         for ( p = parse->left; p; p = p->left )
545             lol_add( inner->args, parse_evaluate( p->right, frame ) );
546
547     /* And invoke the rule. */
548     result = evaluate_rule( parse->string, inner );
549     frame_free( inner );
550     return result;
551 }
552
553
554 static void argument_error( char * message, RULE * rule, FRAME * frame, LIST* arg )
555 {
556     LOL * actual = frame->args;
557     assert( frame->procedure != 0 );
558     backtrace_line( frame->prev );
559     printf( "*** argument error\n* rule %s ( ", frame->rulename );
560     lol_print( rule->arguments->data );
561     printf( " )\n* called with: ( " );
562     lol_print( actual );
563     printf( " )\n* %s %s\n", message, arg ? arg->string : "" );
564     print_source_line( rule->procedure );
565     printf( "see definition of rule '%s' being called\n", rule->name );
566     backtrace( frame->prev );
567     exit( 1 );
568 }
569
570
571 /* Define delimiters for type check elements in argument lists (and return type
572  * specifications, eventually).
573  */
574 # define TYPE_OPEN_DELIM '['
575 # define TYPE_CLOSE_DELIM ']'
576
577 /*
578  * is_type_name() - true iff the given string represents a type check
579  * specification.
580  */
581
582 static int is_type_name( char * s )
583 {
584     return ( s[ 0 ] == TYPE_OPEN_DELIM ) &&
585         ( s[ strlen( s ) - 1 ] == TYPE_CLOSE_DELIM );
586 }
587
588
589 /*
590  * arg_modifier - if the next element of formal is a single character, return
591  * that; return 0 otherwise. Used to extract "*+?" modifiers * from argument
592  * lists.
593  */
594
595 static char arg_modifier( LIST * formal )
596 {
597     if ( formal->next )
598     {
599         char * next = formal->next->string;
600         if ( next && ( next[ 0 ] != 0 ) && ( next[ 1 ] == 0 ) )
601             return next[ 0 ];
602     }
603     return 0;
604 }
605
606
607 /*
608  * type_check() - checks that each element of values satisfies the requirements
609  * of type_name.
610  *
611  *      caller   - the frame of the rule calling the rule whose arguments are
612  *                 being checked
613  *
614  *      called   - the rule being called
615  *
616  *      arg_name - a list element containing the name of the argument being
617  *                 checked
618  */
619
620 static void type_check
621 (
622     char  * type_name,
623     LIST  * values,
624     FRAME * caller,
625     RULE  * called,
626     LIST  * arg_name
627 )
628 {
629     static module_t * typecheck = 0;
630
631     /* If nothing to check, bail now. */
632     if ( !values || !type_name )
633         return;
634
635     if ( !typecheck )
636         typecheck = bindmodule( ".typecheck" );
637
638     /* If the checking rule can not be found, also bail. */
639     {
640         RULE checker_, *checker = &checker_;
641
642         checker->name = type_name;
643         if ( !typecheck->rules || !hashcheck( typecheck->rules, (HASHDATA * *)&checker ) )
644             return;
645     }
646
647     exit_module( caller->module );
648
649     while ( values != 0 )
650     {
651         LIST *error;
652         FRAME frame[1];
653         frame_init( frame );
654         frame->module = typecheck;
655         frame->prev = caller;
656         frame->prev_user = caller->module->user_module ? caller : caller->prev_user;
657
658         enter_module( typecheck );
659         /* Prepare the argument list */
660         lol_add( frame->args, list_new( L0, values->string ) );
661         error = evaluate_rule( type_name, frame );
662
663         exit_module( typecheck );
664
665         if ( error )
666             argument_error( error->string, called, caller, arg_name );
667
668         frame_free( frame );
669         values = values->next;
670     }
671
672     enter_module( caller->module );
673 }
674
675 /*
676  * collect_arguments() - local argument checking and collection
677  */
678 static SETTINGS *
679 collect_arguments( RULE* rule, FRAME* frame )
680 {
681     SETTINGS *locals = 0;
682
683     LOL * all_actual = frame->args;
684     LOL * all_formal = rule->arguments ? rule->arguments->data : 0;
685     if ( all_formal ) /* Nothing to set; nothing to check */
686     {
687         int max = all_formal->count > all_actual->count
688             ? all_formal->count
689             : all_actual->count;
690
691         int n;
692         for ( n = 0; n < max ; ++n )
693         {
694             LIST *actual = lol_get( all_actual, n );
695             char *type_name = 0;
696
697             LIST *formal;
698             for ( formal = lol_get( all_formal, n ); formal; formal = formal->next )
699             {
700                 char* name = formal->string;
701
702                 if ( is_type_name(name) )
703                 {
704                     if ( type_name )
705                         argument_error( "missing argument name before type name:", rule, frame, formal );
706
707                     if ( !formal->next )
708                         argument_error( "missing argument name after type name:", rule, frame, formal );
709
710                     type_name = formal->string;
711                 }
712                 else
713                 {
714                     LIST* value = 0;
715                     char modifier;
716                     LIST* arg_name = formal; /* hold the argument name for type checking */
717                     int multiple = 0;
718
719                     /* Stop now if a variable number of arguments are specified */
720                     if ( name[0] == '*' && name[1] == 0 )
721                         return locals;
722
723                     modifier = arg_modifier( formal );
724
725                     if ( !actual && modifier != '?' && modifier != '*' )
726                         argument_error( "missing argument", rule, frame, formal );
727
728                     switch ( modifier )
729                     {
730                     case '+':
731                     case '*':
732                         value = list_copy( 0, actual );
733                         multiple = 1;
734                         actual = 0;
735                         /* skip an extra element for the modifier */
736                         formal = formal->next;
737                         break;
738                     case '?':
739                         /* skip an extra element for the modifier */
740                         formal = formal->next;
741                         /* fall through */
742                     default:
743                         if ( actual ) /* in case actual is missing */
744                         {
745                             value = list_new( 0, actual->string );
746                             actual = actual->next;
747                         }
748                     }
749
750                     locals = addsettings(locals, VAR_SET, name, value);
751                     locals->multiple = multiple;
752                     type_check( type_name, value, frame, rule, arg_name );
753                     type_name = 0;
754                 }
755             }
756
757             if ( actual )
758             {
759                 argument_error( "extra argument", rule, frame, actual );
760             }
761         }
762     }
763     return locals;
764 }
765
766 RULE *
767 enter_rule( char *rulename, module_t *target_module );
768
769 #ifdef HAVE_PYTHON
770
771 static int python_instance_number = 0;
772
773
774 /* Given a Python object, return a string to use in Jam
775    code instead of said object.
776    If the object is string, use the string value
777    If the object implemenets __jam_repr__ method, use that.
778    Otherwise return 0.
779
780    The result value is newstr-ed.  */
781 char *python_to_string(PyObject* value)
782 {
783     if (PyString_Check(value))
784     {
785         return newstr(PyString_AsString(value));
786     }
787     else
788     {
789         /* See if this is an instance that defines special __jam_repr__
790            method. */
791         if (PyInstance_Check(value)
792             && PyObject_HasAttrString(value, "__jam_repr__"))
793         {
794             PyObject* repr = PyObject_GetAttrString(value, "__jam_repr__");
795             if (repr)
796             {
797                 PyObject* arguments2 = PyTuple_New(0);
798                 PyObject* value2 = PyObject_Call(repr, arguments2, 0);
799                 Py_DECREF(repr);
800                 Py_DECREF(arguments2);
801                 if (PyString_Check(value2))
802                 {
803                     return newstr(PyString_AsString(value2));
804                 }
805                 Py_DECREF(value2);
806             }
807         }
808         return 0;
809     }
810 }
811
812 static LIST*
813 call_python_function(RULE* r, FRAME* frame)
814 {
815     LIST * result = 0;
816     PyObject * arguments = 0;
817     PyObject * kw = NULL;
818     int i ;
819     PyObject * py_result;
820
821     if (r->arguments)
822     {
823         SETTINGS * args;
824
825         arguments = PyTuple_New(0);
826         kw = PyDict_New();
827
828         for (args = collect_arguments(r, frame); args; args = args->next)
829         {
830             PyObject *key = PyString_FromString(args->symbol);
831             PyObject *value = 0;
832             if (args->multiple)
833                 value = list_to_python(args->value);
834             else {
835                 if (args->value)
836                     value = PyString_FromString(args->value->string);
837             }
838
839             if (value)
840                 PyDict_SetItem(kw, key, value);
841             Py_DECREF(key);
842             Py_XDECREF(value);
843         }
844     }
845     else
846     {
847         arguments = PyTuple_New( frame->args->count );
848         for ( i = 0; i < frame->args->count; ++i )
849         {
850             PyObject * arg = PyList_New(0);
851             LIST* l = lol_get( frame->args, i);
852             
853             for ( ; l; l = l->next )
854             {
855                 PyObject * v = PyString_FromString(l->string);
856                 PyList_Append( arg, v );
857                 Py_DECREF(v);
858             }
859             /* Steals reference to 'arg' */
860             PyTuple_SetItem( arguments, i, arg );
861         }
862     }
863
864     frame_before_python_call = frame;
865     py_result = PyObject_Call( r->python_function, arguments, kw );
866     Py_DECREF(arguments);
867     Py_XDECREF(kw);
868     if ( py_result != NULL )
869     {
870         if ( PyList_Check( py_result ) )
871         {
872             int size = PyList_Size( py_result );
873             int i;
874             for ( i = 0; i < size; ++i )
875             {
876                 PyObject * item = PyList_GetItem( py_result, i );
877                 char *s = python_to_string (item);
878                 if (!s) {
879                     fprintf( stderr, "Non-string object returned by Python call.\n" );
880                 } else {
881                     result = list_new (result, s);
882                 }
883             }
884         }
885         else if ( py_result == Py_None )
886         {
887             result = L0;
888         }
889         else 
890         {
891             char *s = python_to_string(py_result);
892             if (s)
893                 result = list_new(0, s);
894             else 
895                 /* We have tried all we could.  Return empty list. There are
896                    cases, e.g.  feature.feature function that should return
897                    value for the benefit of Python code and which also can be
898                    called by Jam code, where no sensible value can be
899                    returned. We cannot even emit a warning, since there will
900                    be a pile of them.  */                
901                 result = L0;                    
902         }
903
904         Py_DECREF( py_result );
905     }
906     else
907     {
908         PyErr_Print();
909         fprintf(stderr,"Call failed\n");
910     }
911
912     return result;
913 }
914
915
916 module_t * python_module()
917 {
918     static module_t * python = 0;
919     if ( !python )
920         python = bindmodule("__python__");
921     return python;
922 }
923
924 #endif
925
926
927 /*
928  * evaluate_rule() - execute a rule invocation.
929  */
930
931 LIST *
932 evaluate_rule(
933     char  * rulename,
934     FRAME * frame )
935 {
936     LIST          * result = L0;
937     RULE          * rule;
938     profile_frame   prof[1];
939     module_t      * prev_module = frame->module;
940
941     LIST * l;
942     {
943         LOL arg_context_, * arg_context = &arg_context_;
944         if ( !frame->prev )
945             lol_init(arg_context);
946         else
947             arg_context = frame->prev->args;
948         l = var_expand( L0, rulename, rulename+strlen(rulename), arg_context, 0 );
949     }
950
951     if ( !l )
952     {
953         backtrace_line( frame->prev );
954         printf( "warning: rulename %s expands to empty string\n", rulename );
955         backtrace( frame->prev );
956         return result;
957     }
958
959     rulename = l->string;
960     rule = bindrule( l->string, frame->module );
961
962 #ifdef HAVE_PYTHON
963     if ( rule->python_function )
964     {
965         /* The below messing with modules is due to the way modules are
966          * implemented in Jam. Suppose we are in module M1 now. The global
967          * variable map actually holds 'M1' variables, and M1->variables hold
968          * global variables.
969          *
970          * If we call Python right away, Python calls back Jam and then Jam
971          * does 'module M1 { }' then Jam will try to swap the current global
972          * variables with M1->variables. The result will be that global
973          * variables map will hold global variables, and any variable settings
974          * we do will go to the global module, not M1.
975          *
976          * By restoring basic state, where the global variable map holds global
977          * variable, we make sure any future 'module M1' entry will work OK.
978          */
979
980         LIST * result;
981         module_t * m = python_module();
982
983         frame->module = m;
984
985         exit_module( prev_module );
986         enter_module( m );
987
988         result = call_python_function( rule, frame );
989
990         exit_module( m );
991         enter_module ( prev_module );
992
993         return result;
994     }
995 #endif
996
997     /* Drop the rule name. */
998     l = list_pop_front( l );
999
1000     /* Tack the rest of the expansion onto the front of the first argument. */
1001     frame->args->list[0] = list_append( l, lol_get( frame->args, 0 ) );
1002
1003     if ( DEBUG_COMPILE )
1004     {
1005         /* Try hard to indicate in which module the rule is going to execute. */
1006         if ( rule->module != frame->module
1007              && rule->procedure != 0 && strcmp( rulename, rule->procedure->rulename ) )
1008         {
1009             char buf[256] = "";
1010             strncat( buf, rule->module->name, sizeof( buf ) - 1 );
1011             strncat( buf, rule->name, sizeof( buf ) - 1 );
1012             debug_compile( 1, buf, frame );
1013         }
1014         else
1015         {
1016             debug_compile( 1, rulename, frame );
1017         }
1018
1019         lol_print( frame->args );
1020         printf( "\n" );
1021     }
1022
1023     if ( rule->procedure && rule->module != prev_module )
1024     {
1025         /* Propagate current module to nested rule invocations. */
1026         frame->module = rule->module;
1027
1028         /* Swap variables. */
1029         exit_module( prev_module );
1030         enter_module( rule->module );
1031     }
1032
1033     /* Record current rule name in frame. */
1034     if ( rule->procedure )
1035     {
1036         frame->rulename = rulename;
1037         /* And enter record profile info. */
1038         if ( DEBUG_PROFILE )
1039             profile_enter( rule->procedure->rulename, prof );
1040     }
1041
1042     /* Check traditional targets $(<) and sources $(>). */
1043     if ( !rule->actions && !rule->procedure )
1044     {
1045         backtrace_line( frame->prev );
1046         printf( "rule %s unknown in module %s\n", rule->name, frame->module->name );
1047         backtrace( frame->prev );
1048         exit( 1 );
1049     }
1050
1051     /* If this rule will be executed for updating the targets then construct the
1052      * action for make().
1053      */
1054     if ( rule->actions )
1055     {
1056         TARGETS * t;
1057         ACTION  * action;
1058
1059         /* The action is associated with this instance of this rule. */
1060         action = (ACTION *)BJAM_MALLOC( sizeof( ACTION ) );
1061         memset( (char *)action, '\0', sizeof( *action ) );
1062
1063         action->rule = rule;
1064         action->targets = targetlist( (TARGETS *)0, lol_get( frame->args, 0 ) );
1065         action->sources = targetlist( (TARGETS *)0, lol_get( frame->args, 1 ) );
1066
1067         /* If we have a group of targets all being built using the same action
1068          * then we must not allow any of them to be used as sources unless they
1069          * had all already been built in the first place or their joined action
1070          * has had a chance to finish its work and build all of them anew.
1071          *
1072          * Without this it might be possible, in case of a multi-process build,
1073          * for their action, triggered by buiding one of the targets, to still
1074          * be running when another target in the group reports as done in order
1075          * to avoid triggering the same action again and gets used prematurely.
1076          *
1077          * As a quick-fix to achieve this effect we make all the targets list
1078          * each other as 'included targets'. More precisely, we mark the first
1079          * listed target as including all the other targets in the list and vice
1080          * versa. This makes anyone depending on any of those targets implicitly
1081          * depend on all of them, thus making sure none of those targets can be
1082          * used as sources until all of them have been built. Note that direct
1083          * dependencies could not have been used due to the 'circular
1084          * dependency' issue.
1085          *
1086          * TODO: Although the current implementation solves the problem of one
1087          * of the targets getting used before its action completes its work it
1088          * also forces the action to run whenever any of the targets in the
1089          * group is not up to date even though some of them might not actually
1090          * be used by the targets being built. We should see how we can
1091          * correctly recognize such cases and use that to avoid running the
1092          * action if possible and not rebuild targets not actually depending on
1093          * targets that are not up to date.
1094          *
1095          * TODO: Using the 'include' feature might have side-effects due to
1096          * interaction with the actual 'inclusion scanning' system. This should
1097          * be checked.
1098          */
1099         if ( action->targets )
1100         {
1101             TARGET * t0 = action->targets->target;
1102             for ( t = action->targets->next; t; t = t->next )
1103             {
1104                 target_include( t->target, t0 );
1105                 target_include( t0, t->target );
1106             }
1107         }
1108
1109         /* Append this action to the actions of each target. */
1110         for ( t = action->targets; t; t = t->next )
1111             t->target->actions = actionlist( t->target->actions, action );
1112     }
1113
1114     /* Now recursively compile any parse tree associated with this rule.
1115      * parse_refer()/parse_free() call pair added to ensure rule not freed
1116      * during use.
1117      */
1118     if ( rule->procedure )
1119     {
1120         SETTINGS * local_args = collect_arguments( rule, frame );
1121         PARSE * parse = rule->procedure;
1122         parse_refer( parse );
1123
1124         pushsettings( local_args );
1125         result = parse_evaluate( parse, frame );
1126         popsettings( local_args );
1127         freesettings( local_args );
1128
1129         parse_free( parse );
1130     }
1131
1132     if ( frame->module != prev_module )
1133     {
1134         exit_module( frame->module );
1135         enter_module( prev_module );
1136     }
1137
1138     if ( DEBUG_PROFILE && rule->procedure )
1139         profile_exit( prof );
1140
1141     if ( DEBUG_COMPILE )
1142         debug_compile( -1, 0, frame);
1143
1144     return result;
1145 }
1146
1147
1148 /*
1149  * Call the given rule with the specified parameters. The parameters should be
1150  * of type LIST* and end with a NULL pointer. This differs from 'evaluate_rule'
1151  * in that frame for the called rule is prepared inside 'call_rule'.
1152  *
1153  * This function is useful when a builtin rule (in C) wants to call another rule
1154  * which might be implemented in Jam.
1155  */
1156
1157 LIST * call_rule( char * rulename, FRAME * caller_frame, ... )
1158 {
1159     va_list va;
1160     LIST * result;
1161
1162     FRAME       inner[1];
1163     frame_init( inner );
1164     inner->prev = caller_frame;
1165     inner->prev_user = caller_frame->module->user_module ?
1166         caller_frame : caller_frame->prev_user;
1167     inner->module = caller_frame->module;
1168     inner->procedure = 0;
1169
1170     va_start( va, caller_frame );
1171     for ( ; ; )
1172     {
1173         LIST * l = va_arg( va, LIST* );
1174         if ( !l )
1175             break;
1176         lol_add( inner->args, l );
1177     }
1178     va_end( va );
1179
1180     result = evaluate_rule( rulename, inner );
1181
1182     frame_free( inner );
1183
1184     return result;
1185 }
1186
1187
1188 /*
1189  * compile_rules() - compile a chain of rules
1190  *
1191  *  parse->left single rule
1192  *  parse->right    more compile_rules() by right-recursion
1193  */
1194
1195 LIST * compile_rules( PARSE * parse, FRAME * frame )
1196 {
1197     /* Ignore result from first statement; return the 2nd. */
1198     /* Optimize recursion on the right by looping. */
1199     do list_free( parse_evaluate( parse->left, frame ) );
1200     while ( ( parse = parse->right )->func == compile_rules );
1201     return parse_evaluate( parse, frame );
1202 }
1203
1204
1205 /*
1206  * assign_var_mode() - convert ASSIGN_XXX compilation flag into corresponding
1207  *                     VAR_XXX variable set flag.
1208  */
1209
1210 static int assign_var_mode( int parsenum, char const * * tracetext )
1211 {
1212     char const * trace;
1213     int          setflag;
1214     switch ( parsenum )
1215     {
1216         case ASSIGN_SET    : setflag = VAR_SET    ; trace = "=" ; break;
1217         case ASSIGN_APPEND : setflag = VAR_APPEND ; trace = "+="; break;
1218         case ASSIGN_DEFAULT: setflag = VAR_DEFAULT; trace = "?="; break;
1219         default:             setflag = VAR_SET    ; trace = ""  ; break;
1220     }
1221     if ( tracetext )
1222         *tracetext = trace ;
1223     return setflag;
1224 }
1225
1226 /*
1227  * compile_set() - compile the "set variable" statement
1228  *
1229  *  parse->left variable names
1230  *  parse->right    variable values
1231  *  parse->num  ASSIGN_SET/APPEND/DEFAULT
1232  */
1233
1234 LIST * compile_set( PARSE * parse, FRAME * frame )
1235 {
1236     LIST       * nt = parse_evaluate( parse->left, frame );
1237     LIST       * ns = parse_evaluate( parse->right, frame );
1238     LIST       * l;
1239     char const * trace;
1240     int          setflag = assign_var_mode( parse->num, &trace );
1241
1242     if ( DEBUG_COMPILE )
1243     {
1244         debug_compile( 0, "set", frame );
1245         list_print( nt );
1246         printf( " %s ", trace );
1247         list_print( ns );
1248         printf( "\n" );
1249     }
1250
1251     /* Call var_set to set variable. var_set keeps ns, so need to copy it. */
1252     for ( l = nt; l; l = list_next( l ) )
1253         var_set( l->string, list_copy( L0, ns ), setflag );
1254     list_free( nt );
1255     return ns;
1256 }
1257
1258
1259 /*
1260  * compile_setcomp() - support for `rule` - save parse tree.
1261  *
1262  *  parse->string  rule name
1263  *  parse->left    rules for rule
1264  *  parse->right   optional list-of-lists describing arguments
1265  */
1266
1267 LIST * compile_setcomp( PARSE * parse, FRAME * frame )
1268 {
1269     argument_list * arg_list = 0;
1270
1271     /* Create new LOL describing argument requirements if supplied. */
1272     if ( parse->right )
1273     {
1274         PARSE * p;
1275         arg_list = args_new();
1276         for ( p = parse->right; p; p = p->left )
1277             lol_add( arg_list->data, parse_evaluate( p->right, frame ) );
1278     }
1279
1280     new_rule_body( frame->module, parse->string, arg_list, parse->left, !parse->num );
1281     return L0;
1282 }
1283
1284
1285 /*
1286  * compile_setexec() - support for `actions` - save execution string.
1287  *
1288  *  parse->string   rule name
1289  *  parse->string1  OS command string
1290  *  parse->num      flags
1291  *  parse->left     `bind` variables
1292  *
1293  * Note that the parse flags (as defined in compile.h) are transferred directly
1294  * to the rule flags (as defined in rules.h).
1295  */
1296
1297 LIST * compile_setexec( PARSE * parse, FRAME * frame )
1298 {
1299     LIST * bindlist = parse_evaluate( parse->left, frame );
1300     new_rule_actions( frame->module, parse->string, parse->string1, bindlist, parse->num );
1301     return L0;
1302 }
1303
1304
1305 /*
1306  * compile_settings() - compile the "on =" (set variable on exec) statement.
1307  *
1308  *  parse->left   variable names
1309  *  parse->right  target name
1310  *  parse->third  variable value
1311  *  parse->num    ASSIGN_SET/APPEND
1312  */
1313
1314 LIST * compile_settings( PARSE * parse, FRAME * frame )
1315 {
1316     LIST       * nt = parse_evaluate( parse->left, frame );
1317     LIST       * ns = parse_evaluate( parse->third, frame );
1318     LIST       * targets = parse_evaluate( parse->right, frame );
1319     LIST       * ts;
1320     char const * trace;
1321     int          setflag = assign_var_mode( parse->num, &trace );
1322
1323     if ( DEBUG_COMPILE )
1324     {
1325         debug_compile( 0, "set", frame );
1326         list_print( nt );
1327         printf( " on " );
1328         list_print( targets );
1329         printf( " %s ", trace );
1330         list_print( ns );
1331         printf( "\n" );
1332     }
1333
1334     /* Call addsettings() to save variable setting. addsettings() keeps ns, so
1335      * need to copy it. Pass append flag to addsettings().
1336      */
1337     for ( ts = targets; ts; ts = list_next( ts ) )
1338     {
1339         TARGET * t = bindtarget( ts->string );
1340         LIST   * l;
1341
1342         for ( l = nt; l; l = list_next( l ) )
1343         t->settings = addsettings( t->settings, setflag, l->string,
1344             list_copy( (LIST *)0, ns ) );
1345     }
1346
1347     list_free( nt );
1348     list_free( targets );
1349     return ns;
1350 }
1351
1352
1353 /*
1354  * compile_switch() - compile 'switch' rule.
1355  *
1356  *  parse->left   switch value (only 1st used)
1357  *  parse->right  cases
1358  *
1359  *  cases->left   1st case
1360  *  cases->right  next cases
1361  *
1362  *  case->string  argument to match
1363  *  case->left    parse tree to execute
1364  */
1365
1366 LIST * compile_switch( PARSE * parse, FRAME * frame )
1367 {
1368     LIST * nt = parse_evaluate( parse->left, frame );
1369     LIST * result = 0;
1370
1371     if ( DEBUG_COMPILE )
1372     {
1373         debug_compile( 0, "switch", frame );
1374         list_print( nt );
1375         printf( "\n" );
1376     }
1377
1378     /* Step through cases. */
1379     for ( parse = parse->right; parse; parse = parse->right )
1380     {
1381         if ( !glob( parse->left->string, nt ? nt->string : "" ) )
1382         {
1383             /* Get & exec parse tree for this case. */
1384             parse = parse->left->left;
1385             result = parse_evaluate( parse, frame );
1386             break;
1387         }
1388     }
1389
1390     list_free( nt );
1391     return result;
1392 }
1393
1394
1395 /*
1396  * debug_compile() - printf with indent to show rule expansion.
1397  */
1398
1399 static void debug_compile( int which, char * s, FRAME * frame )
1400 {
1401     static int level = 0;
1402     static char indent[36] = ">>>>|>>>>|>>>>|>>>>|>>>>|>>>>|>>>>|";
1403
1404     if ( which >= 0 )
1405     {
1406         int i;
1407
1408         print_source_line( frame->procedure );
1409
1410         i = ( level + 1 ) * 2;
1411         while ( i > 35 )
1412         {
1413             fputs( indent, stdout );
1414             i -= 35;
1415         }
1416
1417         printf( "%*.*s ", i, i, indent );
1418     }
1419
1420     if ( s )
1421         printf( "%s ", s );
1422
1423     level += which;
1424 }