aboutsummaryrefslogtreecommitdiff
path: root/mesonbuild/interpreter/primitives/boolean.py
blob: 0a434af58a1663507635c9d41a5ff2ffb0232bbb (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
# Copyright 2021 The Meson development team
# SPDX-license-identifier: Apache-2.0

from ...interpreterbase import (
    ObjectHolder,
    MesonOperator,
    typed_pos_args,
    noKwargs,
    noPosargs,

    TYPE_var,
    TYPE_kwargs,

    InvalidArguments
)

import typing as T

if T.TYPE_CHECKING:
    # Object holders need the actual interpreter
    from ...interpreter import Interpreter

class BooleanHolder(ObjectHolder[bool]):
    def __init__(self, obj: bool, interpreter: 'Interpreter') -> None:
        super().__init__(obj, interpreter)
        self.methods.update({
            'to_int': self.to_int_method,
            'to_string': self.to_string_method,
        })

        self.trivial_operators.update({
            MesonOperator.BOOL: (None, lambda x: self.held_object),
            MesonOperator.NOT: (None, lambda x: not self.held_object),
            MesonOperator.EQUALS: (bool, lambda x: self.held_object == x),
            MesonOperator.NOT_EQUALS: (bool, lambda x: self.held_object != x),
        })

    def display_name(self) -> str:
        return 'bool'

    @noKwargs
    @noPosargs
    def to_int_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> int:
        return 1 if self.held_object else 0

    @noKwargs
    @typed_pos_args('bool.to_string', optargs=[str, str])
    def to_string_method(self, args: T.Tuple[T.Optional[str], T.Optional[str]], kwargs: TYPE_kwargs) -> str:
        true_str = args[0] or 'true'
        false_str = args[1] or 'false'
        if any(x is not None for x in args) and not all(x is not None for x in args):
            raise InvalidArguments('bool.to_string() must have either no arguments or exactly two string arguments that signify what values to return for true and false.')
        return true_str if self.held_object else false_str