summaryrefslogtreecommitdiffstats
path: root/src/engine/SCons/Util.py
blob: 636a74fbe9d612a6452d82bafd602040c92ad79d (plain)
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
"""SCons.Util

Various utility functions go here.

"""

#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"


import copy
import os
import os.path
import re
import stat
import string
import sys
import types
import UserDict
import UserList

import SCons.Errors

try:
    from UserString import UserString
except ImportError:
    # "Borrowed" from the Python 2.2 UserString module
    # and modified slightly for use with SCons.
    class UserString:
        def __init__(self, seq):
            if is_String(seq):
                self.data = seq
            elif isinstance(seq, UserString):
                self.data = seq.data[:]
            else:
                self.data = str(seq)
        def __str__(self): return str(self.data)
        def __repr__(self): return repr(self.data)
        def __int__(self): return int(self.data)
        def __long__(self): return long(self.data)
        def __float__(self): return float(self.data)
        def __complex__(self): return complex(self.data)
        def __hash__(self): return hash(self.data)

        def __cmp__(self, string):
            if isinstance(string, UserString):
                return cmp(self.data, string.data)
            else:
                return cmp(self.data, string)
        def __contains__(self, char):
            return char in self.data

        def __len__(self): return len(self.data)
        def __getitem__(self, index): return self.__class__(self.data[index])
        def __getslice__(self, start, end):
            start = max(start, 0); end = max(end, 0)
            return self.__class__(self.data[start:end])

        def __add__(self, other):
            if isinstance(other, UserString):
                return self.__class__(self.data + other.data)
            elif is_String(other):
                return self.__class__(self.data + other)
            else:
                return self.__class__(self.data + str(other))
        def __radd__(self, other):
            if is_String(other):
                return self.__class__(other + self.data)
            else:
                return self.__class__(str(other) + self.data)
        def __mul__(self, n):
            return self.__class__(self.data*n)
        __rmul__ = __mul__

_altsep = os.altsep
if _altsep is None and sys.platform == 'win32':
    # My ActivePython 2.0.1 doesn't set os.altsep!  What gives?
    _altsep = '/'

def splitext(path):
    "Same as os.path.splitext() but faster."
    if _altsep:
        sep = max(string.rfind(path, os.sep), string.rfind(path, _altsep))
    else:
        sep = string.rfind(path, os.sep)
    dot = string.rfind(path, '.')
    if dot > sep:
        return path[:dot],path[dot:]
    else:
        return path,""

def updrive(path):
    """
    Make the drive letter (if any) upper case.
    This is useful because Windows is inconsitent on the case
    of the drive letter, which can cause inconsistencies when
    calculating command signatures.
    """
    drive, rest = os.path.splitdrive(path)
    if drive:
        path = string.upper(drive) + rest
    return path

#
# Generic convert-to-string functions that abstract away whether or
# not the Python we're executing has Unicode support.  The wrapper
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
if hasattr(types, 'UnicodeType'):
    def to_String(s):
        if isinstance(s, UserString):
            t = type(s.data)
        else:
            t = type(s)
        if t is types.UnicodeType:
            return unicode(s)
        else:
            return str(s)
else:
    to_String = str

def to_String_for_signature(obj):
    try:
        f = obj.for_signature
    except:
        return to_String(obj)
    else:
        return f()

# Indexed by the SUBST_* constants below.
_strconv = [to_String, to_String, to_String_for_signature]

class Literal:
    """A wrapper for a string.  If you use this object wrapped
    around a string, then it will be interpreted as literal.
    When passed to the command interpreter, all special
    characters will be escaped."""
    def __init__(self, lstr):
        self.lstr = lstr

    def __str__(self):
        return self.lstr

    def escape(self, escape_func):
        return escape_func(self.lstr)

    def for_signature(self):
        return self.lstr

    def is_literal(self):
        return 1

class SpecialAttrWrapper:
    """This is a wrapper for what we call a 'Node special attribute.'
    This is any of the attributes of a Node that we can reference from
    Environment variable substitution, such as $TARGET.abspath or
    $SOURCES[1].filebase.  We implement the same methods as Literal
    so we can handle special characters, plus a for_signature method,
    such that we can return some canonical string during signature
    calculation to avoid unnecessary rebuilds."""

    def __init__(self, lstr, for_signature=None):
        """The for_signature parameter, if supplied, will be the
        canonical string we return from for_signature().  Else
        we will simply return lstr."""
        self.lstr = lstr
        if for_signature:
            self.forsig = for_signature
        else:
            self.forsig = lstr

    def __str__(self):
        return self.lstr

    def escape(self, escape_func):
        return escape_func(self.lstr)

    def for_signature(self):
        return self.forsig

    def is_literal(self):
        return 1

