aboutsummaryrefslogtreecommitdiff
path: root/thcolor/decoders.py
blob: cc741015f7a05d549d7307edcc8f9a97eeb1363d (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
#!/usr/bin/env python3
# *****************************************************************************
# Copyright (C) 2019-2022 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the thcolor project, which is MIT-licensed.
# *****************************************************************************
""" Function and data reference. """

import re as _re

from abc import ABCMeta as _ABCMeta
from collections.abc import Mapping as _Mapping
from enum import auto as _auto, Enum as _Enum
from typing import (
    Any as _Any, Optional as _Optional, Union as _Union,
    Sequence as _Sequence, Tuple as _Tuple, List as _List,
)
from inspect import getfullargspec as _getfullargspec
from itertools import zip_longest as _zip_longest

from .angles import Angle as _Angle
from .colors import (
    Color as _Color, HWBColor as _HWBColor, SRGBColor as _SRGBColor,
)
from .angles import (
    DegreesAngle as _DegreesAngle, GradiansAngle as _GradiansAngle,
    RadiansAngle as _RadiansAngle, TurnsAngle as _TurnsAngle,
)
from .errors import ColorExpressionSyntaxError as _ColorExpressionSyntaxError
from .utils import factor as _factor

__all__ = [
    'ColorDecoder', 'MetaColorDecoder',
    'alias', 'fallback',
]

_NO_DEFAULT_VALUE = type('_NO_DEFAULT_VALUE_TYPE', (), {})()


def _canonicalkey(x):
    """ Get a canonical key for the decoder mapping. """

    return str(x).replace('-', '_').casefold()


def _issubclass(cls, types):
    """ Check if ``cls`` is a subclass of ``types``.

        Until Python 3.10, this function is not aware of the special
        types available in the standard ``typing`` module; this function
        aims at fixing this for Python <= 3.9.
    """

    # Check if is a special case from typing that we know of.

    try:
        origin = types.__origin__
    except AttributeError:
        if types is _Any:
            return True
    else:
        if origin is _Union or origin is _Optional:
            return any(_issubclass(cls, type_) for type_ in types.__args__)

    # If ``types`` is any iterable type (tuple, list, you name it),
    # then we check if the class is a subclass of at least one element
    # in the iterable.

    try:
        types_iter = iter(types)
    except TypeError:
        pass
    else:
        return any(_issubclass(cls, type_) for type_ in types_iter)

    # We default on the base ``issubclass`` from here.

    try:
        return issubclass(cls, types)
    except TypeError:
        return False


def _isinstance(value, types):
    """ Check if ``cls`` is a subclass of ``types``.

        Until Python 3.10, this function is not aware of the special
        types available in the standard ``typing`` module; this function
        aims at fixing this for Python <= 3.9.
    """

    return _issubclass(type(value), types)


def _get_args(func) -> _Sequence[_Tuple[str, _Any, _Any]]:
    """ Get the arguments from a function in order to
        call it using optional or make an alias.

        Each argument is returned as a tuple containing:

            * The name of the argument.
            * The type of the argument.
            * The default value of the argument;
            ``_NO_DEFAULT_VALUE`` if the argument has no default
            value.

        In case an argument is keyword-only with no default
        value, the function will raise an exception.
    """

    # TODO: manage functions with variable positional arguments.

    argspec = _getfullargspec(func)
    try:
        kwarg = next(
            arg
            for arg in argspec.kwonlyargs
            if arg not in (argspec.kwonlydefaults or ())
        )
    except StopIteration:
        pass
    else:
        raise ValueError(
            f'keyword-only argument {kwarg} has no default value',
        )

    annotations = getattr(func, '__annotations__', {})

    argnames = argspec.args
    argtypes = [annotations.get(name) for name in argnames]
    argdefaultvalues = list(argspec.defaults or ())
    argdefaultvalues = (
        [_NO_DEFAULT_VALUE] * (
            len(argspec.args or ()) - len(argdefaultvalues)
        )
        + argdefaultvalues
    )

    return list(zip(argnames, argtypes, argdefaultvalues))


def _make_function(func, name: str, args: _Optional[_Sequence[_Any]]):
    """ Create a function calling another.

        This function will rearrange the given positional
        arguments with the given argument order ``args``.

        It will also set the default value and annotations of
        the previous function, rearranged using the given
        function.
    """

    # Here, we get the variables for the base function call.
    # The resulting variables are the following:
    #
    #  * ``proxy_args``: the proxy arguments as (name, type, defvalue) tuples.
    #  * ``args_index``: a args index -> proxy index correspondance.

    args_spec = _get_args(func)
    args_index: _List[_Optional[int]]

    if not args:
        args_index = list(range(len(args_spec)))
        proxy_args = args_spec
    else:
        args_names = [name for (name, _, _) in args_spec]

        args_index = [None] * len(args_spec)
        proxy_args = []

        for proxy_index_i, arg in enumerate(args):
            try:
                index = args_names.index(arg)
            except ValueError:
                raise ValueError(
                    f'{arg!r} is not an argument of the aliased function'
                )

            args_index[index] = proxy_index_i
            proxy_args.append(args_spec[index])

    # We want to check that no value without a default value was
    # left unspecified.

    for (aname, _, adefvalue), proxy_index in zip(args_spec, args_index):
        if proxy_index is None and adefvalue is _NO_DEFAULT_VALUE:
            raise ValueError(
                f'{aname!r} is left without value in the aliased function',
            )

    # Produce the function code.

    locals_ = {
        '__func': func,
    }

    def _iter_proxy_args(d, args):
        # First, obtain the index of the last optional argument from the
        # end, because even arguments with default values before
        # mandatory arguments cannot have a default value exposed in Python.
        #
        # Then, yield the arguments.

        try:
            mandatory_until = max(
                index for index, (_, _, adefvalue) in enumerate(args)
                if adefvalue is _NO_DEFAULT_VALUE
            )
        except ValueError:
            mandatory_until = -1

        for index, (aname, atype, adefvalue) in enumerate(args):
            atypename = None
            adefvaluename = None

            if atype is not None:
                atypename = f'__type{index}'
                d[atypename] = atype

            if index > mandatory_until and adefvalue is not _NO_DEFAULT_VALUE:
                adefvaluename = f'__value{index}'
                d[adefvaluename] = adefvalue

            yield f'{aname}' + (
                (
                    f': {atypename} = {adefvaluename}',
                    f': {atypename}',
                )[adefvaluename is None],
                (f'={adefvaluename}', '')[adefvaluename is None],
            )[atypename is None]

    def _iter_final_args(d, args_spec, arg_indexes):
        for index, ((aname, _, adefvalue), p_index) in enumerate(
            zip(args_spec, arg_indexes),
        ):
            if p_index is None:
                defvaluename = f'__defvalue{index}'
                d[defvaluename] = adefvalue
                yield defvaluename
            else:
                yield aname

    proxy_args_s = ', '.join(_iter_proxy_args(locals_, proxy_args))
    final_args_s = ', '.join(_iter_final_args(locals_, args_spec, args_index))
    keys = ', '.join(locals_.keys())

    code = (
        f'def __define_alias({keys}):\n'
        f'  def {name}({proxy_args_s}):\n'
        f'    return __func({final_args_s})\n'
        f'  return {name}\n'
        '\n'
        f'__func = __define_alias({keys})\n'
    )

    exec(code, {}, locals_)
    func = locals_['__func']

    return func


def _ncol_func(
    angle: _Angle,
    whiteness: _Union[int, float] = 0,
    blackness: _Union[int, float] = 0,
):
    return _HWBColor(
        hue=angle,
        whiteness=_factor(whiteness),
        blackness=_factor(blackness),
    )


# ---
# Lexer.
# ---


class _ColorExpressionTokenType(_Enum):
    """ Token type. """

    NAME = _auto()
    ANGLE = _auto()
    PERCENTAGE = _auto()
    INTEGER = _auto()
    FLOAT = _auto()
    NCOL = _auto()
    HEX = _auto()
    EMPTY = _auto()
    CALL_START = _auto()
    CALL_END = _auto()

    # Not generated by the lexer.
    CALL = _auto()


class _ColorExpressionToken:
    """ A token as expressed by the color expression lexer. """

    __slots__ = ('_type', '_name', '_value', '_column', '_rawtext')

    TYPE_NAME = _ColorExpressionTokenType.NAME
    TYPE_ANGLE = _ColorExpressionTokenType.ANGLE
    TYPE_PERCENTAGE = _ColorExpressionTokenType.PERCENTAGE
    TYPE_INTEGER = _ColorExpressionTokenType.INTEGER
    TYPE_FLOAT = _ColorExpressionTokenType.FLOAT
    TYPE_NCOL = _ColorExpressionTokenType.NCOL
    TYPE_HEX = _ColorExpressionTokenType.HEX
    TYPE_EMPTY = _ColorExpressionTokenType.EMPTY
    TYPE_CALL_START = _ColorExpressionTokenType.CALL_START
    TYPE_CALL_END = _ColorExpressionTokenType.CALL_END

    # Not generated by the lexer.
    TYPE_CALL = _ColorExpressionTokenType.CALL

    def __init__(
        self,
        type_: _ColorExpressionTokenType,
        name=None,
        value=None,
        column=None,
        rawtext=None,
    ):
        self._type = type_
        self._name = name
        self._value = value
        self._column = column
        self._rawtext = rawtext

    def __repr__(self):
        args = [f'type_=TYPE_{self._type.name}']
        if self._name is not None:
            args.append(f'name={self._name!r}')
        if self._value is not None:
            args.append(f'value={self._value!r}')
        if self._column is not None:
            args.append(f'column={self._column!r}')
        if self._rawtext is not None:
            args.append(f'rawtext={self._rawtext!r}')

        return f'{self.__class__.__name__}({", ".join(args)})'

    @property
    def type_(self):
        """ Token type. """

        return self._type

    @property
    def name(self):
        """ Token name. """

        return self._name

    @property
    def value(self):
        """ Token value. """

        return self._value

    @property
    def column(self):
        """ Column at which the token is located. """

        return self._column

    @property
    def rawtext(self):
        """ Raw text for decoding. """

        return self._rawtext


_colorexpressionpattern = _re.compile(
    r"""
    \s*
    (?P<arg>
        (
            (?P<agl>
                (?P<agl_sign> [+-]?)
                (?P<agl_val> ([0-9]+(\.[0-9]*)?|[0-9]*\.[0-9]+)) \s*
                (?P<agl_typ>deg|grad|rad|turns?)
            )
            | (?P<per>
                (?P<per_val>[+-]? [0-9]+(\.[0-9]*)? | [+-]? \.[0-9]+)
                \s* \%
            )
            | (?P<int_val>[+-]? [0-9]+)
            | (?P<flt_val>[+-]? [0-9]+\.[0-9]* | [+-]? \.[0-9]+)
            | (?P<ncol>[RYGCBM] [0-9]{0,2} (\.[0-9]*)?)
            | (
                \# (?P<hex>
                    [0-9a-f]{3} | [0-9a-f]{4}
                    | [0-9a-f]{6} | [0-9a-f]{8}
                )
            )
            | (?P<name> [a-z0-9_-]+)
            |
        ) \s* (?P<sep>,|/|\s|\(|\)|$)
    )
    \s*
    """,
    _re.VERBOSE | _re.I | _re.M,
)


def _get_color_tokens(string: str, extended_hex: bool = False):
    """ Get color tokens.

        :param string: The string to get the color tokens from.
        :param extended_hex: Whether 4 or 8-digit hex colors are
                             allowed (``True``) or not (``False``).
    """

    start: int = 0
    was_call_end: bool = False

    while string:
        match = _colorexpressionpattern.match(string)
        if match is None:
            s = f'{string[:17]}...' if len(string) > 20 else string
            raise _ColorExpressionSyntaxError(
                f'syntax error near {s!r}',
                column=start,
            )

        result = match.groupdict()
        column = start + match.start('arg')

        is_call_end = False

        if result['name']:
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_NAME,
                value=result['name'],
                column=column,
            )
        elif result['agl'] is not None:
            value = float(result['agl_sign'] + result['agl_val'])
            typ = result['agl_typ']
            if typ == 'deg':
                value = _DegreesAngle(value)
            elif typ == 'rad':
                value = _RadiansAngle(value)
            elif typ == 'grad':
                value = _GradiansAngle(value)
            elif typ in ('turn', 'turns'):
                value = _TurnsAngle(value)
            else:
                raise NotImplementedError

            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_ANGLE,
                value=value,
                column=column,
                rawtext=result['agl'],
            )
        elif result['per'] is not None:
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_PERCENTAGE,
                value=float(result['per_val']) / 100,
                column=column,
                rawtext=result['per'],
            )
        elif result['int_val'] is not None:
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_INTEGER,
                value=int(result['int_val']),
                column=column,
                rawtext=result['int_val'],
            )
        elif result['flt_val'] is not None:
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_FLOAT,
                value=float(result['flt_val']),
                column=column,
                rawtext=result['flt_val'],
            )
        elif result['ncol'] is not None:
            letter = result['ncol'][0]
            number = float(result['ncol'][1:])

            if number < 0 or number >= 100:
                yield _ColorExpressionToken(
                    _ColorExpressionToken.TYPE_NAME,
                    value=result['ncol'],
                    column=column,
                )
            else:
                yield _ColorExpressionToken(
                    _ColorExpressionToken.TYPE_NCOL,
                    value=_DegreesAngle(
                        'RYGCBM'.find(letter) * 60 + number / 100 * 60
                    ),
                    column=column,
                    rawtext=result['ncol'],
                )
        elif result['hex'] is not None:
            value_s = result['hex']
            if len(value_s) in (4, 8) and not extended_hex:
                raise _ColorExpressionSyntaxError(
                    f'extended hex values are forbidden: {"#" + value_s!r}',
                    column=start,
                )

            if len(value_s) <= 4:
                value_s = ''.join(map(lambda x: x + x, value_s))

            r = int(value_s[0:2], 16)
            g = int(value_s[2:4], 16)
            b = int(value_s[4:6], 16)
            a = int(value_s[6:8], 16) / 255.0 if len(value_s) == 8 else 1.0

            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_HEX,
                value=_SRGBColor.frombytes(r, g, b, a),
                column=column,
                rawtext='#' + result['hex'],
            )
        else:
            # ``was_call_end`` hack: take ``func(a, b) / c`` for example.
            # By default, it is tokenized as the following:
            #
            #  * name 'func'
            #  * call start
            #  * name 'a'
            #  * name 'b'
            #  * call end
            #  * empty arg [1]
            #  * name 'c'
            #
            # The empty arg at [1] is tokenized since an argument could
            # directly be after the right parenthesis. However, we do not
            # want this to be considered an empty arg, so we ignore empty
            # args right after call ends.
            #
            # Note that ``func(a, b) / / c`` will still contain an empty
            # argument before name 'c'.

            if not was_call_end:
                yield _ColorExpressionToken(
                    _ColorExpressionToken.TYPE_EMPTY,
                    column=column,
                    rawtext='',
                )

        sep = result['sep']
        column = start + match.start('sep')

        if sep == '(':
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_CALL_START,
                column=column,
                rawtext=sep,
            )
        elif sep == ')':
            is_call_end = True
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_CALL_END,
                column=column,
                rawtext=sep,
            )

        start += match.end()
        string = string[match.end():]
        was_call_end = is_call_end


