Nuitka
The Python compiler
Loading...
Searching...
No Matches
boolean.h
1// Copyright 2025, Kay Hayen, mailto:kay.hayen@gmail.com find license text at end of file
2
3#ifndef __NUITKA_HELPER_BOOLEAN_H__
4#define __NUITKA_HELPER_BOOLEAN_H__
5
6// The slot in Python3 got renamed, compensate it like this.
7#if PYTHON_VERSION >= 0x300
8#define nb_nonzero nb_bool
9#endif
10
11NUITKA_MAY_BE_UNUSED static int CHECK_IF_TRUE(PyObject *object) {
12 CHECK_OBJECT(object);
13
14 if (object == Py_True) {
15 return 1;
16 } else if (object == Py_False || object == Py_None) {
17 return 0;
18 } else {
19 Py_ssize_t result;
20
21 if (Py_TYPE(object)->tp_as_number != NULL && Py_TYPE(object)->tp_as_number->nb_nonzero != NULL) {
22 result = (*Py_TYPE(object)->tp_as_number->nb_nonzero)(object);
23 } else if (Py_TYPE(object)->tp_as_mapping != NULL && Py_TYPE(object)->tp_as_mapping->mp_length != NULL) {
24 result = (*Py_TYPE(object)->tp_as_mapping->mp_length)(object);
25 } else if (Py_TYPE(object)->tp_as_sequence != NULL && Py_TYPE(object)->tp_as_sequence->sq_length != NULL) {
26 result = (*Py_TYPE(object)->tp_as_sequence->sq_length)(object);
27 } else {
28 return 1;
29 }
30
31 if (result > 0) {
32 return 1;
33 } else if (result == 0) {
34 return 0;
35 } else {
36 return -1;
37 }
38 }
39}
40
41NUITKA_MAY_BE_UNUSED static int CHECK_IF_FALSE(PyObject *object) {
42 int result = CHECK_IF_TRUE(object);
43
44 if (result == 0) {
45 return 1;
46 }
47 if (result == 1) {
48 return 0;
49 }
50 return -1;
51}
52
53NUITKA_MAY_BE_UNUSED static inline PyObject *BOOL_FROM(bool value) {
54 CHECK_OBJECT(Py_True);
55 CHECK_OBJECT(Py_False);
56
57 return value ? Py_True : Py_False;
58}
59
60#undef nb_nonzero
61
62typedef enum {
63 NUITKA_BOOL_FALSE = 0,
64 NUITKA_BOOL_TRUE = 1,
65 NUITKA_BOOL_UNASSIGNED = 2,
66 NUITKA_BOOL_EXCEPTION = -1
67} nuitka_bool;
68
69typedef enum { NUITKA_VOID_OK = 0, NUITKA_VOID_EXCEPTION = 1 } nuitka_void;
70
71#endif
72
73// Part of "Nuitka", an optimizing Python compiler that is compatible and
74// integrates with CPython, but also works on its own.
75//
76// Licensed under the Apache License, Version 2.0 (the "License");
77// you may not use this file except in compliance with the License.
78// You may obtain a copy of the License at
79//
80// http://www.apache.org/licenses/LICENSE-2.0
81//
82// Unless required by applicable law or agreed to in writing, software
83// distributed under the License is distributed on an "AS IS" BASIS,
84// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85// See the License for the specific language governing permissions and
86// limitations under the License.