class CallableComposite(UserList.UserList):
    """A simple composite callable class that, when called, will invoke all
    of its contained callables with the same arguments."""
    def __init__(self, seq = []):
        UserList.UserList.__init__(self, seq)

    def __call__(self, *args, **kwargs):
        retvals = map(lambda x, args=args, kwargs=kwargs: apply(x,
                                                                args,
                                                                kwargs),
                      self.data)
        if self.data and (len(self.data) == len(filter(callable, retvals))):
            return self.__class__(retvals)
        return NodeList(retvals)

class NodeList(UserList.UserList):
    """This class is almost exactly like a regular list of Nodes
    (actually it can hold any object), with one important difference.
    If you try to get an attribute from this list, it will return that
    attribute from every item in the list.  For example:

    >>> someList = NodeList([ '  foo  ', '  bar  ' ])
    >>> someList.strip()
    [ 'foo', 'bar' ]
    """
    def __init__(self, seq = []):
        UserList.UserList.__init__(self, seq)

    def __nonzero__(self):
        return len(self.data) != 0

    def __str__(self):
        return string.join(map(str, self.data))

    def __getattr__(self, name):
        if not self.data:
            # If there is nothing in the list, then we have no attributes to
            # pass through, so raise AttributeError for everything.
            raise AttributeError, "NodeList has no attribute: %s" % name

        # Return a list of the attribute, gotten from every element
        # in the list
        attrList = map(lambda x, n=name: getattr(x, n), self.data)

        # Special case.  If the attribute is callable, we do not want
        # to return a list of callables.  Rather, we want to return a
        # single callable that, when called, will invoke the function on
        # all elements of this list.
        if self.data and (len(self.data) == len(filter(callable, attrList))):
            return CallableComposite(attrList)
        return self.__class__(attrList)

_valid_var = re.compile(r'[_a-zA-Z]\w*$')
_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')

def is_valid_construction_var(varstr):
    """Return if the specified string is a legitimate construction
    variable.
    """
    return _valid_var.match(varstr)

def get_environment_var(varstr):
    """Given a string, first determine if it looks like a reference
    to a single environment variable, like "$FOO" or "${FOO}".
    If so, return that variable with no decorations ("FOO").
    If not, return None."""
    mo=_get_env_var.match(to_String(varstr))
    if mo:
        var = mo.group(1)
        if var[0] == '{':
            return var[1:-1]
        else:
            return var
    else:
        return None

def quote_spaces(arg):
    """Generic function for putting double quotes around any string that
    has white space in it."""
    if ' ' in arg or '\t' in arg:
        return '"%s"' % arg
    else:
        return str(arg)

class CmdStringHolder(UserString):
    """This is a special class used to hold strings generated by
    scons_subst() and scons_subst_list().  It defines a special method
    escape().  When passed a function with an escape algorithm for a
    particular platform, it will return the contained string with the
    proper escape sequences inserted.

    This should really be a subclass of UserString, but that module
    doesn't exist in Python 1.5.2."""
    def __init__(self, cmd, literal=None):
        UserString.__init__(self, cmd)
        self.literal = literal

    def is_literal(self):
        return self.literal

    def escape(self, escape_func, quote_func=quote_spaces):
        """Escape the string with the supplied function.  The
        function is expected to take an arbitrary string, then
        return it with all special characters escaped and ready
        for passing to the command interpreter.

        After calling this function, the next call to str() will
        return the escaped string.
        """

        if self.is_literal():
            return escape_func(self.data)
        elif ' ' in self.data or '\t' in self.data:
            return quote_func(self.data)
        else:
            return self.data

class DisplayEngine:
    def __init__(self):
        self.__call__ = self.print_it

    def print_it(self, text):
        sys.stdout.write(text + '\n')

    def dont_print(self, text):
        pass

    def set_mode(self, mode):
        if mode:
            self.__call__ = self.print_it
        else:
            self.__call__ = self.dont_print

def escape_list(list, escape_func):
    """Escape a list of arguments by running the specified escape_func
    on every object in the list that has an escape() method."""
    def escape(obj, escape_func=escape_func):
        try:
            e = obj.escape
        except AttributeError:
            return obj
        else:
            return e(escape_func)
    return map(escape, list)

