File: Process.py

package info (click to toggle)
aap 1.072-1.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 4,976 kB
  • ctags: 2,160
  • sloc: python: 15,113; makefile: 62; sh: 13
file content (1185 lines) | stat: -rw-r--r-- 44,142 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# Part of the A-A-P recipe executive: Parse and execute recipe commands

# Copyright (C) 2002-2003 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

import string
import sys
import traceback
from cStringIO import StringIO

from Util import *
from Work import setrpstack
from Error import *
from RecPos import rpcopy
import Global

# ":" commands that only work at the toplevel
aap_cmd_toplevel = [
                "child",
                "clearrules",
                "delrule",
                "dll",
                "import",
                "lib",
                "ltlib",
                "produce",
                "program",
                "recipe",
                "route",
                "rule",
                "toolsearch",
                "totype",
                "variant",
                ]

# All possible names of ":" commands in a recipe, including toplevel-only ones.
aap_cmd_names = [
                "action",
                "add",
                "addall",
                "asroot",
                "assertpkg",
                "attr",
                "attribute",
                "buildcheck",
                "cat",
                "cd",
                "changed",
                "chdir",
                "checkin",
                "checkinall",
                "checkout",
                "checkoutall",
                "checksum",
                "chmod",
                "commit",
                "commitall",
                "conf",
                "copy",
                "del",
                "deldir",
                "delete",
                "do",
                "error",
                "eval",
                "execute",
                "exit",
                "fetch",
                "fetchall",
                "filetype",
                "finish",
                "include",
                "installpkg",
                "log",
                "mkdir",
                "mkdownload",
                "move",
                "pass",
                "popdir",
                "print",
                "progsearch",
                "proxy",
                "publish",
                "publishall",
                "pushdir",
                "quit",
                "remove",
                "removeall",
                "reviseall",
                "scope",
                "start",
                "symlink",
                "sys",
                "sysdepend",
                "syseval",
                "syspath",
                "system",
                "tag",
                "tagall",
                "touch",
                "tree",
                "unlock",
                "unlockall",
                "update",
                "usetool",
                "verscont",
                ] + aap_cmd_toplevel

# marker for recipe line number in Python script
line_marker = '#@recipe='
line_marker_len = len(line_marker)


def assert_scope_name(rpstack, name):
    """Check if "name" is a valid scope name.
       If it isn't, throw a user exception."""
    for c in name:
        if not scopechar(c):
            recipe_error(rpstack, _("Invalid character in scope name"))


def assert_var_name(rpstack, name):
    """Check if "name" is a valid variable name.
       If it isn't, throw a user exception."""
    for c in name:
        if not varchar(c):
            recipe_error(rpstack, _("Invalid character in variable name"))


def get_var_name(fp):
    """Get the name of a variable from the current position at "fp" and
    get the index of the next non-white after it.  Returns an empty string if
    there is no valid variable name."""
    idx = fp.idx
    while idx < fp.line_len and varchar(fp.line[idx]):
        idx = idx + 1
    # Exclude a trailing dot, so that ":print did $target." works.
    if idx > fp.idx and fp.line[idx - 1] == '.':
        idx = idx - 1
    return fp.line[fp.idx:idx], skip_white(fp.line, idx)


class ArgItem:
    """Object used as smallest part in the arglist."""
    def __init__(self, isexpr, str):
        self.isexpr = isexpr        # 0 for string, 1 for Python expression
        self.str = str              # the string itself