# ---
# Base decoder classes.
# ---

def fallback(value: _Union[_Color, _Angle, int, float]):
    """ Decorator for setting a fallback value on a function.

        When a function is used as a symbol instead of a function,
        by default, it yields that it is callable and should be
        accompanied with arguments.

        Using this decorator on a function makes it to be evaluated
        as a color in this case.
    """

    if not isinstance(value, (_Color, _Angle, int, float)):
        raise ValueError(
            'fallback value should be a color, an angle or a number, '
            f'is {value!r}',
        )

    def decorator(func):
        func.__fallback_value__ = value
        return func

    return decorator


class alias:
    """ Define an alias for a function. """

    __slots__ = ('_name', '_args')

    def __init__(self, name: str, args: _Sequence[str] = ()):
        self._name = name
        self._args = tuple(args)

        if len(self._args) != len(set(self._args)):
            raise ValueError('arguments should be unique')
        if any(not x or not isinstance(x, str) for x in self._args):
            raise ValueError('all arguments should be non-empty strings')

    @property
    def name(self):
        return self._name

    @property
    def args(self) -> _Sequence[str]:
        return self._args


class ColorDecoder(_Mapping):
    """ Base color decoder.

        This color decoder behaves as a mapping returning syntax elements,
        with the additional properties controlling its behaviour.

        The properties defined at class definition time are the following:

        ``__mapping__``

            Defines the base mapping that is copied at the
            instanciation of each class.

        ``__ncol_support__``

            Defines whether natural colors (NCol) are
            supported while decoding or not.

        ``__extended_hex_support__``

            Defines whether 4 or 8-digit
            hexadecimal colors (starting with a '#') are allowed or not.

        ``__defaults_to_netscape_color``

            Defines whether color decoding
            defaults to Netscape color parsing or not.

        These properties cannot be changed at runtime, although they might
        be in a future version of thcolor.
    """

    __slots__ = ('_mapping',)
    __mapping__: _Mapping = {}
    __ncol_support__: bool = False
    __extended_hex_support__: bool = False
    __defaults_to_netscape_color__: bool = True

    def __init__(self):
        cls = self.__class__

        mapping = {}
        for key, value in cls.__mapping__.items():
            mapping[_canonicalkey(key)] = value

        self._mapping = mapping
        self._ncol_support = cls.__ncol_support__
        self._extended_hex_support = cls.__extended_hex_support__
        self._defaults_to_netscape_color = cls.__defaults_to_netscape_color__

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError

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

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

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

    def __repr__(self):
        return f'{self.__class__.__name__}()'

    def decode(
        self,
        expr: str,
        prefer_colors: bool = False,
        prefer_angles: bool = False,
    ) -> _Sequence[_Optional[_Union[_Color, _Angle, int, float]]]:
        """ Decode a color expression.

            When top-level result(s) are not colors and colors are
            actually expected if possible to obtain, the caller should
            set ``prefer_colors`` to ``True`` in order for top-level
            conversions to take place.

            Otherwise, when top-level result(s) are not angles and angles
            are actually expected if possible to obtain, the caller should
            set ``prefer_angles`` to ``True`` in order for top-level
            conversions to take place.
        """

        global _color_pattern

        ncol_support = bool(self._ncol_support)
        extended_hex_support = bool(self._extended_hex_support)
        defaults_to_netscape = bool(self._defaults_to_netscape_color)

        # Parsing stage; the results will be in ``current``.
        #
        # * ``stack``: the stack of current values.
        # * ``func_stack``: the function name or special type, as tokens.
        #   Accepted token types here are ``NAME`` and ``NCOL``.
        # * ``implicit_stack``: when the current function is an implicit
        #   one, this stack contains the arguments left to read in this
        #   implicit function.
        # * ``current``: the current list of elements, which is put on
        #   top of the stack when a call is started and is popped out of
        #   the top of the stack when a call is ended.

        stack: _List[_List[_ColorExpressionToken]] = []
        func_stack: _List[_ColorExpressionToken] = []
        implicit_stack: _List[int] = []
        current: _List[_ColorExpressionToken] = []

        def _get_parent_func():
            """ Get the parent function name for exceptions. """

            if not func_stack:
                return None
            if func_stack[0].type_ == _ColorExpressionToken.TYPE_NCOL:
                return '<implicit ncol function>'
            return func_stack[0].value

        token_iter = _get_color_tokens(
            expr,
            extended_hex=extended_hex_support,
        )
        for token in token_iter:
            if (
                token.type_ == _ColorExpressionToken.TYPE_NCOL
                and ncol_support
            ):
                func_stack.insert(0, token)
                stack.insert(0, current)
                implicit_stack.insert(0, 3)
                current = []
            elif token.type_ == _ColorExpressionToken.TYPE_NCOL:
                current.append(_ColorExpressionToken(
                    _ColorExpressionToken.TYPE_NAME,
                    value=token.rawtext,
                    rawtext=token.rawtext,
                    column=token.column,
                ))
            elif token.type_ in (
                _ColorExpressionToken.TYPE_NAME,
                _ColorExpressionToken.TYPE_ANGLE,
                _ColorExpressionToken.TYPE_PERCENTAGE,
                _ColorExpressionToken.TYPE_INTEGER,
                _ColorExpressionToken.TYPE_FLOAT,
                _ColorExpressionToken.TYPE_HEX,
                _ColorExpressionToken.TYPE_EMPTY,
            ):
                # Current token is a value, we simply add it.

                current.append(token)
            elif token.type_ == _ColorExpressionToken.TYPE_CALL_START:
                if func_stack and (
                    func_stack[0].type_ == _ColorExpressionToken.TYPE_NCOL
                ):
                    implicit_stack[0] += 1

                name_token = current.pop(-1)
                if name_token.type_ != _ColorExpressionToken.TYPE_NAME:
                    raise _ColorExpressionSyntaxError(
                        'expected the name of the function to call, '
                        f'got a {name_token.type_.name}',
                        column=name_token.column,
                        func=_get_parent_func(),
                    )

                func_stack.insert(0, name_token)
                stack.insert(0, current)
                current = []
            elif token.type_ == _ColorExpressionToken.TYPE_CALL_END:
                # First, pop out all of the implicit functions.

                while func_stack:
                    try:
                        name_token = func_stack.pop(0)
                    except IndexError:
                        raise _ColorExpressionSyntaxError(
                            'extraneous closing parenthesis',
                            column=token.column,
                            func=_get_parent_func(),
                        ) from None

                    if name_token.type_ == _ColorExpressionToken.TYPE_NAME:
                        break

                    # We just pop the function out of the stack with the
                    # arguments we have.

                    implicit_stack.pop(0)
                    old_current = stack.pop(0)
                    old_current.append(_ColorExpressionToken(
                        type_=_ColorExpressionToken.TYPE_CALL,
                        column=name_token.column,
                        name=_ncol_func,
                        value=(name_token, *current),
                    ))
                    current = old_current

                # We have a function name and it is not implicit.

                old_current = stack.pop(0)
                old_current.append(_ColorExpressionToken(
                    _ColorExpressionTokenType.CALL,
                    name=name_token.value,
                    value=current,
                    column=name_token.column,
                ))
                current = old_current
            else:
                raise NotImplementedError(
                    f'unknown token type: {token.type_!r}',
                )

            if func_stack and (
                func_stack[0].type_ == _ColorExpressionToken.TYPE_NCOL
            ):
                implicit_stack[0] -= 1
                if implicit_stack[0] <= 0:
                    ncol = func_stack.pop(0)
                    implicit_stack.pop(0)

                    # We have the required number of tokens for this
                    # to work.

                    old_current = stack.pop(0)
                    old_current.append(_ColorExpressionToken(
                        type_=_ColorExpressionToken.TYPE_CALL,
                        column=ncol.column,
                        name=_ncol_func,
                        value=(ncol, *current),
                    ))
                    current = old_current

        # We want to pop out all implicit functions we have.
        # If we still have an explicit function in the function stack,
        # that means a parenthesis was omitted.

        while func_stack:
            try:
                name_token = func_stack.pop(0)
            except IndexError:
                break

            if name_token.type_ == _ColorExpressionToken.TYPE_NAME:
                raise _ColorExpressionSyntaxError(
                    'missing closing parenthesis',
                    column=len(expr),
                    func=_get_parent_func(),
                )

            # We just pop the function out of the stack with the
            # arguments we have.

            implicit_stack.pop(0)
            old_current = stack.pop(0)
            old_current.append(_ColorExpressionToken(
                type_=_ColorExpressionToken.TYPE_CALL,
                column=name_token.column,
                name=_ncol_func,
                value=(name_token, *current),
            ))
            current = old_current

        # Evaluating stage.

        def evaluate(element, parent_func=None):
            """ Evaluate the element in the current context.

                Always returns a tuple where:

                 * The first element is the real answer.
                 * The second element is the string which can be used
                   in the case of a color fallback (when Netscape color
                   defaulting is on).
            """

            if element.type_ == _ColorExpressionTokenType.NAME:
                try:
                    data = self[element.value]
                except KeyError:
                    if defaults_to_netscape:
                        return (
                            _SRGBColor.fromnetscapecolorname(element.value),
                            element.value,
                        )

                    raise _ColorExpressionSyntaxError(
                        f'unknown value {element.value!r}',
                        column=element.column,
                        func=parent_func,
                    )
                else:
                    if not isinstance(data, (_Color, _Angle, int, float)):
                        try:
                            fallback_value = data.__fallback_value__
                        except AttributeError:
                            raise _ColorExpressionSyntaxError(
                                f'{element.value!r} is not a value and '
                                f'has no fallback value (is {data!r})',
                                column=element.column,
                                func=parent_func,
                            )

                        if not isinstance(fallback_value, (
                            _Color, _Angle, int, float,
                        )):
                            raise _ColorExpressionSyntaxError(
                                f'{element.value!r} fallback value '
                                f'{fallback_value!r} is not a color, '
                                'an angle or a number.',
                                column=element.column,
                                func=parent_func,
                            )

                        data = fallback_value

                    return (data, element.value)
            elif element.type_ != _ColorExpressionTokenType.CALL:
                return (element.value, element.rawtext)

            func_name = element.name
            if callable(func_name):
                func = func_name
                func_name = '<implicit ncol function>'
            else:
                try:
                    func = self[func_name]
                except KeyError:
                    raise _ColorExpressionSyntaxError(
                        f'function {func_name!r} not found',
                        column=element.column,
                        func=parent_func,
                    )

            # Check the function.

            try:
                args_spec = _get_args(func)
            except ValueError as exc:
                raise _ColorExpressionSyntaxError(
                    f'function {func_name!r} is unsuitable for '
                    f'calling: {str(exc)}',
                    column=element,
                    func=parent_func,
                )

            # Check the argument count.
            #
            # We remove empty arguments at the end of calls so that
            # even calls such as ``func(a, b, , , , , ,)`` will only
            # have arguments 'a' and 'b'.

            unevaluated_args = element.value
            while (
                unevaluated_args and unevaluated_args[-1].type_
                == _ColorExpressionToken.TYPE_EMPTY
            ):
                unevaluated_args.pop(-1)

            if len(unevaluated_args) > len(args_spec):
                raise _ColorExpressionSyntaxError(
                    f'too many arguments for {func_name!r}: '
                    f'expected {len(args_spec)}, got {len(unevaluated_args)}',
                    column=element.column,
                    func=parent_func,
                )

            # Now we should evaluate subtokens and check the types of
            # the function.

            new_args = []

            for token, (argname, argtype, argdefvalue) in _zip_longest(
                unevaluated_args, args_spec, fillvalue=None,
            ):
                arg, fallback_string, column = None, None, element.column
                if token is not None:
                    column = token.column
                    arg, *_, fallback_string = evaluate(token)

                arg = arg if arg is not None else argdefvalue
                if arg is _NO_DEFAULT_VALUE:
                    raise _ColorExpressionSyntaxError(
                        f'expected a value for {argname!r}',
                        column=column,
                        func=func_name,
                    )

                if argtype is None or _isinstance(arg, argtype):
                    pass
                elif (
                    _issubclass(_Color, argtype) and defaults_to_netscape
                    and fallback_string is not None
                ):
                    arg = _SRGBColor.fromnetscapecolorname(fallback_string)
                elif (
                    _issubclass(_Angle, argtype)
                    and isinstance(arg, (int, float))
                ):
                    arg = _DegreesAngle(arg)
                elif (
                    _issubclass(float, argtype)
                    and isinstance(arg, int)
                ):
                    arg = float(arg)
                elif (
                    _issubclass(int, argtype)
                    and isinstance(arg, float)
                    and arg == int(arg)
                ):
                    arg = int(arg)
                else:
                    raise _ColorExpressionSyntaxError(
                        f'{arg!r} did not match expected type {argtype!r}'
                        f' for argument {argname!r}',
                        column=column,
                        func=func_name,
                    )

                new_args.append(arg)

            # Get the result.

            result = func(*new_args)
            if result is None:
                raise _ColorExpressionSyntaxError(
                    f'function {func_name!r} returned an empty '
                    'result for the following arguments: '
                    f'{", ".join(map(repr, new_args))}.',
                    column=token.column,
                    func=parent_func,
                )

            return result, None

        return tuple(
            _SRGBColor.fromnetscapecolorname(fallback_string)
            if (
                not isinstance(result, _Color)
                and prefer_colors
                and defaults_to_netscape
                and fallback_string is not None
            )
            else _DegreesAngle(result)
            if (
                isinstance(result, (int, float))
                and prefer_angles
            )
            else result
            for result, *_, fallback_string in map(evaluate, current)
        )


# ---
# Meta base type.
# ---


class _MetaColorDecoderType(_ABCMeta):
    """ The decoder type. """

    def __new__(mcls, clsname, superclasses, attributedict):
        elements = {}
        options = {
            '__ncol_support__': False,
            '__extended_hex_support__': False,
            '__defaults_to_netscape_color__': False,
        }

        # Explore the parents.

        for supercls in reversed(superclasses):
            if not issubclass(supercls, ColorDecoder):
                continue

            for option in options:
                if getattr(supercls, option, False):
                    options[option] = True

            elements.update(supercls.__mapping__)

        for option, value in options.items():
            options[option] = attributedict.get(option, value)

        # Instanciate the class.

        clsattrs = {
            '__doc__': attributedict.get('__doc__', None),
            '__mapping__': elements,
        }
        clsattrs.update(options)

        cls = super().__new__(mcls, clsname, superclasses, clsattrs)
        del clsattrs

        # Get the elements and aliases from the current attribute dictionary.

        aliases = {}
        childelements = {}
        for key, value in attributedict.items():
            if key.startswith('_') or key.endswith('_'):
                continue

            key = _canonicalkey(key)

            if isinstance(value, alias):
                aliases[key] = value
                continue
            elif callable(value):
                pass
            elif isinstance(value, (int, float, _Color, _Angle)):
                value = value
            else:
                raise TypeError(
                    f'{clsname} property {key!r} is neither an alias, '
                    'a function, a number, a color or an angle',
                )

            childelements[key] = value

        # Resolve the aliases.
        #
        # Because of dependencies, we do the basic solution for that:
        # We try to resolve aliases as we can, ignoring the ones for which
        # the aliases are still awaiting. If we could not resolve any
        # of the aliases in one round and there still are some left,
        # there must be a cyclic dependency somewhere.
        #
        # This is not optimized. However, given the cases we have,
        # it'll be enough.

        aliaselements = {}
        while aliases:
            resolved = len(aliases)
            nextaliases = {}

            for key, alias_value in aliases.items():
                funcname = _canonicalkey(alias_value.name)

                # Check if the current alias still depends on an alias
                # that hasn't been resolved yet; in that case, ignore
                # it for now.

                if funcname in aliases:
                    resolved -= 1
                    nextaliases[key] = alias_value
                    continue

                # Check the function name and arguments.

                try:
                    func = childelements[funcname]
                except KeyError:
                    try:
                        func = elements[funcname]
                    except KeyError:
                        raise ValueError(
                            f'{clsname} property {key!r} references '
                            f'undefined function {funcname!r}',
                        ) from None

                if not callable(func):
                    raise ValueError(
                        f'{clsname} property {key!r} '
                        f'references non-function {funcname!r}',
                    )

                aliaselements[_canonicalkey(key)] = _make_function(
                    func, name=key.replace('-', '_'), args=alias_value.args,
                )

            aliases = nextaliases
            if aliases and not resolved:
                raise ValueError(
                    f'could not resolve left aliases in class {clsname}, '
                    'there might be a cyclic dependency between these '
                    'aliases: ' + ', '.join(aliases.keys()) + '.',
                )

        # Add all of the elements in order of importance.

        elements.update(aliaselements)
        elements.update(childelements)

        # Check the types of the annotations, just in case.

        for key, element in elements.items():
            try:
                args_spec = _get_args(element)
            except TypeError:
                continue

            for argname, argtype, argdefvalue in args_spec:
                if argtype is None:
                    continue

                if all(
                    not _issubclass(type_, argtype)
                    for type_ in (int, float, _Color, _Angle, type(None))
                ):
                    raise TypeError(
                        f'function {key!r}, argument {argname!r}: '
                        'none of the types handled by the decoder are '
                        f'valid subclasses of type hint {argtype}',
                    )

                if argdefvalue is _NO_DEFAULT_VALUE:
                    continue

                if (
                    not _isinstance(argdefvalue, argtype)
                    and not (
                        isinstance(argdefvalue, int)
                        and _issubclass(float, argtype)
                    )
                    and not (
                        isinstance(argdefvalue, float)
                        and int(argdefvalue) == argdefvalue
                        and _issubclass(int, argtype)
                    )
                    and not (
                        isinstance(argdefvalue, (int, float))
                        and _issubclass(_Angle, argtype)
                    )
                ):
                    raise TypeError(
                        f'function {key!r}, argument {argname!r}: '
                        f'default value {argdefvalue!r} is not a valid '
                        f'instance of type hint {argtype!r}',
                    )

        return cls


class MetaColorDecoder(ColorDecoder, metaclass=_MetaColorDecoderType):
    """ Base meta color decoder, which gets the function and things. """

    pass


# End of file.