class NLWrapper:
    """A wrapper class that delays turning a list of sources or targets
    into a NodeList until it's needed.  The specified function supplied
    when the object is initialized is responsible for turning raw nodes
    into proxies that implement the special attributes like .abspath,
    .source, etc.  This way, we avoid creating those proxies just
    "in case" someone is going to use $TARGET or the like, and only
    go through the trouble if we really have to.

    In practice, this might be a wash performance-wise, but it's a little
    cleaner conceptually...
    """

    def __init__(self, list, func):
        self.list = list
        self.func = func
    def _create_nodelist(self):
        try:
            return self.nodelist
        except AttributeError:
            list = self.list
            if list is None:
                list = []
            elif not is_List(list):
                list = [list]
            # The map(self.func) call is what actually turns
            # a list into appropriate proxies.
            self.nodelist = NodeList(map(self.func, list))
        return self.nodelist

class Targets_or_Sources(UserList.UserList):
    """A class that implements $TARGETS or $SOURCES expansions by in turn
    wrapping a NLWrapper.  This class handles the different methods used
    to access the list, calling the NLWrapper to create proxies on demand.

    Note that we subclass UserList.UserList purely so that the is_List()
    function will identify an object of this class as a list during
    variable expansion.  We're not really using any UserList.UserList
    methods in practice.
    """
    def __init__(self, nl):
        self.nl = nl
    def __getattr__(self, attr):
        nl = self.nl._create_nodelist()
        return getattr(nl, attr)
    def __getitem__(self, i):
        nl = self.nl._create_nodelist()
        return nl[i]
    def __getslice__(self, i, j):
        nl = self.nl._create_nodelist()
        i = max(i, 0); j = max(j, 0)
        return nl[i:j]
    def __str__(self):
        nl = self.nl._create_nodelist()
        return str(nl)
    def __repr__(self):
        nl = self.nl._create_nodelist()
        return repr(nl)

class Target_or_Source:
    """A class that implements $TARGET or $SOURCE expansions by in turn
    wrapping a NLWrapper.  This class handles the different methods used
    to access an individual proxy Node, calling the NLWrapper to create
    a proxy on demand.
    """
    def __init__(self, nl):
        self.nl = nl
    def __getattr__(self, attr):
        nl = self.nl._create_nodelist()
        try:
            nl0 = nl[0]
        except IndexError:
            # If there is nothing in the list, then we have no attributes to
            # pass through, so raise AttributeError for everything.
            raise AttributeError, "NodeList has no attribute: %s" % attr
        return getattr(nl0, attr)
    def __str__(self):
        nl = self.nl._create_nodelist()
        try:
            nl0 = nl[0]
        except IndexError:
            return ''
        return str(nl0)
    def __repr__(self):
        nl = self.nl._create_nodelist()
        try:
            nl0 = nl[0]
        except IndexError:
            return ''
        return repr(nl0)

def subst_dict(target, source):
    """Create a dictionary for substitution of special
    construction variables.

    This translates the following special arguments:

    target - the target (object or array of objects),
             used to generate the TARGET and TARGETS
             construction variables

    source - the source (object or array of objects),
             used to generate the SOURCES and SOURCE
             construction variables
    """
    dict = {}

    if target:
        tnl = NLWrapper(target, lambda x: x.get_subst_proxy())
        dict['TARGETS'] = Targets_or_Sources(tnl)
        dict['TARGET'] = Target_or_Source(tnl)

    if source:
        snl = NLWrapper(source, lambda x: x.rfile().get_subst_proxy())
        dict['SOURCES'] = Targets_or_Sources(snl)
        dict['SOURCE'] = Target_or_Source(snl)

    return dict

# Constants for the "mode" parameter to scons_subst_list() and
# scons_subst().  SUBST_RAW gives the raw command line.  SUBST_CMD
# gives a command line suitable for passing to a shell.  SUBST_SIG
# gives a command line appropriate for calculating the signature
# of a command line...if this changes, we should rebuild.
SUBST_CMD = 0
SUBST_RAW = 1
SUBST_SIG = 2

_rm = re.compile(r'\$[()]')
_remove = re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')

# Indexed by the SUBST_* constants above.
_regex_remove = [ _rm, None, _remove ]