def getarg(fp, stop):
    """Get an argument starting at fp.line[fp.idx] and ending at a character in
       stop[].
       Quotes are used to include stop characters in the argument.
       Backticks are handled here.  `` is reduced to a single `.  A Python
       expression `python` is translated to '" + expr2str(python) + "'.
       Ignore $(`).
       Returns the resulting string and fp.idx is updated to the character
       after the argument (the stop character or past the end of line).
       """
    inquote = ''                        # quote we're inside of
    inbraces = 0                        # inside {} count

    # String concatenation is slow.  Create a list and append parts of the
    # result as items.  They are concatenated all at once at the end.
    l = []                            # argument collected so far

    while 1:
        if fp.idx >= fp.line_len:       # end of line
            break

        # Python `expression`?
        if fp.line[fp.idx] == '`':
            # `` isn't the start of an expression, reduce it to a single `.
            if fp.idx + 1 < fp.line_len and fp.line[fp.idx + 1] == '`':
                l.append('`')
                fp.idx = fp.idx + 2
                continue
            # Append the Python expression.
            l.append('" + expr2str(' + get_py_expr(fp) + ') + "')
            continue

        # Copy $(x) verbatim.
        if (fp.line[fp.idx] == '$'
                and fp.idx + 4 <= fp.line_len
                and fp.line[fp.idx + 1] == '('
                and fp.line[fp.idx + 3] == ')'):
            l.append(fp.line[fp.idx : fp.idx + 4])
            fp.idx = fp.idx + 4
            continue

        # End of quoted string?
        if inquote:
            if fp.line[fp.idx] == inquote:
                inquote = ''

        # Start of quoted string?
        elif fp.line[fp.idx] == '"' or fp.line[fp.idx] == "'":
            inquote = fp.line[fp.idx]

        else:
            # start/end of {}?
            if fp.line[fp.idx] == '{':
                inbraces = inbraces + 1
            elif fp.line[fp.idx] == '}':
                inbraces = inbraces - 1
                if inbraces < 0:
                    # TODO: recipe_error(fp.rpstack, _("Unmatched }"))
                    inbraces = 0

            # Stop character found?
            # A ':' must be followed by white space to be recongized.
            # A '=' must not be inside {}.
            if fp.line[fp.idx] in stop \
                    and (fp.line[fp.idx] != ':'
                            or fp.idx + 1 == fp.line_len
                            or fp.line[fp.idx + 1] == ' '
                            or fp.line[fp.idx + 1] == '\t') \
                    and (fp.line[fp.idx] != '=' or inbraces == 0):
                break

        # Need to escape backslash and double quote.
        c = fp.line[fp.idx]
        if c == '"' or c == '\\':
            l.append('\\' + c)
        else:
            l.append(c)
        fp.idx = fp.idx + 1

        # Skip over $$ and $#.
        if (c == '$' and fp.idx < fp.line_len
                       and (fp.line[fp.idx] == '$' or fp.line[fp.idx] == '#')):
            l.append(fp.line[fp.idx])
            fp.idx = fp.idx + 1

    # Turn the list into a single string.
    res = list2string(l)

    # Remove trailing white space.
    e = len(res)
    while e > 0 and (res[e - 1] == ' ' or res[e - 1] == '\t'):
        e = e - 1

    return res[:e]


def get_func_args(fp, indent):
    """Get the arguments for an aap_ function or assignment from the recipe
       line(s).
       Stop at a line with an indent of "indent" or less.

       Input lines:   cmdname arg ` <python-expr> `arg
                                arg
       Result:        "arg " + expr2str(<python-expr>) + "arg arg"

       Return the argument string, advance fp to the following line."""

    res = ''
    fp.idx = skip_white(fp.line, fp.idx)

    while 1:
        if fp.idx >= fp.line_len or fp.line[fp.idx] == '#':
            # Read the next line
            fp.nextline()
            if fp.line is None:
                break   # end of file
            fp.idx = skip_white(fp.line, 0)
            if get_indent(fp.line) > indent:
                continue
            # A line with less indent finishes the list of arguments
            break

        # Get the argument, stop at a comment, handle python expression.
        # A line break is changed into a space.
        # When a line ends in "$br" insert a line break.  But not when it ends
        # in "$$br".  But do it for "$$$br".  Etc.
        if res:
            if len(res) >= 3 and res[-3:] == "$br":
                i = len(res) - 4
                escaped = 0
                while i >= 0 and res[i] == '$':
                    i = i - 1
                    escaped = not escaped
                if escaped:
                    res = res + ' '
                else:
                    res = res[:-3] + '\\n'
            else:
                res = res + ' '
        res = res + getarg(fp, "#")

    return '"' + res + '"'


def esc_quote(s):
    """Escape double quotes and backslash with a backslash."""
    return string.replace(string.replace(s, '\\', '\\\\'), '"', '\\"')


def get_commands(fp, indent):
    """Read command lines for a dependency or a rule.
       Stop when the indent is at or below "indent".
       Separate the part at the start with more indent than the smallest indent
       in the block (this is considered continuation of the first line).
       Returns the head and the string of commands, each line ending in '\n'."""
    # First get all lines, until the indent drops to "indent" or lower.
    # Also remember the line markers, empty lines may be skipped thus we can't
    # compute the line numbers from the index.
    markers = []
    lines = []
    min_indent = 99999
    min_indent_idx = 0      # first line with the smallest indent, this is
                            # where the build commands start.
    while 1:
        if fp.line is None:
            break           # end of commands reached
        idt = get_indent(fp.line)
        if idt <= indent:
            break           # end of commands reached
        if idt < min_indent:
            min_indent = idt
            min_indent_idx = len(lines)
        markers.append(' ' + ("%s%d" % (line_marker, fp.rpstack[-1].line_nr)))
        lines.append(fp.line)
        fp.nextline()

    # Make the string for the head (no line breaks).
    # Need to use a ParsePos here, so that getarg() can be called.  It
    # handles Python expressions that may continue over a line break.
    head = ''
    l = []
    for i in range(0, min_indent_idx):
        l.append(lines[i])
        l.append('\n')
    if l:
        from ParsePos import ParsePos
        pp = ParsePos(fp.rpstack, string = list2string(l))
        pp.nextline()
        while 1:
            if pp.line is None:
                break
            pp.index = skip_white(pp.line, 0)
            head = head + ' ' + getarg(pp, "#")
            pp.nextline()

    # Make the string for the commands (with markers and line breaks).
    # Use the clumsy but fast method to concatenate strings, because long
    # strings are used here.
    str = StringIO()
    for i in range(min_indent_idx, len(lines)):
        str.write(markers[i])
        str.write('\n')
        str.write(lines[i])
        str.write('\n')

    return head, '"""' + esc_quote(str.getvalue()) + '"""'


