summaryrefslogtreecommitdiff
path: root/scss/types.py
blob: c35905a3113da62ff51ab0b589ca7f27a22dafc6 (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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from collections import Iterable
import colorsys
from fractions import Fraction
import operator
import re
import string
from warnings import warn

import six

from scss.cssdefs import COLOR_LOOKUP, COLOR_NAMES, ZEROABLE_UNITS, convert_units_to_base_units, cancel_base_units, count_base_units

PRECISION = 5


###############################################################################
# pyScss data types:

# TODO make Value work as a string in every way?  i.e. have a .quotes...
class Value(object):
    is_null = False
    sass_type_name = 'unknown'

    def __repr__(self):
        return "<{0}: {1!r}>".format(type(self).__name__, self.value)

    # Sass values are all true, except for booleans and nulls
    def __bool__(self):
        return True

    def __nonzero__(self):
        # Py 2's name for __bool__
        return self.__bool__()

    # All Sass scalars also act like one-element spaced lists
    use_comma = False

    def __iter__(self):
        return iter((self,))

    def __len__(self):
        return 1

    def __getitem__(self, key):
        if key not in (-1, 0):
            raise IndexError(key)

        return self

    def __contains__(self, item):
        return self == item

    ### NOTE: From here on down, the operators are exposed to Sass code and
    ### thus should ONLY return Sass types

    # Reasonable default for equality
    def __eq__(self, other):
        return Boolean(
            type(self) == type(other) and self.value == other.value)

    def __ne__(self, other):
        return Boolean(not self.__eq__(other))

    # Only numbers support ordering
    def __lt__(self, other):
        raise TypeError("Can't compare %r with %r" % (self, other))

    def __le__(self, other):
        raise TypeError("Can't compare %r with %r" % (self, other))

    def __gt__(self, other):
        raise TypeError("Can't compare %r with %r" % (self, other))

    def __ge__(self, other):
        raise TypeError("Can't compare %r with %r" % (self, other))

    # Math ops
    def __add__(self, other):
        # Default behavior is to treat both sides like strings
        if isinstance(other, String):
            return String(self.render() + other.value, quotes=other.quotes)
        return String(self.render() + other.render())

    def __sub__(self, other):
        # Default behavior is to treat the whole expression like one string
        return String.unquoted(self.render() + "-" + other.render())

    def __div__(self, other):
        return String.unquoted(self.render() + "/" + other.render())

    # Sass types have no notion of floor vs true division
    def __truediv__(self, other):
        return self.__div__(other)

    def __floordiv__(self, other):
        return self.__div__(other)

    def __mul__(self, other):
        return NotImplemented

    def __pos__(self):
        return String("+" + self.render())

    def __neg__(self):
        return String("-" + self.render())

    def to_dict(self):
        """Return the Python dict equivalent of this map.

        If this type can't be expressed as a map, raise.
        """
        return dict(self.to_pairs())

    def to_pairs(self):
        """Return the Python list-of-tuples equivalent of this map.  Note that
        this is different from ``self.to_dict().items()``, because Sass maps
        preserve order.

        If this type can't be expressed as a map, raise.
        """
        raise ValueError("Not a map: {0!r}".format(self))

    def render(self, compress=False):
        """Return this value's CSS representation as a string (text, i.e.
        unicode!).

        If `compress` is true, try hard to shorten the string at the cost of
        readability.
        """
        raise NotImplementedError

    def render_interpolated(self, compress=False):
        """Return this value's string representation as appropriate for
        returning from an interpolation.
        """
        return self.render(compress)


class Null(Value):
    is_null = True
    sass_type_name = 'null'

    def __init__(self, value=None):
        pass

    def __str__(self):
        return self.sass_type_name

    def __repr__(self):
        return "<{0}>".format(type(self).__name__)

    def __hash__(self):
        return hash(None)

    def __bool__(self):
        return False

    def __eq__(self, other):
        return Boolean(isinstance(other, Null))

    def __ne__(self, other):
        return Boolean(not self.__eq__(other))

    def render(self, compress=False):
        return self.sass_type_name

    def render_interpolated(self, compress=False):
        # Interpolating a null gives you nothing.
        return ''


class Undefined(Null):
    sass_type_name = 'undefined'

    def __init__(self, value=None):
        pass

    def __add__(self, other):
        return self

    def __radd__(self, other):
        return self

    def __sub__(self, other):
        return self

    def __rsub__(self, other):
        return self

    def __div__(self, other):
        return self

    def __rdiv__(self, other):
        return self

    def __truediv__(self, other):
        return self

    def __rtruediv__(self, other):
        return self

    def __floordiv__(self, other):
        return self

    def __rfloordiv__(self, other):
        return self

    def __mul__(self, other):
        return self

    def __rmul__(self, other):
        return self

    def __pos__(self):
        return self

    def __neg__(self):
        return self


class Boolean(Value):
    sass_type_name = 'bool'

    def __init__(self, value):
        self.value = bool(value)

    def __str__(self):
        return 'true' if self.value else 'false'

    def __hash__(self):
        return hash(self.value)

    def __bool__(self):
        return self.value

    def render(self, compress=False):
        if self.value:
            return 'true'
        else:
            return 'false'


class Number(Value):
    sass_type_name = 'number'

    def __init__(self, amount, unit=None, unit_numer=(), unit_denom=()):
        if isinstance(amount, Number):
            assert not unit and not unit_numer and not unit_denom
            self.value = amount.value
            self.unit_numer = amount.unit_numer
            self.unit_denom = amount.unit_denom
            return

        # Numbers with units are stored internally as a "base" unit, which can
        # involve float division, which can lead to precision errors in obscure
        # cases.  Storing the original units would only partially solve this
        # problem, because there'd still be a possible loss of precision when
        # converting in Sass-land.  Almost all of the conversion factors are
        # simple ratios of small whole numbers, so using Fraction across the
        # board preserves as much precision as possible.
        # TODO in fact, i wouldn't mind parsing Sass values as fractions of a
        # power of ten!
        # TODO this slowed the test suite down by about 10%, ha
        if isinstance(amount, (int, float)):
            amount = Fraction.from_float(amount)
        elif isinstance(amount, Fraction):
            pass
        else:
            raise TypeError("Expected number, got %r" % (amount,))

        if unit is not None:
            unit_numer = unit_numer + (unit.lower(),)

        # Cancel out any convertable units on the top and bottom
        numerator_base_units = count_base_units(unit_numer)
        denominator_base_units = count_base_units(unit_denom)

        # Count which base units appear both on top and bottom
        cancelable_base_units = {}
        for unit, count in numerator_base_units.items():
            cancelable_base_units[unit] = min(
                count, denominator_base_units.get(unit, 0))

        # Actually remove the units
        numer_factor, unit_numer = cancel_base_units(unit_numer, cancelable_base_units)
        denom_factor, unit_denom = cancel_base_units(unit_denom, cancelable_base_units)

        # And we're done
        self.unit_numer = tuple(unit_numer)
        self.unit_denom = tuple(unit_denom)
        self.value = amount * (numer_factor / denom_factor)

    def __repr__(self):
        value = self.value
        int_value = int(value)
        if value == int_value:
            value = int_value

        full_unit = ' * '.join(self.unit_numer)
        if self.unit_denom:
            full_unit += ' / '
            full_unit += ' * '.join(self.unit_denom)

            if full_unit:
                full_unit = ' ' + full_unit

        return "<{0} {1}{2}>".format(type(self).__name__, value, full_unit)

    def __hash__(self):
        return hash((self.value, self.unit_numer, self.unit_denom))

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

    def __pos__(self):
        return self

    def __neg__(self):
        return self * Number(-1)

    def __str__(self):
        return self.render()

    def __eq__(self, other):
        if not isinstance(other, Number):
            return Boolean(False)
        return self._compare(other, operator.__eq__, soft_fail=True)

    def __lt__(self, other):
        return self._compare(other, operator.__lt__)

    def __le__(self, other):
        return self._compare(other, operator.__le__)

    def __gt__(self, other):
        return self._compare(other, operator.__gt__)

    def __ge__(self, other):
        return self._compare(other, operator.__ge__)

    def _compare(self, other, op, soft_fail=False):
        if not isinstance(other, Number):
            raise TypeError("Can't compare %r and %r" % (self, other))

        # A unitless operand is treated as though it had the other operand's
        # units, and zero values can cast to anything, so in both cases the
        # units can be ignored
        if (self.is_unitless or other.is_unitless or
                self.value == 0 or other.value == 0):
            left = self
            right = other
        else:
            left = self.to_base_units()
            right = other.to_base_units()

            if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
                if soft_fail:
                    # Used for equality only, where == should never fail
                    return Boolean(False)
                else:
                    raise ValueError("Can't reconcile units: %r and %r" % (self, other))

        return Boolean(op(round(left.value, PRECISION), round(right.value, PRECISION)))

    def __pow__(self, exp):
        if not isinstance(exp, Number):
            raise TypeError("Can't raise %r to power %r" % (self, exp))
        if not exp.is_unitless:
            raise TypeError("Exponent %r cannot have units" % (exp,))

        if self.is_unitless:
            return Number(self.value ** exp.value)

        # Units can only be exponentiated to integral powers -- what's the
        # square root of 'px'?  (Well, it's sqrt(px), but supporting that is
        # a bit out of scope.)
        if exp.value != int(exp.value):
            raise ValueError("Can't raise units of %r to non-integral power %r" % (self, exp))

        return Number(
            self.value ** int(exp.value),
            unit_numer=self.unit_numer * int(exp.value),
            unit_denom=self.unit_denom * int(exp.value),
        )

    def __mul__(self, other):
        if not isinstance(other, Number):
            return NotImplemented

        amount = self.value * other.value
        numer = self.unit_numer + other.unit_numer
        denom = self.unit_denom + other.unit_denom

        return Number(amount, unit_numer=numer, unit_denom=denom)

    def __div__(self, other):
        if not isinstance(other, Number):
            return NotImplemented

        amount = self.value / other.value
        numer = self.unit_numer + other.unit_denom
        denom = self.unit_denom + other.unit_numer

        return Number(amount, unit_numer=numer, unit_denom=denom)

    def __mod__(self, other):
        if not isinstance(other, Number):
            return NotImplemented

        amount = self.value % other.value

        if self.is_unitless:
            return Number(amount)

        if not other.is_unitless:
            left = self.to_base_units()
            right = other.to_base_units()

            if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
                raise ValueError("Can't reconcile units: %r and %r" % (self, other))

        return Number(amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom)

    def __add__(self, other):
        # Numbers auto-cast to strings when added to other strings
        if isinstance(other, String):
            return String(self.render(), quotes=None) + other

        return self._add_sub(other, operator.add)

    def __sub__(self, other):
        return self._add_sub(other, operator.sub)

    def _add_sub(self, other, op):
        """Implements both addition and subtraction."""
        if not isinstance(other, Number):
            return NotImplemented

        # If either side is unitless, inherit the other side's units.  Skip all
        # the rest of the conversion math, too.
        if self.is_unitless or other.is_unitless:
            return Number(
                op(self.value, other.value),
                unit_numer=self.unit_numer or other.unit_numer,
                unit_denom=self.unit_denom or other.unit_denom,
            )

        # Likewise, if either side is zero, it can auto-cast to any units
        if self.value == 0:
            return Number(
                op(self.value, other.value),
                unit_numer=other.unit_numer,
                unit_denom=other.unit_denom,
            )
        elif other.value == 0:
            return Number(
                op(self.value, other.value),
                unit_numer=self.unit_numer,
                unit_denom=self.unit_denom,
            )

        # Reduce both operands to the same units
        left = self.to_base_units()
        right = other.to_base_units()

        if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom:
            raise ValueError("Can't reconcile units: %r and %r" % (self, other))

        new_amount = op(left.value, right.value)

        # Convert back to the left side's units
        if left.value != 0:
            new_amount = new_amount * self.value / left.value

        return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom)

    ### Helper methods, mostly used internally

    def to_base_units(self):
        """Convert to a fixed set of "base" units.  The particular units are
        arbitrary; what's important is that they're consistent.

        Used for addition and comparisons.
        """
        # Convert to "standard" units, as defined by the conversions dict above
        amount = self.value

        numer_factor, numer_units = convert_units_to_base_units(self.unit_numer)
        denom_factor, denom_units = convert_units_to_base_units(self.unit_denom)

        return Number(
            amount * numer_factor / denom_factor,
            unit_numer=numer_units,
            unit_denom=denom_units,
        )

    ### Utilities for public consumption

    @classmethod
    def wrap_python_function(cls, fn):
        """Wraps an unary Python math function, translating the argument from
        Sass to Python on the way in, and vice versa for the return value.

        Used to wrap simple Python functions like `ceil`, `floor`, etc.
        """
        def wrapped(sass_arg):
            # TODO enforce no units for trig?
            python_arg = sass_arg.value
            python_ret = fn(python_arg)
            sass_ret = cls(
                python_ret,
                unit_numer=sass_arg.unit_numer,
                unit_denom=sass_arg.unit_denom)
            return sass_ret

        return wrapped

    def to_python_index(self, length, check_bounds=True, circular=False):
        """Return a plain Python integer appropriate for indexing a sequence of
        the given length.  Raise if this is impossible for any reason
        whatsoever.
        """
        if not self.is_unitless:
            raise ValueError("Index cannot have units: {0!r}".format(self))

        ret = int(self.value)
        if ret != self.value:
            raise ValueError("Index must be an integer: {0!r}".format(ret))

        if ret == 0:
            raise ValueError("Index cannot be zero")

        if check_bounds and not circular and abs(ret) > length:
            raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length))

        if ret > 0:
            ret -= 1

        if circular:
            ret = ret % length

        return ret

    @property
    def has_simple_unit(self):
        """Returns True iff the unit is expressible in CSS, i.e., has no
        denominator and at most one unit in the numerator.
        """
        return len(self.unit_numer) <= 1 and not self.unit_denom

    def is_simple_unit(self, unit):
        """Return True iff the unit is simple (as above) and matches the given
        unit.
        """
        if self.unit_denom or len(self.unit_numer) > 1:
            return False

        if not self.unit_numer:
            # Empty string historically means no unit
            return unit == ''

        return self.unit_numer[0] == unit

    @property
    def is_unitless(self):
        return not self.unit_numer and not self.unit_denom

    def render(self, compress=False):
        if not self.has_simple_unit:
            raise ValueError("Can't express compound units in CSS: %r" % (self,))

        if self.unit_numer:
            unit = self.unit_numer[0]
        else:
            unit = ''

        value = self.value
        if compress and unit in ZEROABLE_UNITS and value == 0:
            return '0'

        if value == 0:  # -0.0 is plain 0
            value = 0

        val = ('%%0.0%df' % PRECISION) % round(value, PRECISION)
        val = val.rstrip('0').rstrip('.')

        if compress and val.startswith('0.'):
            # Strip off leading zero when compressing
            val = val[1:]

        return val + unit