# This regular expression splits a string into the following types of
# arguments for use by the scons_subst() and scons_subst_list() functions:
#
#       "$$"
#       "$("
#       "$)"
#       "$variable"             [must begin with alphabetic or underscore]
#       "${any stuff}"
#       "   "                   [white space]
#       "non-white-space"       [without any dollar signs]
#       "$"                     [single dollar sign]
#
_separate_args = re.compile(r'(\$[\$\(\)]|\$[_a-zA-Z][\.\w]*|\${[^}]*}|\s+|[^\s\$]+|\$)')

# This regular expression is used to replace strings of multiple white
# space characters in the string result from the scons_subst() function.
_space_sep = re.compile(r'[\t ]+(?![^{]*})')

def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
    """Expand a string containing construction variable substitutions.

    This is the work-horse function for substitutions in file names
    and the like.  The companion scons_subst_list() function (below)
    handles separating command lines into lists of arguments, so see
    that function if that's what you're looking for.
    """
    class StringSubber:
        """A class to construct the results of a scons_subst() call.

        This binds a specific construction environment, mode, target and
        source with two methods (substitute() and expand()) that handle
        the expansion.
        """
        def __init__(self, env, mode, target, source, conv, gvars):
            self.env = env
            self.mode = mode
            self.target = target
            self.source = source
            self.conv = conv
            self.gvars = gvars

        def expand(self, s, lvars):
            """Expand a single "token" as necessary, returning an
            appropriate string containing the expansion.

            This handles expanding different types of things (strings,
            lists, callables) appropriately.  It calls the wrapper
            substitute() method to re-expand things as necessary, so that
            the results of expansions of side-by-side strings still get
            re-evaluated separately, not smushed together.
            """
            if is_String(s):
                try:
                    s0, s1 = s[:2]
                except (IndexError, ValueError):
                    return s
                if s0 == '$':
                    if s1 == '$':
                        return '$'
                    elif s1 in '()':
                        return s
                    else:
                        key = s[1:]
                        if key[0] == '{':
                            key = key[1:-1]
                        try:
                            s = eval(key, self.gvars, lvars)
                        except (IndexError, NameError, TypeError):
                            return ''
                        except SyntaxError,e:
                            if self.target:
                                raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
                            else:
                                raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
                        else:
                            # Before re-expanding the result, handle
                            # recursive expansion by copying the local
                            # variable dictionary and overwriting a null
                            # string for the value of the variable name
                            # we just expanded.
                            lv = lvars.copy()
                            var = string.split(key, '.')[0]
                            lv[var] = ''
                            return self.substitute(s, lv)
                else:
                    return s
            elif is_List(s):
                r = []
                for l in s:
                    r.append(self.conv(self.substitute(l, lvars)))
                return string.join(r)
            elif callable(s):
                s = s(target=self.target,
                     source=self.source,
                     env=self.env,
                     for_signature=(self.mode != SUBST_CMD))
                return self.substitute(s, lvars)
            elif s is None:
                return ''
            else:
                return s

        def substitute(self, args, lvars):
            """Substitute expansions in an argument or list of arguments.

            This serves as a wrapper for splitting up a string into
            separate tokens.
            """
            if is_String(args) and not isinstance(args, CmdStringHolder):
                args = _separate_args.findall(args)
                result = []
                for a in args:
                    result.append(self.conv(self.expand(a, lvars)))
                try:
                    result = string.join(result, '')
                except TypeError:
                    pass
                return result
            else:
                return self.expand(args, lvars)

    if dict is None:
        dict = subst_dict(target, source)
    if conv is None:
        conv = _strconv[mode]
    if gvars is None:
        gvars = env.Dictionary()

    ss = StringSubber(env, mode, target, source, conv, gvars)
    result = ss.substitute(strSubst, dict)

    if is_String(result):
        # Remove $(-$) pairs and any stuff in between,
        # if that's appropriate.
        remove = _regex_remove[mode]
        if remove:
            result = remove.sub('', result)
        if mode != SUBST_RAW:
            # Compress strings of white space characters into
            # a single space.
            result = string.strip(_space_sep.sub(' ', result))

    return result

def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
    """Substitute construction variables in a string (or list or other
    object) and separate the arguments into a command list.

    The companion scons_subst() function (above) handles basic
    substitutions within strings, so see that function instead
    if that's what you're looking for.
    """
    class ListSubber(UserList.UserList):
        """A class to construct the results of a scons_subst_list() call.

        Like StringSubber, this class binds a specific binds a specific
        construction environment, mode, target and source with two methods
        (substitute() and expand()) that handle the expansion.

        In addition, however, this class is used to track the state of
        the result(s) we're gathering so we can do the appropriate thing
        whenever we have to append another word to the result--start a new
        line, start a new word, append to the current word, etc.  We do
        this by setting the "append" attribute to the right method so
        that our wrapper methods only need ever call ListSubber.append(),
        and the rest of the object takes care of doing the right thing
        internally.
        """
        def __init__(self, env, mode, target, source, conv, gvars):
            UserList.UserList.__init__(self, [])
            self.env = env
            self.mode = mode
            self.target = target
            self.source = source
            self.conv = conv
            self.gvars = gvars

            if self.mode == SUBST_RAW:
                self.add_strip = lambda x, s=self: s.append(x)
            else:
                self.add_strip = lambda x, s=self: None
            self.in_strip = None
            self.next_line()

        def expand(self, s, lvars, within_list):
            """Expand a single "token" as necessary, appending the
            expansion to the current result.

            This handles expanding different types of things (strings,
            lists, callables) appropriately.  It calls the wrapper
            substitute() method to re-expand things as necessary, so that
            the results of expansions of side-by-side strings still get
            re-evaluated separately, not smushed together.
            """
            if is_String(s):
                try:
                    s0, s1 = s[:2]
                except (IndexError, ValueError):
                    self.append(s)
                    return
                if s0 == '$':
                    if s1 == '$':
                        self.append('$')
                    elif s1 == '(':
                        self.open_strip('$(')
                    elif s1 == ')':
                        self.close_strip('$)')
                    else:
                        key = s[1:]
                        if key[0] == '{':
                            key = key[1:-1]
                        try:
                            s = eval(key, self.gvars, lvars)
                        except (IndexError, NameError, TypeError):
                            return
                        except SyntaxError,e:
                            if self.target:
                                raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
                            else:
                                raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
                        else:
                            # Before re-expanding the result, handle
                            # recursive expansion by copying the local
                            # variable dictionary and overwriting a null
                            # string for the value of the variable name
                            # we just expanded.
                            lv = lvars.copy()
                            var = string.split(key, '.')[0]
                            lv[var] = ''
                            self.substitute(s, lv, 0)
                            self.this_word()
                else:
                    self.append(s)
            elif is_List(s):
                for a in s:
                    self.substitute(a, lvars, 1)
                    self.next_word()
            elif callable(s):
                s = s(target=self.target,
                     source=self.source,
                     env=self.env,
                     for_signature=(self.mode != SUBST_CMD))
                self.substitute(s, lvars, within_list)
            elif s is None:
                self.this_word()
            else:
                self.append(s)

        def substitute(self, args, lvars, within_list):
            """Substitute expansions in an argument or list of arguments.

            This serves as a wrapper for splitting up a string into
            separate tokens.
            """
            if is_String(args) and not isinstance(args, CmdStringHolder):
                args = _separate_args.findall(args)
                for a in args:
                    if a[0] in ' \t\n\r\f\v':
                        if '\n' in a:
                            self.next_line()
                        elif within_list:
                            self.append(a)
                        else:
                            self.next_word()
                    else:
                        self.expand(a, lvars, within_list)
            else:
                self.expand(args, lvars, within_list)

        def next_line(self):
            """Arrange for the next word to start a new line.  This
            is like starting a new word, except that we have to append
            another line to the result."""
            UserList.UserList.append(self, [])
            self.next_word()
        def this_word(self):
            """Arrange for the next word to append to the end of the
            current last word in the result."""
            self.append = self.add_to_current_word
        def next_word(self):
            """Arrange for the next word to start a new word."""
            self.append = self.add_new_word

        def add_to_current_word(self, x):
            if not self.in_strip or self.mode != SUBST_SIG:
                try:
                    self[-1][-1] = self[-1][-1] + x
                except IndexError:
                    self.add_new_word(x)
        def add_new_word(self, x):
            if not self.in_strip or self.mode != SUBST_SIG:
                try:
                    l = x.is_literal
                except AttributeError:
                    literal = None
                else:
                    literal = l()
                x = self.conv(x)
                if is_String(x):
                    x = CmdStringHolder(x, literal)
                self[-1].append(x)
            self.append = self.add_to_current_word

        def open_strip(self, x):
            """Handle the "open strip" $( token."""
            self.add_strip(x)
            self.in_strip = 1
        def close_strip(self, x):
            """Handle the "close strip" $) token."""
            self.add_strip(x)
            self.in_strip = None

    if dict is None:
        dict = subst_dict(target, source)
    if conv is None:
        conv = _strconv[mode]
    if gvars is None:
        gvars = env.Dictionary()

    ls = ListSubber(env, mode, target, source, conv, gvars)
    ls.substitute(strSubst, dict, 0)

    return ls.data

def scons_subst_once(strSubst, env, key):
    """Perform single (non-recursive) substitution of a single
    construction variable keyword.

    This is used when setting a variable when copying or overriding values
    in an Environment.  We want to capture (expand) the old value before
    we override it, so people can do things like:

        env2 = env.Copy(CCFLAGS = '$CCFLAGS -g')

    We do this with some straightforward, brute-force code here...
    """
    matchlist = ['$' + key, '${' + key + '}']
    if is_List(strSubst):
        result = []
        for arg in strSubst:
            if is_String(arg):
                if arg in matchlist:
                    arg = env[key]
                    if is_List(arg):
                        result.extend(arg)
                    else:
                        result.append(arg)
                else:
                    r = []
                    for a in _separate_args.findall(arg):
                        if a in matchlist:
                            a = env[key]
                        if is_List(a):
                            r.append(string.join(map(str, a)))
                        else:
                            r.append(str(a))
                    result.append(string.join(r, ''))
            else:
                result.append(arg)
        return result
    elif is_String(strSubst):
        result = []
        for a in _separate_args.findall(strSubst):
            if a in matchlist:
                a = env[key]
            if is_List(a):
                result.append(string.join(map(str, a)))
            else:
                result.append(str(a))
        return string.join(result, '')
    else:
        return strSubst

def render_tree(root, child_func, prune=0, margin=[0], visited={}):
    """
    Render a tree of nodes into an ASCII tree view.
    root - the root node of the tree
    child_func - the function called to get the children of a node
    prune - don't visit the same node twice
    margin - the format of the left margin to use for children of root.
       1 results in a pipe, and 0 results in no pipe.
    visited - a dictionary of visited nodes in the current branch if not prune,
       or in the whole tree if prune.
    """

    if visited.has_key(root):
        return ""

    children = child_func(root)
    retval = ""
    for pipe in margin[:-1]:
        if pipe:
            retval = retval + "| "
        else:
            retval = retval + "  "

    retval = retval + "+-" + str(root) + "\n"
    if not prune:
        visited = copy.copy(visited)
    visited[root] = 1

    for i in range(len(children)):
        margin.append(i<len(children)-1)
        retval = retval + render_tree(children[i], child_func, prune, margin, visited
)
        margin.pop()

    return retval

def is_Dict(e):
    return type(e) is types.DictType or isinstance(e, UserDict.UserDict)

def is_List(e):
    return type(e) is types.ListType or isinstance(e, UserList.UserList)

if hasattr(types, 'UnicodeType'):
    def is_String(e):
        return type(e) is types.StringType \
            or type(e) is types.UnicodeType \
            or isinstance(e, UserString)
else:
    def is_String(e):
        return type(e) is types.StringType or isinstance(e, UserString)

class Proxy:
    """A simple generic Proxy class, forwarding all calls to
    subject.  Inherit from this class to create a Proxy."""
    def __init__(self, subject):
        self.__subject = subject

    def __getattr__(self, name):
        return getattr(self.__subject, name)

    def get(self):
        return self.__subject

# attempt to load the windows registry module:
can_read_reg = 0
try:
    import _winreg

    can_read_reg = 1
    hkey_mod = _winreg

    RegOpenKeyEx = _winreg.OpenKeyEx
    RegEnumKey = _winreg.EnumKey
    RegEnumValue = _winreg.EnumValue
    RegQueryValueEx = _winreg.QueryValueEx
    RegError = _winreg.error

except ImportError:
    try:
        import win32api
        import win32con
        can_read_reg = 1
        hkey_mod = win32con

        RegOpenKeyEx = win32api.RegOpenKeyEx
        RegEnumKey = win32api.RegEnumKey
        RegEnumValue = win32api.RegEnumValue
        RegQueryValueEx = win32api.RegQueryValueEx
        RegError = win32api.error

    except ImportError:
        class _NoError(Exception):
            pass
        RegError = _NoError

if can_read_reg:
    HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
    HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
    HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
    HKEY_USERS = hkey_mod.HKEY_USERS

    def RegGetValue(root, key):
        """This utility function returns a value in the registry
        without having to open the key first.  Only available on
        Windows platforms with a version of Python that can read the
        registry.  Returns the same thing as
        SCons.Util.RegQueryValueEx, except you just specify the entire
        path to the value, and don't have to bother opening the key
        first.  So:

        Instead of:
          k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\Microsoft\Windows\CurrentVersion')
          out = SCons.Util.RegQueryValueEx(k,
                'ProgramFilesDir')

        You can write:
          out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
        """
        # I would use os.path.split here, but it's not a filesystem
        # path...
        p = key.rfind('\\') + 1
        keyp = key[:p]
        val = key[p:]
        k = SCons.Util.RegOpenKeyEx(root, keyp)
        return SCons.Util.RegQueryValueEx(k,val)

if sys.platform == 'win32':

    def WhereIs(file, path=None, pathext=None, reject=[]):
        if path is None:
            path = os.environ['PATH']
        if is_String(path):
            path = string.split(path, os.pathsep)
        if pathext is None:
            try:
                pathext = os.environ['PATHEXT']
            except KeyError:
                pathext = '.COM;.EXE;.BAT;.CMD'
        if is_String(pathext):
            pathext = string.split(pathext, os.pathsep)
        for ext in pathext:
            if string.lower(ext) == string.lower(file[-len(ext):]):
                pathext = ['']
                break
        if not is_List(reject):
            reject = [reject]
        for dir in path:
            f = os.path.join(dir, file)
            for ext in pathext:
                fext = f + ext
                if os.path.isfile(fext):
                    try:
                        reject.index(fext)
                    except ValueError:
                        return os.path.normpath(fext)
                    continue
        return None

elif os.name == 'os2':

    def WhereIs(file, path=None, pathext=None, reject=[]):
        if path is None:
            path = os.environ['PATH']
        if is_String(path):
            path = string.split(path, os.pathsep)
        if pathext is None:
            pathext = ['.exe', '.cmd']
        for ext in pathext:
            if string.lower(ext) == string.lower(file[-len(ext):]):
                pathext = ['']
                break
        if not is_List(reject):
            reject = [reject]
        for dir in path:
            f = os.path.join(dir, file)
            for ext in pathext:
                fext = f + ext
                if os.path.isfile(fext):
                    try:
                        reject.index(fext)
                    except ValueError:
                        return os.path.normpath(fext)
                    continue
        return None

else:

    def WhereIs(file, path=None, pathext=None, reject=[]):
        if path is None:
            path = os.environ['PATH']
        if is_String(path):
            path = string.split(path, os.pathsep)
        if not is_List(reject):
            reject = [reject]
        for d in path:
            f = os.path.join(d, file)
            if os.path.isfile(f):
                try:
                    st = os.stat(f)
                except OSError:
                    continue
                if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
                    try:
                        reject.index(f)
                    except ValueError:
                        return os.path.normpath(f)
                    continue
        return None

def PrependPath(oldpath, newpath, sep = os.pathsep):
    """This prepends newpath elements to the given oldpath.  Will only
    add any particular path once (leaving the first one it encounters
    and ignoring the rest, to preserve path order), and will
    os.path.normpath and os.path.normcase all paths to help assure
    this.  This can also handle the case where the given old path
    variable is a list instead of a string, in which case a list will
    be returned instead of a string.

    Example:
      Old Path: "/foo/bar:/foo"
      New Path: "/biz/boom:/foo"
      Result:   "/biz/boom:/foo:/foo/bar"
    """

    orig = oldpath
    is_list = 1
    paths = orig
    if not is_List(orig):
        paths = string.split(paths, sep)
        is_list = 0

    if is_List(newpath):
        newpaths = newpath
    else:
        newpaths = string.split(newpath, sep)

    newpaths = newpaths + paths # prepend new paths

    normpaths = []
    paths = []
    # now we add them only of they are unique
    for path in newpaths:
        normpath = os.path.normpath(os.path.normcase(path))
        if path and not normpath in normpaths:
            paths.append(path)
            normpaths.append(normpath)

    if is_list:
        return paths
    else:
        return string.join(paths, sep)

def AppendPath(oldpath, newpath, sep = os.pathsep):
    """This appends new path elements to the given old path.  Will
    only add any particular path once (leaving the last one it
    encounters and ignoring the rest, to preserve path order), and
    will os.path.normpath and os.path.normcase all paths to help
    assure this.  This can also handle the case where the given old
    path variable is a list instead of a string, in which case a list
    will be returned instead of a string.

    Example:
      Old Path: "/foo/bar:/foo"
      New Path: "/biz/boom:/foo"
      Result:   "/foo/bar:/biz/boom:/foo"
    """

    orig = oldpath
    is_list = 1
    paths = orig
    if not is_List(orig):
        paths = string.split(paths, sep)
        is_list = 0

    if is_List(newpath):
        newpaths = newpath
    else:
        newpaths = string.split(newpath, sep)

    newpaths = paths + newpaths # append new paths
    newpaths.reverse()

    normpaths = []
    paths = []
    # now we add them only of they are unique
    for path in newpaths:
        normpath = os.path.normpath(os.path.normcase(path))
        if path and not normpath in normpaths:
            paths.append(path)
            normpaths.append(normpath)

    paths.reverse()

    if is_list:
        return paths
    else:
        return string.join(paths, sep)


def dir_index(directory):
    files = []
    for f in os.listdir(directory):
        fullname = os.path.join(directory, f)
        files.append(fullname)

    # os.listdir() isn't guaranteed to return files in any specific order,
    # but some of the test code expects sorted output.
    files.sort()
    return files

def fs_delete(path, remove=1):
    try:
        if os.path.exists(path):
            if os.path.isfile(path):
                if remove: os.unlink(path)
                display("Removed " + path)
            elif os.path.isdir(path) and not os.path.islink(path):
                # delete everything in the dir
                for p in dir_index(path):
                    if os.path.isfile(p):
                        if remove: os.unlink(p)
                        display("Removed " + p)
                    else:
                        fs_delete(p, remove)
                # then delete dir itself
                if remove: os.rmdir(path)
                display("Removed directory " + path)
    except OSError, e:
        print "scons: Could not remove '%s':" % str(path), e.strerror

if sys.platform == 'cygwin':
    def get_native_path(path):
        """Transforms an absolute path into a native path for the system.  In
        Cygwin, this converts from a Cygwin path to a Win32 one."""
        return string.replace(os.popen('cygpath -w ' + path).read(), '\n', '')
else:
    def get_native_path(path):
        """Transforms an absolute path into a native path for the system.
        Non-Cygwin version, just leave the path alone."""
        return path

display = DisplayEngine()

def Split(arg):
    if is_List(arg):
        return arg
    elif is_String(arg):
        return string.split(arg)
    else:
        return [arg]

class CLVar(UserList.UserList):
    """A class for command-line construction variables.

    This is a list that uses Split() to split an initial string along
    white-space arguments, and similarly to split any strings that get
    added.  This allows us to Do the Right Thing with Append() and
    Prepend() (as well as straight Python foo = env['VAR'] + 'arg1
    arg2') regardless of whether a user adds a list or a string to a
    command-line construction variable.
    """
    def __init__(self, seq = []):
        UserList.UserList.__init__(self, Split(seq))
    def __coerce__(self, other):
        return (self, CLVar(other))
    def __str__(self):
        return string.join(self.data)

class Selector(UserDict.UserDict):
    """A callable dictionary that maps file suffixes to dictionary
    values."""
    def __call__(self, env, source):
        ext = splitext(str(source[0]))[1]
        try:
            return self[ext]
        except KeyError:
            # Try to perform Environment substitution on the keys of
            # emitter_dict before giving up.
            s_dict = {}
            for (k,v) in self.items():
                if not k is None:
                    s_k = env.subst(k)
                    if s_dict.has_key(s_k):
                        # We only raise an error when variables point
                        # to the same suffix.  If one suffix is literal
                        # and a variable suffix contains this literal,
                        # the literal wins and we don't raise an error.
                        raise KeyError, (s_dict[s_k][0], k, s_k)
                    s_dict[s_k] = (k,v)
            try:
                return s_dict[ext][1]
            except KeyError:
                try:
                    return self[None]
                except KeyError:
                    return None


if sys.platform == 'cygwin':
    # On Cygwin, os.path.normcase() lies, so just report back the
    # fact that the underlying Win32 OS is case-insensitive.
    def case_sensitive_suffixes(s1, s2):
        return 0
else:
    def case_sensitive_suffixes(s1, s2):
        return (os.path.normcase(s1) != os.path.normcase(s2))

def adjustixes(fname, pre, suf):
    if pre:
        path, fn = os.path.split(os.path.normpath(fname))
        if fn[:len(pre)] != pre:
            fname = os.path.join(path, pre + fn)
    # Only append a suffix if the file does not have one.
    if suf and not splitext(fname)[1] and fname[-len(suf):] != suf:
            fname = fname + suf
    return fname