def get_py_expr(fp):
    """Get a Python expression from ` to matching `.
       Reduce `` to ` and $(`) to `.
       fp.idx points to the ` and is advanced to after the matching `.
       Returns the expression excluding the ` before and after."""
    # Remember the RecPos where the first ` was found; need to make a copy,
    # because fp.nextline() will change it.
    rpstack = rpcopy(fp.rpstack, fp.rpstack[-1].line_nr)

    res = ''
    fp.idx = fp.idx + 1
    while 1:
        if fp.idx >= fp.line_len:
            # Python expression continues in the next line.
            fp.nextline()
            if fp.line is None:
                recipe_error(rpstack, _("Missing `"))
            res = res + '\n'
        if fp.line[fp.idx] == '`':
            # Either the matching ` or `` that stands for a single `.
            fp.idx = fp.idx + 1
            if fp.idx >= fp.line_len or fp.line[fp.idx] != '`':
                break       # found matching `
            res = res + '`'
        elif (fp.line[fp.idx] == '$'
                and fp.idx + 4 <= fp.line_len
                and fp.line[fp.idx + 1 : fp.idx + 4] == '(`)'):
            res = res + '`'
            fp.idx = fp.idx + 3
        else:
            # Append a character to the Python expression.
            res = res + fp.line[fp.idx]
        fp.idx = fp.idx + 1

    return res


def get_recipe_msg(rpstack):
    # Note: This messages is not translated, so that a parser for the
    # messages isn't confused by various languages.
    if not rpstack:
        return 'in recipe: '
    return 'in recipe "%s" line %d: ' % (rpstack[-1].name, rpstack[-1].line_nr)


def recipe_error(rpstack, msg):
    """Throw an exception for an error in a recipe:
            Error: Unknown command
            in recipe "main.aap" line 88: :foobar asdf
            included from "main.aap" line 33
       When "rpstack" is empty it's not mentioned, useful for errors
       not related to a specific line."""
    e = "Error " + get_recipe_msg(rpstack) + msg + '\n'
    if len(rpstack) > 1:
        for i in range(len(rpstack) - 2, 0, -1):
            e = e + 'included from "%s" line %d\n' \
                                        % (rpstack[i].name, rpstack[i].line_nr)
    e = e[:-1]      # remove trailing \n

    raise UserError, e


def option_error(rpstack, dict, cmd):
    """Give an error message for options in dictionary "dict"."""
    if len(dict.keys()) > 1:
        recipe_error(rpstack, _("Illegal options for %s command: %s")
                                                     % (cmd, str(dict.keys())))
    else:
        recipe_error(rpstack, _("Illegal option for %s command: %s")
                                                       % (cmd, dict.keys()[0]))

def get_line_marker(s, sidx = 0):
    """Check for the line marker comment at string "s".
       Return the line number if found, None otherwise."""
    if s[sidx:sidx + line_marker_len] == line_marker:
        j = sidx + line_marker_len
        try:
            while s[j] in string.digits:
                j = j + 1
        except:
            pass
        return int(s[sidx + line_marker_len:j])
    return None


def get_block_term(fp, cmd):
    """Get the argument used to terminate a block of lines.
       Used for ":python EOF" and "var << EOF"."""
    fp.idx = skip_white(fp.line, fp.idx)
    n = skip_to_white(fp.line, fp.idx)
    if n == fp.idx:
        recipe_error(fp.rpstack, _("Missing item for %s") % cmd)
    term = fp.line[fp.idx:n]
    n = skip_white(fp.line, n)
    if n < fp.line_len and fp.line[n] != '#':
        recipe_error(fp.rpstack, _("Too many arguments for %s") % cmd)
    return term

