summaryrefslogtreecommitdiff
path: root/scss/types.py
blob: 2944c716755f4fb2def9286fb2d3a05344259a0e (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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import operator

import six

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


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

class ParserValue(object):
    def __init__(self, value):
        self.value = value


class Value(object):
    is_null = False
    sass_type_name = u'unknown'

    def __repr__(self):
        return '<%s(%s)>' % (self.__class__.__name__, repr(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__()

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

    # 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

    # 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(self.render() + "-" + other.render())

    def __div__(self, other):
        return String(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 render(self, compress=False):
        return self.__str__()


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

    def __init__(self, value=None):
        pass

    def __str__(self):
        return self.sass_type_name

    def __repr__(self):
        return "<%s()>" % (self.__class__.__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


class Undefined(Null):
    sass_type_name = u'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 = u'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 = u'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

        if not isinstance(amount, (int, float)):
            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):
        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 '<%s(%r%s)>' % (self.__class__.__name__, self.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 __neg__(self):
        return self * Number(-1)

    def __pos__(self):
        return self

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

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

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

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

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

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

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

        left = self.to_base_units()
        right = other.to_base_units()

        if (left.value != 0 or left.unit_numer or left.unit_denom) and (right.value != 0 or right.unit_numer or right.unit_denom):
            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 op(round(left.value, 5), round(right.value, 5))

    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 __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,
            )

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

        if (left.value != 0 or left.unit_numer or left.unit_denom) and (right.value != 0 or right.unit_numer or right.unit_denom):
            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=sass_arg.unit)
            return sass_ret

        return wrapped

    @property
    def unit(self):
        if self.unit_denom:
            raise TypeError

        if not self.unit_numer:
            return ''

        if len(self.unit_numer) != 1:
            raise TypeError

        return self.unit_numer[0]

    @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

    @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,))

        unit = self.unit

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

        val = "%0.05f" % round(self.value, 5)
        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 = u'list'

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

        if not isinstance(iterable, (list, tuple)):
            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

    @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 "<List(%r, %r)>" % (
            self.value,
            self.delimiter(compress=True),
        )

    def __hash__(self):
        return hash((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 __getitem__(self, key):
        return self.value[key]

    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(List, self).__mul__(other)

        if not other.is_unitless:
            raise TypeError("Can only multiply %s by %s" % (self.__class__.__name__, other.__class__.__name__))

    def render(self, compress=False):
        delim = self.delimiter(compress)

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


class Color(Value):
    sass_type_name = u'color'

    HEX2RGBA = {
        9: lambda c: (int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16), int(c[7:9], 16)),
        7: lambda c: (int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16), 1.0),
        5: lambda c: (int(c[1] * 2, 16), int(c[2] * 2, 16), int(c[3] * 2, 16), int(c[4] * 2, 16)),
        4: lambda c: (int(c[1] * 2, 16), int(c[2] * 2, 16), int(c[3] * 2, 16), 1.0),
    }

    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, ParserValue):
            hex = tokens.value
            self.original_literal = hex
            self.value = self.HEX2RGBA[len(hex)](hex)
        elif isinstance(tokens, Color):
            self.value = tokens.value
        elif isinstance(tokens, (list, tuple)):
            c = tokens[:4]
            r = 255.0, 255.0, 255.0, 1.0
            c = [0.0 if c[i] < 0 else r[i] if c[i] > r[i] else c[i] for i in range(4)]
            self.value = tuple(c)
        else:
            raise TypeError("Can't make Color from %r" % (tokens,))

    ### Alternate constructors

    @classmethod
    def from_rgb(cls, red, green, blue, alpha=1.0):
        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)
        return self

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

        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)

    @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):
        return tuple(self.value[:3])

    @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 '<%s(%s)>' % (self.__class__.__name__, repr(self.value))

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

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

        # Round to the nearest 5 digits for comparisons; corresponds roughly to
        # 16 bits per channel, the most that generally matters.  Otherwise
        # float errors make equality fail for HSL colors.
        left = tuple(round(n, 5) for n in self.value)
        right = tuple(round(n, 5) for n in other.value)
        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%.2g)" % (r, sp, g, sp, b, sp, a))

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


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 = u'string'

    def __init__(self, value, quotes='"'):
        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 = str(value)

        if isinstance(value, six.binary_type):
            # TODO this blows!  need to be unicode-clean so this never happens.
            value = value.decode('ascii')

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

        # TODO probably disallow creating an unquoted string outside a
        # set of chars like [-a-zA-Z0-9]+

        if six.PY3:
            self.value = value
        else:
            # TODO not unicode clean on 2 yet...
            self.value = value.encode('ascii')
        self.quotes = quotes

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

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

    def __str__(self):
        if self.quotes:
            return self.quotes + escape(self.value) + self.quotes
        else:
            return self.value

    def __repr__(self):
        if self.quotes != '"':
            quotes = ', quotes=%r' % self.quotes
        else:
            quotes = ''
        return '<%s(%s%s)>' % (self.__class__.__name__, repr(self.value), quotes)

    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 render(self, compress=False):
        return self.__str__()


### XXX EXPERIMENTAL XXX
class Map(Value):
    sass_type_name = u'map'

    def __init__(self, pairs):
        self.pairs = pairs
        self.index = {}
        for key, value in pairs:
            self.index[key] = value

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

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

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

    def get_by_key(self, key):
        return self.index[key]

    def get_by_pos(self, key):
        return self.pairs[key][1]

    def render(self, compress=False):
        raise TypeError("maps cannot be rendered as CSS")