aboutsummaryrefslogtreecommitdiff
path: root/thcolor/decoders/base.py
blob: 0f4d7cf2e960d91813c7137cda64112d2e09617f (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
#!/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,
)
from inspect import getfullargspec as _getfullargspec

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

__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 _factor(x, max_=100):
    """ Return a factor based on if something is a float or an int. """

    if isinstance(x, float):
        return x
    return x / max_


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)

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

    return issubclass(cls, types)


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.
    """

    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)

    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, 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
            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 = ', '.join(_iter_proxy_args(locals_, proxy_args))
    final_args = ', '.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}):\n'
        f'    return __func({final_args})\n'
        f'  return {name}\n'
        '\n'
        f'__func = __define_alias({keys})\n'
    )

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

    return func


# ---
# 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-z_-]([a-z0-9_-]*[a-z0-9_-])?)
            |
        ) \s* (?P<sep>,|/|\s|\(|\)|$)
    )
    \s*
    """,
    _re.VERBOSE | _re.I | _re.M,
)


def _get_color_tokens(string: str):
    """ Get color tokens. """

    start = 0
    was_call_end = 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:
            yield _ColorExpressionToken(
                _ColorExpressionToken.TYPE_NCOL,
                value=result['ncol'],
                column=column,
                rawtext=result['ncol'],
            )
        elif result['hex'] is not None:
            value = result['hex']
            if len(value) <= 4:
                value = ''.join(map(lambda x: x + x, value))

            r = int(value[0:2], 16)
            g = int(value[2:4], 16)
            b = int(value[4:6], 16)
            a = int(value[6:8], 16) / 255.0 if len(value) == 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.
         * ``__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
    __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._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)
        defaults_to_netscape = bool(self._defaults_to_netscape_color)

        # Parsing stage; the results will be in ``current``.

        stack = []
        func_stack = [_ColorExpressionToken(
            _ColorExpressionToken.TYPE_NAME,
            value=None,
        )]
        current = []

        token_iter = _get_color_tokens(expr)
        for token in token_iter:
            if (
                token.type_ == _ColorExpressionToken.TYPE_NCOL
                and ncol_support
            ):
                letter = token.value[0]
                number = float(token.value[1:])

                if number < 0 or number >= 100:
                    raise _ColorExpressionSyntaxError(
                        'ncol number should be between 0 and 100 excluded, '
                        f'is {number!r}',
                        column=token.column,
                        func=func_stack[0].value,
                    )

                # Get the two next tokens, which should be numbers.
                # Note that they cannot result from function calls, they
                # should be defined in the syntax directly.
                #
                # TODO: make this an implicit function with two arguments,
                # so that percentages can be determined dynamically.
                # TODO: if the NColor is not valid, maybe it is a symbol
                # name, in which case a default should be set.

                first_token, second_token = None, None
                try:
                    first_token = next(token_iter)
                    second_token = next(token_iter)
                except StopIteration:
                    break

                if first_token is None or second_token is None or any(
                    token.type_ not in (
                        _ColorExpressionToken.TYPE_INTEGER,
                        _ColorExpressionToken.TYPE_FLOAT,
                        _ColorExpressionToken.TYPE_PERCENTAGE,
                    )
                    for token in (first_token, second_token)
                ):
                    raise _ColorExpressionSyntaxError(
                        'ncol should be followed by the whiteness and '
                        'the blackness as two constant values',
                        column=token.column,
                        func=func_stack[0].value,
                    )

                current.append(_ColorExpressionToken(
                    type_=_ColorExpressionToken.TYPE_HEX,
                    column=token.column,
                    value=_HWBColor(
                        hue=_DegreesAngle(
                            'RYGCBM'.find(letter) * 60 + number / 100 * 60
                        ),
                        whiteness=_factor(first_token.value),
                        blackness=_factor(second_token.value),
                    ),
                ))
            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:
                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=func_stack[0].value,
                    )

                func_stack.insert(0, name_token)
                stack.insert(0, current)
                current = []
            elif token.type_ == _ColorExpressionToken.TYPE_CALL_END:
                try:
                    old_current = stack.pop(0)
                except IndexError:
                    raise _ColorExpressionSyntaxError(
                        'extraneous closing parenthesis',
                        column=token.column,
                        func=func_stack[0].value,
                    ) from None

                name_token = func_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 stack:
            raise _ColorExpressionSyntaxError(
                'missing closing parenthesis',
                column=len(expr),
                func=func_stack[0].value,
            )

        # 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

            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(
                unevaluated_args, args_spec
            ):
                arg, *_, fallback_string = evaluate(token)
                arg = arg if arg is not None else argdefvalue

                if arg is None:
                    raise _ColorExpressionSyntaxError(
                        f'expected a value for {argname!r}',
                        column=token.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)
                else:
                    raise _ColorExpressionSyntaxError(
                        f'{arg!r} did not match expected type {argtype!r}'
                        f' for argument {argname!r}',
                        column=token.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,
            '__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.
        #
        # TODO: check if the argument types are valid (we had ``_angle``
        # versus ``_Angle`` problems before, so we need to check).

        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)

        return cls


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

    __defaults_to_netscape_color__ = True
    __ncol_support__ = False


# End of file.