def get_block_lines(fp, term, indent, indent_sub, cmd):
    """Get the lines for a block of lines followed by terminator "term".
       Stop when "term" is empty and the indent drops below "indent".
       Remove "indent_sub" indent from the lines.
       Used for ":python EOF" and "var << EOF"."""
    lines = ''
    start_line_nr = fp.rpstack[-1].line_nr
    term_len = len(term)
    first_indent = -1

    while 1:
        fp.nextline()
        if fp.line is None:
            if not term:
                break
            fp.rpstack[-1].line_nr = start_line_nr
            recipe_error(fp.rpstack, _("Unterminated %s block") % cmd)

        # Need to know the indent of the first line.
        if first_indent == -1:
            first_indent = get_indent(fp.line)

        if not term:
            # No terminator defined: end when indent is smaller.
            if get_indent(fp.line) <= indent:
                break
        else:
            # Terminator defined: end when it's found.
            n = skip_white(fp.line, 0)
            if n < fp.line_len and fp.line[n:n + term_len] == term:
                n = skip_white(fp.line, n + term_len)
                if n >= fp.line_len or fp.line[n] == "#":
                    fp.nextline()
                    break

        if cmd == ":python":
            # Append the recipe line number, used for error messages.
            lines = lines + ("%s%d\n" % (line_marker, fp.rpstack[-1].line_nr))

            # Remove the indent difference between "indent" and "first_indent".
            keep_indent = indent - indent_sub
        else:
            # Remove the indent by as much as the indent of the first line.
            keep_indent = 0

        # Find the index of the character that has enough indent.
        i = 0
        ind = 0
        while ind + keep_indent < first_indent and i < len(fp.line):
            if fp.line[i] == ' ':
                ind = ind + 1
            elif fp.line[i] == '\t':
                ind = ind + 8 - ind % 8
            else:
                break
            i = i + 1

        # Check that removing blanks upto line[i] result in the right amount of
        # indent.  When there are spaces before a tab it won't be so, also
        # remove the tab.
        if get_indent(fp.line[i:]) > first_indent - keep_indent:
            while i < len(fp.line):
                if fp.line[i] == '\t':
                    ind = ind + 8 - ind % 8
                    i = i + 1
                    break
                if fp.line[i] != ' ':
                    break
                ind = ind + 1
                i = i + 1

        if ind < first_indent - keep_indent:
            recipe_error(fp.rpstack, _("Not enough indent in %s block") % cmd)
        line = (' ' * (ind - first_indent + keep_indent)) + fp.line[i:]
        lines = lines + line + '\n'

    return lines


def script_error(rpstack, recdict, script):
    """Handle an error raised while executing the Python script produced for a
    recipe.  The error is probably in the recipe, try to give a useful error
    message."""
    etype, evalue, tb = sys.exc_info()

    # A SyntaxError is special: it's not the last frame in the traceback but
    # only in the "etype" and "evalue".  When there is a filename it must have
    # been an internal error, otherwise it's an error in the converted recipe.
    py_line_nr = -1
    if etype is SyntaxError:
        try:
            msg, (filename, py_line_nr, offset, line) = evalue
            if not filename is None:
                py_line_nr = -2
        except:
            pass

    if py_line_nr < 0:
        # Find the line number in the last traceback frame.
        while tb.tb_next:
            tb = tb.tb_next
        fname = tb.tb_frame.f_code.co_filename
        if py_line_nr == -2 or (fname and not fname == "<string>"):
            # If there is a filename, it's not an error in the script.
            from Main import error_msg
            error_msg(recdict, _("Internal Error"))
            # traceback.print_exc()
            e = sys.exc_info()
            error_msg(recdict,
                     string.join(traceback.format_exception(e[0], e[1], e[2])))
            sys.exit(1)

        py_line_nr = traceback.tb_lineno(tb)

    # Translate the line number in the Python script to the line number
    # in the recipe.
    i = 0
    script_len = len(script)
    rec_line_nr = 1
    while 1:
        if py_line_nr == 1:
            break
        while i < script_len:
            if script[i] == '\n':
                break
            i = i + 1
        i = i + 1
        if i >= script_len:
            break
        n = get_line_marker(script[i:])
        if not n is None:
            rec_line_nr = n
        py_line_nr = py_line_nr - 1

    # Give the exception error with the line number in the recipe.
    recipe_py_error(rpcopy(rpstack, rec_line_nr), '')


def recipe_py_error(rpstack, msg):
    """Turn the list from format_exception_only() into a simple string and pass
    it to recipe_error()."""
    etype, evalue, tb = sys.exc_info()

    lines = traceback.format_exception_only(etype, evalue)

    # For a syntax error remove the "<string>" and line number that the 
    # Python script causes.
    if etype is SyntaxError:
        try:
            emsg, (filename, lineno, offset, line) = evalue
            if filename is None:
                lines[0] = '\n'
        except:
            pass

    str = msg
    for line in lines[:-1]:
        str = str + line + ' '
    str = str + lines[-1]
    recipe_error(rpstack, str)