class List(Value):
    """A list of other values.  May be delimited by commas or spaces.

    Lists of one item don't make much sense in CSS, but can exist in Sass.  Use ......

    Lists may also contain zero items, but these are forbidden from appearing
    in CSS output.
    """

    sass_type_name = 'list'

    def __init__(self, iterable, separator=None, use_comma=None, literal=False):
        if isinstance(iterable, List):
            iterable = iterable.value

        if (not isinstance(iterable, Iterable) or
                isinstance(iterable, six.string_types)):
            raise TypeError("Expected list, got %r" % (iterable,))

        self.value = list(iterable)

        for item in self.value:
            if not isinstance(item, Value):
                raise TypeError("Expected a Sass type, got %r" % (item,))

        # TODO remove separator argument entirely
        if use_comma is None:
            self.use_comma = separator == ","
        else:
            self.use_comma = use_comma

        self.literal = literal

    @classmethod
    def maybe_new(cls, values, use_comma=True):
        """If `values` contains only one item, return that item.  Otherwise,
        return a List as normal.
        """
        if len(values) == 1:
            return values[0]
        else:
            return cls(values, use_comma=use_comma)

    def maybe(self):
        """If this List contains only one item, return it.  Otherwise, return
        the List.
        """
        if len(self.value) == 1:
            return self.value[0]
        else:
            return self

    @classmethod
    def from_maybe(cls, values, use_comma=True):
        """If `values` appears to not be a list, return a list containing it.
        Otherwise, return a List as normal.
        """
        if values is None:
            values = []
        return values

    @classmethod
    def from_maybe_starargs(cls, args, use_comma=True):
        """If `args` has one element which appears to be a list, return it.
        Otherwise, return a list as normal.

        Mainly used by Sass function implementations that predate `...`
        support, so they can accept both a list of arguments and a single list
        stored in a variable.
        """
        if len(args) == 1:
            if isinstance(args[0], cls):
                return args[0]
            elif isinstance(args[0], (list, tuple)):
                return cls(args[0], use_comma=use_comma)

        return cls(args, use_comma=use_comma)

    def __repr__(self):
        return "<{0} {1}>".format(
            type(self).__name__,
            self.delimiter().join(repr(item) for item in self),
        )

    def __hash__(self):
        return hash((tuple(self.value), self.use_comma))

    def delimiter(self, compress=False):
        if self.use_comma:
            if compress:
                return ','
            else:
                return ', '
        else:
            return ' '

    def __len__(self):
        return len(self.value)

    def __str__(self):
        return self.render()

    def __iter__(self):
        return iter(self.value)

    def __contains__(self, item):
        return item in self.value

    def __getitem__(self, key):
        return self.value[key]

    def to_pairs(self):
        pairs = []
        for item in self:
            if len(item) != 2:
                return super(List, self).to_pairs()

            pairs.append(tuple(item))

        return pairs

    def render(self, compress=False):
        if not self.value:
            raise ValueError("Can't render empty list as CSS")

        delim = self.delimiter(compress)

        if self.literal:
            value = self.value
        else:
            # Non-literal lists have nulls stripped
            value = [item for item in self.value if not item.is_null]
            # Non-empty lists containing only nulls become nothing, just like
            # single nulls
            if not value:
                return ''

        return delim.join(
            item.render(compress=compress)
            for item in value
        )

    def render_interpolated(self, compress=False):
        return self.delimiter(compress).join(
            item.render_interpolated(compress) for item in self)

    # DEVIATION: binary ops on lists and scalars act element-wise
    def __add__(self, other):
        if isinstance(other, List):
            max_list, min_list = (self, other) if len(self) > len(other) else (other, self)
            return List([item + max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma)

        elif isinstance(other, String):
            # UN-DEVIATION: adding a string should fall back to canonical
            # behavior of string addition
            return super(List, self).__add__(other)

        else:
            return List([item + other for item in self], use_comma=self.use_comma)

    def __sub__(self, other):
        if isinstance(other, List):
            max_list, min_list = (self, other) if len(self) > len(other) else (other, self)
            return List([item - max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma)

        return List([item - other for item in self], use_comma=self.use_comma)

    def __mul__(self, other):
        if isinstance(other, List):
            max_list, min_list = (self, other) if len(self) > len(other) else (other, self)
            max_list, min_list = (self, other) if len(self) > len(other) else (other, self)
            return List([item * max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma)

        return List([item * other for item in self], use_comma=self.use_comma)

    def __div__(self, other):
        if isinstance(other, List):
            max_list, min_list = (self, other) if len(self) > len(other) else (other, self)
            return List([item / max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma)

        return List([item / other for item in self], use_comma=self.use_comma)

    def __pos__(self):
        return self

    def __neg__(self):
        return List([-item for item in self], use_comma=self.use_comma)


class Arglist(List):
    """An argument list.  Acts mostly like a list, with keyword arguments sort
    of tacked on separately, and only accessible via Python (or the Sass
    `keywords` function).
    """
    sass_type_name = 'arglist'
    keywords_retrieved = False

    def __init__(self, args, kwargs):
        self._kwargs = Map(kwargs)
        super(Arglist, self).__init__(args, use_comma=True)

    def extract_keywords(self):
        self.keywords_retrieved = True
        return self._kwargs


def _constrain(value, lb=0, ub=1):
    """Helper for Color constructors.  Constrains a value to a range."""
    if value < lb:
        return lb
    elif value > ub:
        return ub
    else:
        return value


class Color(Value):
    sass_type_name = 'color'
    original_literal = None

    def __init__(self, tokens):
        self.tokens = tokens
        self.value = (0, 0, 0, 1)
        if tokens is None:
            self.value = (0, 0, 0, 1)
        elif isinstance(tokens, Color):
            self.value = tokens.value
        else:
            raise TypeError("Can't make Color from %r" % (tokens,))

    ### Alternate constructors

    @classmethod
    def from_rgb(cls, red, green, blue, alpha=1.0, original_literal=None):
        red = _constrain(red)
        green = _constrain(green)
        blue = _constrain(blue)
        alpha = _constrain(alpha)

        self = cls.__new__(cls)  # TODO
        self.tokens = None
        # TODO really should store these things internally as 0-1, but can't
        # until stuff stops examining .value directly
        self.value = (red * 255.0, green * 255.0, blue * 255.0, alpha)

        if original_literal is not None:
            self.original_literal = original_literal

        return self

    @classmethod
    def from_hsl(cls, hue, saturation, lightness, alpha=1.0):
        hue = _constrain(hue)
        saturation = _constrain(saturation)
        lightness = _constrain(lightness)
        alpha = _constrain(alpha)

        r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation)
        return cls.from_rgb(r, g, b, alpha)

    @classmethod
    def from_hex(cls, hex_string, literal=False):
        if not hex_string.startswith('#'):
            raise ValueError("Expected #abcdef, got %r" % (hex_string,))

        if literal:
            original_literal = hex_string
        else:
            original_literal = None

        hex_string = hex_string[1:]

        # Always include the alpha channel
        if len(hex_string) == 3:
            hex_string += 'f'
        elif len(hex_string) == 6:
            hex_string += 'ff'

        # Now there should be only two possibilities.  Normalize to a list of
        # two hex digits
        if len(hex_string) == 4:
            chunks = [ch * 2 for ch in hex_string]
        elif len(hex_string) == 8:
            chunks = [
                hex_string[0:2], hex_string[2:4], hex_string[4:6], hex_string[6:8]
            ]

        rgba = [int(ch, 16) / 255 for ch in chunks]
        return cls.from_rgb(*rgba, original_literal=original_literal)

    @classmethod
    def from_name(cls, name):
        """Build a Color from a CSS color name."""
        self = cls.__new__(cls)  # TODO
        self.original_literal = name

        r, g, b, a = COLOR_NAMES[name]

        self.value = r, g, b, a
        return self

    ### Accessors

    @property
    def rgb(self):
        # TODO: deprecate, relies on internals
        return tuple(self.value[:3])

    @property
    def rgba(self):
        return (
            self.value[0] / 255,
            self.value[1] / 255,
            self.value[2] / 255,
            self.value[3],
        )

    @property
    def hsl(self):
        rgba = self.rgba
        h, l, s = colorsys.rgb_to_hls(*rgba[:3])
        return h, s, l

    @property
    def alpha(self):
        return self.value[3]

    @property
    def rgba255(self):
        return (
            int(self.value[0] * 1 + 0.5),
            int(self.value[1] * 1 + 0.5),
            int(self.value[2] * 1 + 0.5),
            int(self.value[3] * 255 + 0.5),
        )

    def __repr__(self):
        return "<{0} {1}>".format(type(self).__name__, self.render())

    def __hash__(self):
        return hash(self.value)

    def __eq__(self, other):
        if not isinstance(other, Color):
            return Boolean(False)

        # Scale channels to 255 and round to integers; this allows only 8-bit
        # color, but Ruby sass makes the same assumption, and otherwise it's
        # easy to get lots of float errors for HSL colors.
        left = tuple(round(n) for n in self.rgba255)
        right = tuple(round(n) for n in other.rgba255)
        return Boolean(left == right)

    def __add__(self, other):
        if isinstance(other, (Color, Number)):
            return self._operate(other, operator.add)
        else:
            return super(Color, self).__add__(other)

    def __sub__(self, other):
        if isinstance(other, (Color, Number)):
            return self._operate(other, operator.sub)
        else:
            return super(Color, self).__sub__(other)

    def __mul__(self, other):
        if isinstance(other, (Color, Number)):
            return self._operate(other, operator.mul)
        else:
            return super(Color, self).__mul__(other)

    def __div__(self, other):
        if isinstance(other, (Color, Number)):
            return self._operate(other, operator.div)
        else:
            return super(Color, self).__div__(other)

    def _operate(self, other, op):
        if isinstance(other, Number):
            if not other.is_unitless:
                raise ValueError("Expected unitless Number, got %r" % (other,))

            other_rgb = (other.value,) * 3
        elif isinstance(other, Color):
            if self.alpha != other.alpha:
                raise ValueError("Alpha channels must match between %r and %r"
                    % (self, other))

            other_rgb = other.rgb
        else:
            raise TypeError("Expected Color or Number, got %r" % (other,))

        new_rgb = [
            min(255., max(0., op(left, right)))
            # for from_rgb
                / 255.
            for (left, right) in zip(self.rgb, other_rgb)
        ]

        return Color.from_rgb(*new_rgb, alpha=self.alpha)

    def render(self, compress=False):
        """Return a rendered representation of the color.  If `compress` is
        true, the shortest possible representation is used; otherwise, named
        colors are rendered as names and all others are rendered as hex (or
        with the rgba function).
        """

        if not compress and self.original_literal:
            return self.original_literal

        candidates = []

        # TODO this assumes CSS resolution is 8-bit per channel, but so does
        # Ruby.
        r, g, b, a = self.value
        r, g, b = int(round(r)), int(round(g)), int(round(b))

        # Build a candidate list in order of preference.  If `compress` is
        # True, the shortest candidate is used; otherwise, the first candidate
        # is used.

        # Try color name
        key = r, g, b, a
        if key in COLOR_LOOKUP:
            candidates.append(COLOR_LOOKUP[key])

        if a == 1:
            # Hex is always shorter than function notation
            if all(ch % 17 == 0 for ch in (r, g, b)):
                candidates.append("#%1x%1x%1x" % (r // 17, g // 17, b // 17))
            else:
                candidates.append("#%02x%02x%02x" % (r, g, b))
        else:
            # Can't use hex notation for RGBA
            if compress:
                sp = ''
            else:
                sp = ' '
            candidates.append("rgba(%d,%s%d,%s%d,%s%.6g)" % (r, sp, g, sp, b, sp, a))

        if compress:
            return min(candidates, key=len)
        else:
            return candidates[0]


# TODO be unicode-clean and delete this nonsense
DEFAULT_STRING_ENCODING = "utf8"


class String(Value):
    """Represents both CSS quoted string values and CSS identifiers (such as
    `left`).

    Makes no distinction between single and double quotes, except that the same
    quotes are preserved on string literals that pass through unmodified.
    Otherwise, double quotes are used.
    """

    sass_type_name = 'string'

    bad_identifier_rx = re.compile('[^-_a-zA-Z\x80-\U0010FFFF]')

    def __init__(self, value, quotes='"', literal=False):
        if isinstance(value, String):
            # TODO unclear if this should be here, but many functions rely on
            # it
            value = value.value
        elif isinstance(value, Number):
            # TODO this may only be necessary in the case of __radd__ and
            # number values
            value = six.text_type(value)

        if isinstance(value, six.binary_type):
            warn(FutureWarning(
                "String got a bytes type {0!r} "
                "-- this will no longer be supported in pyScss 2.0"
                .format(value)
            ))
            value = value.decode(DEFAULT_STRING_ENCODING)

        if not isinstance(value, six.text_type):
            raise TypeError("Expected string, got {0!r}".format(value))

        self.value = value
        self.quotes = quotes
        # TODO this isn't quite used yet
        if literal:
            self.original_literal = value
        else:
            self.original_literal = None

    @classmethod
    def unquoted(cls, value, literal=False):
        """Helper to create a string with no quotes."""
        return cls(value, quotes=None, literal=literal)

    def __hash__(self):
        return hash(self.value)

    def __repr__(self):
        if self.quotes:
            quotes = '(' + self.quotes + ')'
        else:
            quotes = ''
        return "<{0}{1} {2!r}>".format(
            type(self).__name__, quotes, self.value)

    def __eq__(self, other):
        return Boolean(isinstance(other, String) and self.value == other.value)

    def __add__(self, other):
        if isinstance(other, String):
            other_value = other.value
        else:
            other_value = other.render()

        return String(
            self.value + other_value,
            quotes='"' if self.quotes else None)

    def __mul__(self, other):
        # DEVIATION: Ruby Sass doesn't do this, because Ruby doesn't.  But
        # Python does, and in Ruby Sass it's just fatal anyway.
        if not isinstance(other, Number):
            return super(String, self).__mul__(other)

        if not other.is_unitless:
            raise TypeError("Can only multiply strings by unitless numbers")

        n = other.value
        if n != int(n):
            raise ValueError("Can only multiply strings by integers")

        return String(self.value * int(other.value), quotes=self.quotes)

    def _escape_character(self, match):
        """Given a single character, return it appropriately CSS-escaped."""
        # TODO is there any case where we'd want to use unicode escaping?
        # TODO unsure if this works with newlines
        return '\\' + match.group(0)

    def _is_name_start(self, ch):
        if ch == '_':
            return True
        if ord(ch) >= 128:
            return True
        if ch in string.ascii_letters:
            return True
        return False

    def render(self, compress=False):
        # TODO should preserve original literals here too -- even the quotes.
        # or at least that's what sass does.
        # Escape and add quotes as appropriate.
        if self.quotes is None:
            # If you deliberately construct a bareword with bogus CSS in it,
            # you're assumed to know what you're doing
            return self.value
        else:
            return self._render_quoted()

    def render_interpolated(self, compress=False):
        # Always render without quotes
        return self.value

    def _render_bareword(self):
        # TODO this is currently unused, and only implemented due to an
        # oversight, but would make for a much better implementation of
        # escape()

        # This is a bareword, so almost anything outside \w needs escaping
        ret = self.value
        ret = self.bad_identifier_rx.sub(self._escape_character, ret)

        # Also apply some minor quibbling rules about how barewords can
        # start: with a "name start", an escape, a hyphen followed by one
        # of those, or two hyphens.
        if not ret:
            # TODO is an unquoted empty string allowed to be rendered?
            pass
        elif ret[0] == '-':
            if ret[1] in '-\\' or self._is_name_start(ret[1]):
                pass
            else:
                # Escape the second character
                # TODO what if it's a digit, oops
                ret = ret[0] + '\\' + ret[1:]
        elif ret[0] == '\\' or self._is_name_start(ret[0]):
            pass
        else:
            # Escape the first character
            # TODO what if it's a digit, oops
            ret = '\\' + ret

        return ret

    def _render_quoted(self):
        # Strictly speaking, the only things we need to quote are the quotes
        # themselves, backslashes, and newlines.
        # TODO Ruby Sass takes backslashes in barewords literally, but treats
        # backslashes in quoted strings as escapes -- their mistake?
        # TODO In Ruby Sass, generated strings never have single quotes -- but
        # neither do variable interpolations, so I'm not sure what they're
        # doing
        quote = self.quotes

        ret = self.value
        ret = ret.replace('\\', '\\\\')
        ret = ret.replace(quote, '\\' + quote)
        # Note that a literal newline is ignored when escaped, so we have to
        # use the codepoint instead.  But we'll leave the newline as well, to
        # aid readability.
        ret = ret.replace('\n', '\\a\\\n')
        return quote + ret + quote


# TODO this needs to pretend the url(...) is part of the string for all string
# operations -- even the quotes!  alas.
# TODO recasting a function to a String will lose the function part?  whoops.
# maybe .value should just be, uh, the literal value instead of the insides???
class Function(String):
    """Function call pseudo-type, which crops up frequently in CSS as a string
    marker.  Acts mostly like a string, but has a function name and parentheses
    around it.
    """
    def __init__(self, string, function_name, quotes='"', literal=False):
        super(Function, self).__init__(string, quotes=quotes, literal=literal)
        self.function_name = function_name

    def render(self, compress=False):
        return "{0}({1})".format(
            self.function_name,
            super(Function, self).render(compress),
        )

    def render_interpolated(self, compress=False):
        return "{0}({1})".format(
            self.function_name,
            super(Function, self).render_interpolated(compress),
        )


class Url(Function):
    # Bare URLs may not contain quotes, parentheses, or unprintables.  Quoted
    # URLs may, of course, contain whatever they like.
    # Ref: http://dev.w3.org/csswg/css-syntax-3/#consume-a-url-token0
    bad_identifier_rx = re.compile("[$'\"()\\x00-\\x08\\x0b\\x0e-\\x1f\\x7f]")

    def __init__(self, string, **kwargs):
        super(Url, self).__init__(string, 'url', **kwargs)

    def render(self, compress=False):
        if self.quotes is None:
            return self.render_interpolated(compress)
        else:
            inside = self._render_quoted()
            return "url(" + inside + ")"

    def render_interpolated(self, compress=False):
        # Always render without quotes.
        # When doing that, we need to escape some stuff to make sure the result
        # is valid CSS.
        inside = self.bad_identifier_rx.sub(
            self._escape_character, self.value)

        return "url(" + inside + ")"


class Map(Value):
    sass_type_name = 'map'

    def __init__(self, pairs, index=None):
        self.pairs = tuple(pairs)

        if index is None:
            self.index = {}
            for key, value in pairs:
                self.index[key] = value
        else:
            self.index = index

    def __repr__(self):
        return "<Map: (%s)>" % (", ".join("%s: %s" % pair for pair in self.pairs),)

    def __hash__(self):
        return hash(self.pairs)

    def __len__(self):
        return len(self.pairs)

    def __iter__(self):
        return iter(self.pairs)

    def __getitem__(self, index):
        return List(self.pairs[index], use_comma=True)

    def __eq__(self, other):
        try:
            return self.pairs == other.to_pairs()
        except ValueError:
            return NotImplemented

    def to_dict(self):
        return self.index

    def to_pairs(self):
        return self.pairs

    def render(self, compress=False):
        raise TypeError("Cannot render map %r as CSS" % (self,))


def expect_type(value, types, unit=any):
    if not isinstance(value, types):
        if isinstance(types, type):
            types = (type,)
        sass_type_names = list(set(t.sass_type_name for t in types))
        sass_type_names.sort()

        # Join with commas in English fashion
        if len(sass_type_names) == 1:
            sass_type = sass_type_names[0]
        elif len(sass_type_names) == 2:
            sass_type = ' or '.join(sass_type_names)
        else:
            sass_type = ', '.join(sass_type_names[:-1])
            sass_type += ', or ' + sass_type_names[-1]

        raise TypeError("Expected %s, got %r" % (sass_type, value))

    if unit is not any and isinstance(value, Number):
        if unit is None and not value.is_unitless:
            raise ValueError("Expected unitless number, got %r" % (value,))

        elif unit == '%' and not (
                value.is_unitless or value.is_simple_unit('%')):
            raise ValueError("Expected unitless number or percentage, got %r" % (value,))