def Process(fp, recdict, toplevel):
    """
    Read all the lines in ParsePos "fp", convert it into a Python script and
    execute it.
    When "fp.string" is empty, the source is a recipe file, otherwise it is a
    string (commands from a dependency or rule).
    When executing the recipe itself, not build commands or a file included
    from build commands, "toplevel" is True.
    """

    # Need to be able to find the RecPos stack in recdict.
    setrpstack(recdict, fp.rpstack)

    # Ugly: Tell invoked commands whether we are at the toplevel.
    save_at_toplevel = Global.at_toplevel
    Global.at_toplevel = toplevel

    class Variant:
        """Class used to remember nested ":variant" commands in
           variant_stack."""
        def __init__(self, name, indent, line_nr):
            self.name = name
            self.min_indent = indent
            self.line_nr = line_nr
            self.val_indent = 0
            self.had_star = 0       # encountered * item

    #
    # At the start of the loop "fp.line" contains the next line to be
    # processsed.  "fp.rpstack[-1].line_nr" is the number of this line in the
    # recipe.
    #
    script = []             # the resulting script, line by line
    shell_cmd = ""          # shell command collected so far
    shell_cmd_indent = 0    # avoid PyChecker warning
    shell_cmd_line_nr = 0   # avoid PyChecker warning
    variant_stack = []      # nested ":variant" commands
    had_recipe_cmd = 0      # encountered ":recipe" command
    fp.nextline()           # read the first line

    first_indent = 0        # Default, may be set when reading from a string
                            # at the first non-blank non-comment line
    had_first_indent = 0    # Didn't find first non-blank non-comment line yet

    from Commands import shell_cmd_has_force

    while 1:

        # Skip leading white space (unless at end of file).
        if not fp.line is None:
            indent = get_indent(fp.line)
            fp.idx = skip_white(fp.line, 0)
            if (had_first_indent == 0 and fp.idx < fp.line_len
                                                   and fp.line[fp.idx] != '#'):
                if not fp.string and indent > 0:
                    # Common mistake: recipe with indented line.
                    recipe_error(fp.rpstack,
                                       _("First command in recipe has indent"))
                first_indent = indent
                had_first_indent = 1
            indent_string = ' ' * (indent - first_indent)

        # If it's not a shell command and the previous line was, generate the
        # collected shell commands now.
        if shell_cmd:
            if (fp.line is None \
                    or indent < shell_cmd_indent \
                    or fp.line[fp.idx:fp.idx + 4] != ":sys") \
                    or shell_cmd_has_force(fp.rpstack, recdict, shell_cmd) \
                    or shell_cmd_has_force(fp.rpstack, recdict, fp.line[
                                             skip_to_white(fp.line, fp.idx):]):
                script.append((' ' * (shell_cmd_indent - first_indent)) \
                              + ('aap_shell(%d, globals(), "%s")\n'
                                             % (shell_cmd_line_nr, shell_cmd)))
                shell_cmd = ''
        elif not fp.line is None:
            # Append the recipe line number, used for error messages.
            script.append("%s%d\n" % (line_marker, fp.rpstack[-1].line_nr))


        #
        # Handle the end of commands in a variant or the end of a variant
        #
        if len(variant_stack) > 0:
            v = variant_stack[-1]
            v_indent_string = ' ' * (v.min_indent - first_indent)
            if fp.line is None or indent <= v.min_indent:
                # End of the :variant command.
                if v.val_indent == 0:
                    recipe_error(fp.rpstack,
                                  _("Exepected list of values after :variant"))
                if not v.had_star:
                    script.append(v_indent_string + "else:\n")
                    script.append(v_indent_string
                              + "  aap_error(%d, globals(), 'invalid value for %s: %%s' %% %s)\n"
                                  % (v.line_nr, v.name, v.name))

                del variant_stack[-1]
                if len(variant_stack) > 0:
                    continue    # another may end here as well
            else:
                if v.val_indent == 0:
                    v.val_indent = indent
                    first = 1
                else:
                    first = 0
                if indent <= v.val_indent:
                    # Start of a variant value: "debug [ condition ]"
                    # We simply ignore the condition here.
                    if v.had_star:
                        recipe_error(fp.rpstack,
                                          _("Variant item * must be last one"))
                    if fp.idx < fp.line_len and fp.line[fp.idx] == '*':
                        if (fp.idx + 1 < fp.line_len
                                        and not is_white(fp.line[fp.idx + 1])):
                            recipe_error(fp.rpstack, _("* must be by itself"))
                        if not first:
                            script.append(v_indent_string + "else:\n")
                        v.had_star = 1
                    else:
                        val, n = get_var_name(fp)
                        if val == '':
                            recipe_error(fp.rpstack,
                                                  _("Exepected variant value"))
                        if first:
                            # Specify the default value and change $BDIR.
                            script.append(v_indent_string + (
                                    'if not globals()["_no"].has_key("%s"):\n'
                                                                     % v.name))
                            script.append(v_indent_string + (
                                              '  %s = "%s"\n' % (v.name, val)))
                            script.append(v_indent_string + (
                                      "BDIR = _no.BDIR + '-' + _no.%s\n" % v.name))

                        s = v_indent_string
                        if not first:
                            s = s + "el"
                        script.append(s + ("if _no.%s == '%s':\n" % (v.name, val)))
                    fp.nextline()
                    if fp.line is None or get_indent(fp.line) <= v.val_indent:
                        script.append(v_indent_string + "  pass\n")
                    continue

        #
        # Stop at the end of the file.
        #
        if fp.line is None:
            break

        #
        # A Python block
        #
        #  recipe:    :python EOF
        #                   command
        #                   command
        #                 EOF
        #  Python:        command
        #                 command
        #
        if fp.line[fp.idx:fp.idx + 7] == ":python":
            fp.idx = skip_white(fp.line, fp.idx + 7)
            if fp.idx >= fp.line_len or fp.line[fp.idx] == '#':
                term = ''
            else:
                term = get_block_term(fp, ":python")

            # Get the lines until the terminator and append them to the script.
            lines = get_block_lines(fp, term, indent, first_indent, ":python")
            script.append(lines)


            continue

        #
        # An A-A-P command
        #
        #  recipe:  :cmd arg arg
        #                  arg
        #  Python:  aap_cmd(123, globals(), "arg arg arg")
        #
        if fp.line[fp.idx] == ":":
            s = fp.idx
            fp.idx = fp.idx + 1
            e = skip_to_white(fp.line, fp.idx)
            cmd_name = fp.line[fp.idx:e]
            fp.idx = skip_white(fp.line, e)

            # Check if this is a valid command name.  The error is postponed
            # until executing the line, so that "@if _no.AAPVERSION > nr" can
            # be used before it.
            if cmd_name not in aap_cmd_names:
                cmd_name = "unknown"
                fp.idx = s
            if not toplevel and cmd_name in aap_cmd_toplevel:
                cmd_name = "nothere"
                fp.idx = s

            #
            # To avoid starting a shell for every single command, collect
            # system commands until encountering another command.
            #
            # recipe:       :system one
            #               :sys  two
            #                       three
            # Python:       aap_shell(123, globals(), "one\ntwo three\n")
            #
            if cmd_name == "system" or cmd_name == "sys":
                if not shell_cmd:
                    shell_cmd_line_nr = fp.rpstack[-1].line_nr
                    shell_cmd_indent = indent
                shell_cmd = shell_cmd + getarg(fp, "#")

                # get the next line and continue until the indent is less
                while 1:
                    fp.nextline()
                    if fp.line is None or get_indent(fp.line) <= indent:
                        break       # end of commands reached
                    fp.idx = skip_white(fp.line, 0)
                    shell_cmd = shell_cmd + ' ' + getarg(fp, "#")

                shell_cmd = shell_cmd + '\\n'
                continue

            # recipe:   :variant VAR
            #               foo  [ condition ]
            #                  cmds
            #               *    [ condition ]
            #                  cmds
            # Python:   if VAR == "foo":
            #                  cmds
            #           else:
            #                  cmds
            #           BDIR = BDIR + '-' + VAR
            # This is complicated, because "cmds" can be any command, and
            # variants may nest.  Store the info about the variant in
            # variant_stack and continue, the rest is handled above.
            if cmd_name == "variant":
                var_name, n = get_var_name(fp)
                if var_name == '' or (n < fp.line_len and fp.line[n] != '#'):
                    recipe_error(fp.rpstack,
                                   _("Expected variable name after :variant"))
                variant_stack.append(Variant(var_name, indent,
                                                       fp.rpstack[-1].line_nr))

                # get the next line
                fp.nextline()
                continue

            # Generate the start of a call to the Python function for this
            # command.  The handling of the arguments may depend on the
            # command.
            #
            # All AAP commands (including :include, :import, etc.) arrive
            # here for processing and are turned into Python calls
            # for functions in Commands.py.
            #
            # recipe:   :cmd arg ...
            # Python:   aap_cmd(123, globals(),
            script.append(indent_string + ('aap_%s(%d, globals(), '
                                         % (cmd_name, fp.rpstack[-1].line_nr)))

            if cmd_name == "rule":
                # recipe:   :rule {attr} target : {attr} source
                #                 commands
                # Python:   aap_rule(123, globals(), "target", "source",
                #                      124, """commands""")
                target = getarg(fp, ":#")
                if fp.idx >= fp.line_len or fp.line[fp.idx] != ':':
                    recipe_error(fp.rpstack, _("Missing ':' after :%s")
                                                                % cmd_name)
                fp.idx = fp.idx + 1
                script.append('"%s", ' % target)

                source = getarg(fp, "#")

                fp.nextline()
                head, cmds = get_commands(fp, indent)

                script.append('"%s", %s)\n' % (source + head, cmds))

            elif cmd_name == "delrule":
                # recipe:   :delrule {attr} target : {attr} source
                # Python:   aap_delrule(123, globals(), "target", "source")
                target = getarg(fp, ":#")
                if fp.idx >= fp.line_len or fp.line[fp.idx] != ':':
                    recipe_error(fp.rpstack, _("Missing ':' after :%s")
                                                                % cmd_name)
                script.append('"%s", ' % target)
                fp.idx = fp.idx + 1
                script.append(get_func_args(fp, indent) + ")\n")

            elif cmd_name == "route":
                # recipe:   :route {default} ft1 ft2 ft3
                #                 lines
                # Python:   aap_route(123, globals(), "ft1 ft2 ft3",
                #                      124, """lines""")
                types = getarg(fp, "#")

                fp.nextline()
                head, cmds = get_commands(fp, indent)

                script.append('"%s", %s)\n' % (types + head, cmds))

            elif cmd_name == "tree":
                # recipe:   :tree dir {attr} ...
                #                 commands
                # Python:   aap_tree(123, globals(), "dir {attr} ...",
                #                      124, """commands""")
                dir = getarg(fp, "#")

                cmd_line_nr = fp.rpstack[-1].line_nr
                fp.nextline()
                head, cmds = get_commands(fp, indent)

                script.append('"%s", %d, %s)\n'
                                          % (dir + head, cmd_line_nr, cmds))

            elif cmd_name in [ "filetype", "action" ]:
                # recipe:   :filetype [filename]
                #               detection-lines
                #           :action action ftype
                #               commands
                # Python:   aap_filetype(123, globals(), "arg",
                #                              line_nr, """detection-lines""")
                #           aap_action(123, globals(), "arg",
                #                              line_nr, """commands""")
                #
                arg = getarg(fp, "#")
                cmd_line_nr = fp.rpstack[-1].line_nr
                fp.nextline()
                head, cmds = get_commands(fp, indent)

                script.append('"%s", %d, %s)\n'
                                             % (arg + head, cmd_line_nr, cmds))

            else:
                # get an argument string that may continue on the next line
                #
                # recipe:   :cmd  arg...
                # Python:   aap_cmd(123, globals(), "arg")
                script.append(get_func_args(fp, indent) + ")\n")

                # When a ":recipe" command is encountered that will probably
                # be executed, make a copy of the recdict at the start, so that
                # this can be restored when executing the updated recipe.
                # This is a "heavy" command, only do it when needed.
                from Commands import maydo_recipe_cmd
                if (cmd_name == "recipe" and not had_recipe_cmd
                                             and maydo_recipe_cmd(fp.rpstack)):
                    had_recipe_cmd = 1
                    script.insert(0, 'globals()["_start_recdict"] = globals().copy()\n')

            continue

        #
        # A Python command
        #
        #  recipe:    @command args
        #  Python:        command args
        #
        if fp.line[fp.idx] == "@":
            fp.idx = fp.idx + 1
            if fp.idx < fp.line_len:
                # The amount of indent produced is the current indent, plus
                # any indent after the "@", minus the indent of the first line.
                if fp.line[fp.idx] == ' ' or fp.line[fp.idx] == '\t':
                    # Followed by white space: replace @ with a space.
                    # Careful: there can be a TAB after the '@'.
                    i = get_indent(' ' * (indent + 1) + fp.line[fp.idx:])
                    while fp.idx < fp.line_len and fp.line[fp.idx] in " \t":
                        fp.idx = fp.idx + 1
                else:
                    # followed by text: remove the @
                    i = indent
                script.append((' ' * (i - first_indent))
                                                     + fp.line[fp.idx:] + '\n')

            # get the next line
            fp.nextline()
            continue

        #
        # A section marker
        #
        #  recipe:    >always
        #  Python:        if 1:
        #  recipe:    >build
        #  Python:        if _really_build:
        #  recipe:    >nobuild
        #  Python:        if not _really_build:
        #
        if fp.line[fp.idx] == ">":
            fp.idx = fp.idx + 1
            i = skip_to_white(fp.line, fp.idx)
            section = fp.line[fp.idx:i]
            if section == "always":
                line = "if 1:"
            elif section == "build":
                line = "if _really_build:"
            elif section == "nobuild":
                line = "if not _really_build:"
            else:
                recipe_error(fp.rpstack, _("Unknown section name: %s")
                                                                     % section)
            i = skip_white(fp.line, i)
            if i < fp.line_len and fp.line[i] != '#':
                recipe_error(fp.rpstack, _("Trailing text: %s") % fp.line[i:])
            if recdict.get("_really_build") == None:
                recipe_error(fp.rpstack, _("Using sections not allowed here"))

            script.append(indent_string + line + '\n')

            # get the next line
            fp.nextline()
            continue

        #
        # Assignment
        #
        #  recipe:   name = $VAR {attr=val} ` glob("*.c") `
        #                     two
        #  Python:       name = aap_assign(123, globals(),
        #                       "$VAR {attr=val} " + glob("*.c") + " two", 1)
        #
        #  var = value      assign
        #  var += value     append (assign if not set yet)
        #  var ?= value     only assign when not set yet
        #  var $= value     evaluate when used
        #  var $+= value    append, evaluate when used
        #  var $?= value    only when not set, evaluate when used
        #  var $+<< EOF     assign multiple lines
        #       value1
        #       value2
        #      EOF
        var_name, n = get_var_name(fp)

        if var_name != '' and n < fp.line_len:
            nc = fp.line[n]
            ec = nc
            if ec == '$' and n + 1 < fp.line_len:
                ne = n + 1
                ec = fp.line[ne]
            else:
                ne = n
            if (ec == '+' or ec == '?') and ne + 1 < fp.line_len:
                lc = ec
                ne = ne + 1
                ec = fp.line[ne]
            else:
                lc = ''
            if ec == '=' or ec == '<':
                if ec == '<':
                    # Get the term string from "var << term".
                    if ne + 1 >= fp.line_len or fp.line[ne + 1] != '<':
                        recipe_error(fp.rpstack, _("Single < not allowed"))
                    fp.idx = ne + 2
                    term = get_block_term(fp, "<<")

                # When changing $CACHEPATH need to flush the cache and reload
                # it.
                if var_name == "CACHEPATH":
                    script.append(indent_string + "flush_cache(globals())\n")
                fp.idx = skip_white(fp.line, ne + 1)
                script.append(indent_string + (
                                     "aap_assign(%d, globals(), '%s', "
                                         % (fp.rpstack[-1].line_nr, var_name)))
                if ec == '<':
                    args = get_block_lines(fp, term, 0, 0, "assignment")
                    args = '"""' + args + '"""'
                else:
                    args = get_func_args(fp, indent)
                script.append(args + (", '%s', '%s')\n" % (nc, lc)))
                continue

        #
        # If there is no ":" following we don't know what it is.
        #
        targets = getarg(fp, ":#")
        if fp.idx >= fp.line_len or fp.line[fp.idx] != ':':
            s = skip_white(fp.line, 0)
            e = skip_to_white(fp.line, s)
            recipe_error(fp.rpstack, _('Unrecognized item: "%s"')
                                                                % fp.line[s:e])

        if not toplevel:
            recipe_error(fp.rpstack, _("Dependency not allowed here"))

        #
        # Dependency
        #
        #  recipe:     target target : source source
        #                    commands
        #  Python:     aap_depend(123, globals(), list-of-targets,
        #                             list-of-sources, "commands")
        #
        else:
            # Skip the ':' and get the list of sources.
            fp.idx = skip_white(fp.line, fp.idx + 1)
            sources = getarg(fp, '#')
            nr = fp.rpstack[-1].line_nr
            fp.nextline()

            # get the commands and the following line
            head, cmds = get_commands(fp, indent)
            sources = sources + head

            script.append(indent_string
                        + ('aap_depend(%d, globals(), "%s", "%s", '
                                                      % (nr, targets, sources))
                        + cmds + ')\n')

        #
        # End of loop over all lines in recipe.
        #


    if fp.file:
        # Close the file before executing the script, so that ":recipe" can
        # overwrite the file.
        fp.file.close()

    # Prepend the default imports.
    script.insert(0, "from Commands import *\n"
                   + "from RecPython import *\n"
                   + "from Port import *\n"
                   + "from glob import glob\n")

    # Trun the list of lines into a single string.
    # It's in a separate function for profiling.
    script_string = list2string(script)

    # Need to be able to find the globals from invoked functions.
    save_globals = Global.globals
    Global.globals = recdict
    try:
        
        # DEBUG - list generated Python always
        # msg_note(recdict, script_string)

        #
        # Execute the resulting Python script.
        # Give a useful error message when something is wrong.
        #
        try:
            exec script_string in recdict, recdict
        except KeyboardInterrupt:
            raise       # don't need a stack dump when interrupted
        except StandardError, e:
            # DEBUG - list generated Python when a Python error is encountered
            #msg_note(recdict, script_string)
            script_error(fp.rpstack, recdict, script_string)

        # DEBUG - list generated Python when a recipe error is encountered
        #except UserError:
            #msg_note(recdict, script_string)
            #raise

    finally:
        # Restore the old globals.
        Global.globals = save_globals

        # Restore at_toplevel.
        Global.at_toplevel = save_at_toplevel



# vim: set sw=4 et sts=4 tw=79 fo+=l: