2013-10-19 04:09:25 -03:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
#
|
|
|
|
# Argument Clinic
|
|
|
|
# Copyright 2012-2013 by Larry Hastings.
|
|
|
|
# Licensed to the PSF under a contributor agreement.
|
|
|
|
#
|
2023-07-03 11:03:31 -03:00
|
|
|
from __future__ import annotations
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 13:24:23 -03:00
|
|
|
import argparse
|
2013-10-19 04:09:25 -03:00
|
|
|
import ast
|
2023-05-15 05:49:28 -03:00
|
|
|
import builtins as bltns
|
2013-10-19 04:09:25 -03:00
|
|
|
import contextlib
|
2023-07-06 18:17:12 -03:00
|
|
|
import dataclasses as dc
|
2023-05-18 18:58:42 -03:00
|
|
|
import enum
|
2013-10-19 04:09:25 -03:00
|
|
|
import functools
|
|
|
|
import inspect
|
|
|
|
import io
|
|
|
|
import itertools
|
|
|
|
import os
|
2014-01-17 21:47:17 -04:00
|
|
|
import pprint
|
2013-10-19 04:09:25 -03:00
|
|
|
import re
|
|
|
|
import shlex
|
|
|
|
import sys
|
|
|
|
import textwrap
|
|
|
|
|
2023-07-04 19:15:10 -03:00
|
|
|
from collections.abc import (
|
|
|
|
Callable,
|
|
|
|
Iterable,
|
|
|
|
Iterator,
|
|
|
|
Sequence,
|
|
|
|
)
|
2023-08-21 10:59:58 -03:00
|
|
|
from operator import attrgetter
|
2023-05-16 09:02:18 -03:00
|
|
|
from types import FunctionType, NoneType
|
2023-07-02 20:42:38 -03:00
|
|
|
from typing import (
|
|
|
|
Any,
|
|
|
|
Final,
|
|
|
|
Literal,
|
|
|
|
NamedTuple,
|
|
|
|
NoReturn,
|
2023-07-16 21:04:10 -03:00
|
|
|
Protocol,
|
2023-07-02 20:42:38 -03:00
|
|
|
)
|
2015-05-04 10:59:46 -03:00
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
|
|
|
|
# Local imports.
|
|
|
|
import libclinic
|
2023-12-27 19:20:57 -04:00
|
|
|
import libclinic.cpp
|
2024-03-14 11:37:22 -03:00
|
|
|
from libclinic import (
|
|
|
|
ClinicError, Sentinels, VersionTuple,
|
|
|
|
fail, warn, unspecified, unknown)
|
|
|
|
from libclinic.function import (
|
|
|
|
Module, Class, Function, Parameter,
|
|
|
|
ClassDict, ModuleDict, FunctionKind,
|
|
|
|
CALLABLE, STATIC_METHOD, CLASS_METHOD, METHOD_INIT, METHOD_NEW,
|
|
|
|
GETTER, SETTER)
|
2024-03-14 13:11:39 -03:00
|
|
|
from libclinic.language import Language, PythonLanguage
|
|
|
|
from libclinic.block_parser import Block, BlockParser
|
2024-03-14 14:59:43 -03:00
|
|
|
from libclinic.crenderdata import CRenderData, Include, TemplateDict
|
|
|
|
from libclinic.converter import (
|
|
|
|
CConverter, CConverterClassT,
|
|
|
|
converters, legacy_converters)
|
2023-12-22 20:37:39 -04:00
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
# TODO:
|
|
|
|
#
|
|
|
|
# soon:
|
|
|
|
#
|
|
|
|
# * allow mixing any two of {positional-only, positional-or-keyword,
|
|
|
|
# keyword-only}
|
|
|
|
# * dict constructor uses positional-only and keyword-only
|
|
|
|
# * max and min use positional only with an optional group
|
|
|
|
# and keyword-only
|
|
|
|
#
|
|
|
|
|
2023-08-31 18:42:34 -03:00
|
|
|
|
2024-03-11 19:42:18 -03:00
|
|
|
# Match '#define Py_LIMITED_API'.
|
|
|
|
# Match '# define Py_LIMITED_API 0x030d0000' (without the version).
|
|
|
|
LIMITED_CAPI_REGEX = re.compile(r'# *define +Py_LIMITED_API')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-18 18:58:42 -03:00
|
|
|
|
|
|
|
# This one needs to be a distinct class, unlike the other two
|
2013-10-19 04:09:25 -03:00
|
|
|
class Null:
|
2023-05-16 14:18:28 -03:00
|
|
|
def __repr__(self) -> str:
|
2013-10-19 04:09:25 -03:00
|
|
|
return '<Null>'
|
|
|
|
|
2014-01-16 15:32:01 -04:00
|
|
|
|
2023-05-18 18:58:42 -03:00
|
|
|
NULL = Null()
|
2014-01-16 15:32:01 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-04 19:15:10 -03:00
|
|
|
ParamTuple = tuple["Parameter", ...]
|
|
|
|
|
|
|
|
|
|
|
|
def permute_left_option_groups(
|
2023-07-20 18:33:33 -03:00
|
|
|
l: Sequence[Iterable[Parameter]]
|
2023-07-04 19:15:10 -03:00
|
|
|
) -> Iterator[ParamTuple]:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
2023-07-04 08:36:40 -03:00
|
|
|
Given [(1,), (2,), (3,)], should yield:
|
2013-10-19 04:09:25 -03:00
|
|
|
()
|
|
|
|
(3,)
|
|
|
|
(2, 3)
|
|
|
|
(1, 2, 3)
|
|
|
|
"""
|
|
|
|
yield tuple()
|
2023-07-04 19:15:10 -03:00
|
|
|
accumulator: list[Parameter] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
for group in reversed(l):
|
|
|
|
accumulator = list(group) + accumulator
|
|
|
|
yield tuple(accumulator)
|
|
|
|
|
|
|
|
|
2023-07-04 19:15:10 -03:00
|
|
|
def permute_right_option_groups(
|
2023-07-20 18:33:33 -03:00
|
|
|
l: Sequence[Iterable[Parameter]]
|
2023-07-04 19:15:10 -03:00
|
|
|
) -> Iterator[ParamTuple]:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
2023-07-04 08:36:40 -03:00
|
|
|
Given [(1,), (2,), (3,)], should yield:
|
2013-10-19 04:09:25 -03:00
|
|
|
()
|
|
|
|
(1,)
|
|
|
|
(1, 2)
|
|
|
|
(1, 2, 3)
|
|
|
|
"""
|
|
|
|
yield tuple()
|
2023-07-04 19:15:10 -03:00
|
|
|
accumulator: list[Parameter] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
for group in l:
|
|
|
|
accumulator.extend(group)
|
|
|
|
yield tuple(accumulator)
|
|
|
|
|
|
|
|
|
2023-07-04 19:15:10 -03:00
|
|
|
def permute_optional_groups(
|
2023-07-20 18:33:33 -03:00
|
|
|
left: Sequence[Iterable[Parameter]],
|
|
|
|
required: Iterable[Parameter],
|
|
|
|
right: Sequence[Iterable[Parameter]]
|
2023-07-04 19:15:10 -03:00
|
|
|
) -> tuple[ParamTuple, ...]:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Generator function that computes the set of acceptable
|
|
|
|
argument lists for the provided iterables of
|
|
|
|
argument groups. (Actually it generates a tuple of tuples.)
|
|
|
|
|
|
|
|
Algorithm: prefer left options over right options.
|
|
|
|
|
|
|
|
If required is empty, left must also be empty.
|
|
|
|
"""
|
|
|
|
required = tuple(required)
|
|
|
|
if not required:
|
2022-10-07 18:41:35 -03:00
|
|
|
if left:
|
|
|
|
raise ValueError("required is empty but left is not")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-04 19:15:10 -03:00
|
|
|
accumulator: list[ParamTuple] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
counts = set()
|
|
|
|
for r in permute_right_option_groups(right):
|
|
|
|
for l in permute_left_option_groups(left):
|
|
|
|
t = l + required + r
|
|
|
|
if len(t) in counts:
|
|
|
|
continue
|
|
|
|
counts.add(len(t))
|
|
|
|
accumulator.append(t)
|
|
|
|
|
|
|
|
accumulator.sort(key=len)
|
|
|
|
return tuple(accumulator)
|
|
|
|
|
|
|
|
|
2023-07-04 19:13:30 -03:00
|
|
|
def declare_parser(
|
|
|
|
f: Function,
|
|
|
|
*,
|
2023-08-31 18:42:34 -03:00
|
|
|
hasformat: bool = False,
|
|
|
|
clinic: Clinic,
|
|
|
|
limited_capi: bool,
|
2023-07-04 19:13:30 -03:00
|
|
|
) -> str:
|
2022-08-11 18:25:49 -03:00
|
|
|
"""
|
|
|
|
Generates the code template for a static local PyArg_Parser variable,
|
|
|
|
with an initializer. For core code (incl. builtin modules) the
|
|
|
|
kwtuple field is also statically initialized. Otherwise
|
|
|
|
it is initialized at runtime.
|
|
|
|
"""
|
|
|
|
if hasformat:
|
|
|
|
fname = ''
|
|
|
|
format_ = '.format = "{format_units}:{name}",'
|
|
|
|
else:
|
|
|
|
fname = '.fname = "{name}",'
|
|
|
|
format_ = ''
|
2022-08-13 07:09:40 -03:00
|
|
|
|
|
|
|
num_keywords = len([
|
|
|
|
p for p in f.parameters.values()
|
|
|
|
if not p.is_positional_only() and not p.is_vararg()
|
|
|
|
])
|
2023-08-31 18:42:34 -03:00
|
|
|
if limited_capi:
|
|
|
|
declarations = """
|
|
|
|
#define KWTUPLE NULL
|
|
|
|
"""
|
|
|
|
elif num_keywords == 0:
|
2022-08-13 07:09:40 -03:00
|
|
|
declarations = """
|
|
|
|
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
|
|
|
|
# define KWTUPLE (PyObject *)&_Py_SINGLETON(tuple_empty)
|
|
|
|
#else
|
|
|
|
# define KWTUPLE NULL
|
|
|
|
#endif
|
|
|
|
"""
|
|
|
|
else:
|
|
|
|
declarations = """
|
|
|
|
#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
|
|
|
|
|
|
|
|
#define NUM_KEYWORDS %d
|
|
|
|
static struct {{
|
|
|
|
PyGC_Head _this_is_not_used;
|
|
|
|
PyObject_VAR_HEAD
|
|
|
|
PyObject *ob_item[NUM_KEYWORDS];
|
|
|
|
}} _kwtuple = {{
|
|
|
|
.ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
|
|
|
|
.ob_item = {{ {keywords_py} }},
|
|
|
|
}};
|
|
|
|
#undef NUM_KEYWORDS
|
|
|
|
#define KWTUPLE (&_kwtuple.ob_base.ob_base)
|
|
|
|
|
|
|
|
#else // !Py_BUILD_CORE
|
|
|
|
# define KWTUPLE NULL
|
|
|
|
#endif // !Py_BUILD_CORE
|
|
|
|
""" % num_keywords
|
|
|
|
|
2023-08-31 18:42:34 -03:00
|
|
|
condition = '#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)'
|
|
|
|
clinic.add_include('pycore_gc.h', 'PyGC_Head', condition=condition)
|
|
|
|
clinic.add_include('pycore_runtime.h', '_Py_ID()', condition=condition)
|
|
|
|
|
2022-08-13 07:09:40 -03:00
|
|
|
declarations += """
|
|
|
|
static const char * const _keywords[] = {{{keywords_c} NULL}};
|
|
|
|
static _PyArg_Parser _parser = {{
|
|
|
|
.keywords = _keywords,
|
|
|
|
%s
|
|
|
|
.kwtuple = KWTUPLE,
|
|
|
|
}};
|
|
|
|
#undef KWTUPLE
|
|
|
|
""" % (format_ or fname)
|
2023-12-23 13:08:10 -04:00
|
|
|
return libclinic.normalize_snippet(declarations)
|
2015-04-14 19:07:59 -03:00
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class CLanguage(Language):
|
|
|
|
|
2014-01-07 16:41:53 -04:00
|
|
|
body_prefix = "#"
|
2013-10-19 04:09:25 -03:00
|
|
|
language = 'C'
|
2014-01-07 16:41:53 -04:00
|
|
|
start_line = "/*[{dsl_name} input]"
|
2013-10-19 04:09:25 -03:00
|
|
|
body_prefix = ""
|
2014-01-07 16:41:53 -04:00
|
|
|
stop_line = "[{dsl_name} start generated code]*/"
|
2014-01-28 09:00:08 -04:00
|
|
|
checksum_line = "/*[{dsl_name} end generated code: {arguments}]*/"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
NO_VARARG: Final[str] = "PY_SSIZE_T_MAX"
|
|
|
|
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_KEYWORD: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *args, PyObject *kwargs)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_KEYWORD___INIT__: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static int
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *args, PyObject *kwargs)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_VARARGS: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *args)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_FASTCALL: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *const *args, Py_ssize_t nargs)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_FASTCALL_KEYWORDS: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_DEF_CLASS: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyTypeObject *{defining_class_name}, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_NOARGS: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *Py_UNUSED(ignored))
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_GETTER: Final[str] = libclinic.normalize_snippet("""
|
2023-11-30 06:40:53 -04:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, void *Py_UNUSED(context))
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
PARSER_PROTOTYPE_SETTER: Final[str] = libclinic.normalize_snippet("""
|
2023-12-13 10:00:34 -04:00
|
|
|
static int
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *value, void *Py_UNUSED(context))
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
METH_O_PROTOTYPE: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({impl_parameters})
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
DOCSTRING_PROTOTYPE_VAR: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
PyDoc_VAR({c_basename}__doc__);
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
DOCSTRING_PROTOTYPE_STRVAR: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
PyDoc_STRVAR({c_basename}__doc__,
|
|
|
|
{docstring});
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
GETSET_DOCSTRING_PROTOTYPE_STRVAR: Final[str] = libclinic.normalize_snippet("""
|
2023-12-20 08:52:12 -04:00
|
|
|
PyDoc_STRVAR({getset_basename}__doc__,
|
|
|
|
{docstring});
|
|
|
|
#define {getset_basename}_HAS_DOCSTR
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
IMPL_DEFINITION_PROTOTYPE: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
static {impl_return_type}
|
|
|
|
{c_basename}_impl({impl_parameters})
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
METHODDEF_PROTOTYPE_DEFINE: Final[str] = libclinic.normalize_snippet(r"""
|
2023-08-02 16:37:36 -03:00
|
|
|
#define {methoddef_name} \
|
|
|
|
{{"{name}", {methoddef_cast}{c_basename}{methoddef_cast_end}, {methoddef_flags}, {c_basename}__doc__}},
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
GETTERDEF_PROTOTYPE_DEFINE: Final[str] = libclinic.normalize_snippet(r"""
|
2023-12-20 08:52:12 -04:00
|
|
|
#if defined({getset_basename}_HAS_DOCSTR)
|
|
|
|
# define {getset_basename}_DOCSTR {getset_basename}__doc__
|
|
|
|
#else
|
|
|
|
# define {getset_basename}_DOCSTR NULL
|
|
|
|
#endif
|
2023-12-13 10:00:34 -04:00
|
|
|
#if defined({getset_name}_GETSETDEF)
|
|
|
|
# undef {getset_name}_GETSETDEF
|
2023-12-20 08:52:12 -04:00
|
|
|
# define {getset_name}_GETSETDEF {{"{name}", (getter){getset_basename}_get, (setter){getset_basename}_set, {getset_basename}_DOCSTR}},
|
2023-12-13 10:00:34 -04:00
|
|
|
#else
|
2023-12-20 08:52:12 -04:00
|
|
|
# define {getset_name}_GETSETDEF {{"{name}", (getter){getset_basename}_get, NULL, {getset_basename}_DOCSTR}},
|
2023-12-13 10:00:34 -04:00
|
|
|
#endif
|
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
SETTERDEF_PROTOTYPE_DEFINE: Final[str] = libclinic.normalize_snippet(r"""
|
2023-12-20 08:52:12 -04:00
|
|
|
#if defined({getset_name}_HAS_DOCSTR)
|
|
|
|
# define {getset_basename}_DOCSTR {getset_basename}__doc__
|
|
|
|
#else
|
|
|
|
# define {getset_basename}_DOCSTR NULL
|
|
|
|
#endif
|
2023-12-13 10:00:34 -04:00
|
|
|
#if defined({getset_name}_GETSETDEF)
|
|
|
|
# undef {getset_name}_GETSETDEF
|
2023-12-20 08:52:12 -04:00
|
|
|
# define {getset_name}_GETSETDEF {{"{name}", (getter){getset_basename}_get, (setter){getset_basename}_set, {getset_basename}_DOCSTR}},
|
2023-12-13 10:00:34 -04:00
|
|
|
#else
|
|
|
|
# define {getset_name}_GETSETDEF {{"{name}", NULL, (setter){getset_basename}_set, NULL}},
|
|
|
|
#endif
|
2023-11-30 06:40:53 -04:00
|
|
|
""")
|
2023-12-23 13:08:10 -04:00
|
|
|
METHODDEF_PROTOTYPE_IFNDEF: Final[str] = libclinic.normalize_snippet("""
|
2023-08-02 16:37:36 -03:00
|
|
|
#ifndef {methoddef_name}
|
|
|
|
#define {methoddef_name}
|
|
|
|
#endif /* !defined({methoddef_name}) */
|
|
|
|
""")
|
2023-08-19 04:13:35 -03:00
|
|
|
COMPILER_DEPRECATION_WARNING_PROTOTYPE: Final[str] = r"""
|
2023-08-08 05:43:41 -03:00
|
|
|
// Emit compiler warnings when we get to Python {major}.{minor}.
|
2023-08-07 08:28:08 -03:00
|
|
|
#if PY_VERSION_HEX >= 0x{major:02x}{minor:02x}00C0
|
2023-08-19 04:13:35 -03:00
|
|
|
# error {message}
|
2023-08-07 08:28:08 -03:00
|
|
|
#elif PY_VERSION_HEX >= 0x{major:02x}{minor:02x}00A0
|
|
|
|
# ifdef _MSC_VER
|
2023-08-19 04:13:35 -03:00
|
|
|
# pragma message ({message})
|
2023-08-07 08:28:08 -03:00
|
|
|
# else
|
2023-08-19 04:13:35 -03:00
|
|
|
# warning {message}
|
2023-08-07 08:28:08 -03:00
|
|
|
# endif
|
|
|
|
#endif
|
2023-08-19 04:13:35 -03:00
|
|
|
"""
|
|
|
|
DEPRECATION_WARNING_PROTOTYPE: Final[str] = r"""
|
|
|
|
if ({condition}) {{{{{errcheck}
|
2023-08-07 11:33:52 -03:00
|
|
|
if (PyErr_WarnEx(PyExc_DeprecationWarning,
|
2023-08-19 04:13:35 -03:00
|
|
|
{message}, 1))
|
2023-08-07 11:33:52 -03:00
|
|
|
{{{{
|
2023-08-19 04:13:35 -03:00
|
|
|
goto exit;
|
2023-08-07 08:28:08 -03:00
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
"""
|
2023-08-02 16:37:36 -03:00
|
|
|
|
2023-07-17 08:47:08 -03:00
|
|
|
def __init__(self, filename: str) -> None:
|
2014-02-01 02:03:12 -04:00
|
|
|
super().__init__(filename)
|
2023-12-27 19:20:57 -04:00
|
|
|
self.cpp = libclinic.cpp.Monitor(filename)
|
2014-02-01 02:03:12 -04:00
|
|
|
|
2023-07-04 20:07:57 -03:00
|
|
|
def parse_line(self, line: str) -> None:
|
2014-02-01 02:03:12 -04:00
|
|
|
self.cpp.writeline(line)
|
|
|
|
|
2023-07-04 20:07:57 -03:00
|
|
|
def render(
|
|
|
|
self,
|
2024-02-15 09:21:31 -04:00
|
|
|
clinic: Clinic,
|
2023-07-11 18:21:14 -03:00
|
|
|
signatures: Iterable[Module | Class | Function]
|
2023-07-04 20:07:57 -03:00
|
|
|
) -> str:
|
2013-10-19 04:09:25 -03:00
|
|
|
function = None
|
|
|
|
for o in signatures:
|
|
|
|
if isinstance(o, Function):
|
|
|
|
if function:
|
|
|
|
fail("You may specify at most one function per block.\nFound a block containing at least two:\n\t" + repr(function) + " and " + repr(o))
|
|
|
|
function = o
|
2014-01-17 21:47:17 -04:00
|
|
|
return self.render_function(clinic, function)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
def compiler_deprecated_warning(
|
|
|
|
self,
|
|
|
|
func: Function,
|
|
|
|
parameters: list[Parameter],
|
|
|
|
) -> str | None:
|
|
|
|
minversion: VersionTuple | None = None
|
|
|
|
for p in parameters:
|
|
|
|
for version in p.deprecated_positional, p.deprecated_keyword:
|
|
|
|
if version and (not minversion or minversion > version):
|
|
|
|
minversion = version
|
|
|
|
if not minversion:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# Format the preprocessor warning and error messages.
|
|
|
|
assert isinstance(self.cpp.filename, str)
|
|
|
|
message = f"Update the clinic input of {func.full_name!r}."
|
|
|
|
code = self.COMPILER_DEPRECATION_WARNING_PROTOTYPE.format(
|
|
|
|
major=minversion[0],
|
|
|
|
minor=minversion[1],
|
2023-12-22 20:37:39 -04:00
|
|
|
message=libclinic.c_repr(message),
|
2023-08-19 04:13:35 -03:00
|
|
|
)
|
2023-12-23 13:08:10 -04:00
|
|
|
return libclinic.normalize_snippet(code)
|
2023-08-19 04:13:35 -03:00
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
def deprecate_positional_use(
|
|
|
|
self,
|
|
|
|
func: Function,
|
|
|
|
params: dict[int, Parameter],
|
|
|
|
) -> str:
|
|
|
|
assert len(params) > 0
|
2023-08-21 10:59:58 -03:00
|
|
|
first_pos = next(iter(params))
|
|
|
|
last_pos = next(reversed(params))
|
2023-08-07 11:33:52 -03:00
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
# Format the deprecation message.
|
|
|
|
if len(params) == 1:
|
|
|
|
condition = f"nargs == {first_pos+1}"
|
2023-08-21 10:59:58 -03:00
|
|
|
amount = f"{first_pos+1} " if first_pos else ""
|
|
|
|
pl = "s"
|
2023-08-07 08:28:08 -03:00
|
|
|
else:
|
|
|
|
condition = f"nargs > {first_pos} && nargs <= {last_pos+1}"
|
2023-08-21 10:59:58 -03:00
|
|
|
amount = f"more than {first_pos} " if first_pos else ""
|
|
|
|
pl = "s" if first_pos != 1 else ""
|
|
|
|
message = (
|
|
|
|
f"Passing {amount}positional argument{pl} to "
|
|
|
|
f"{func.fulldisplayname}() is deprecated."
|
|
|
|
)
|
|
|
|
|
|
|
|
for (major, minor), group in itertools.groupby(
|
|
|
|
params.values(), key=attrgetter("deprecated_positional")
|
|
|
|
):
|
|
|
|
names = [repr(p.name) for p in group]
|
2023-12-22 20:37:39 -04:00
|
|
|
pstr = libclinic.pprint_words(names)
|
2023-08-21 10:59:58 -03:00
|
|
|
if len(names) == 1:
|
|
|
|
message += (
|
|
|
|
f" Parameter {pstr} will become a keyword-only parameter "
|
|
|
|
f"in Python {major}.{minor}."
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
message += (
|
|
|
|
f" Parameters {pstr} will become keyword-only parameters "
|
|
|
|
f"in Python {major}.{minor}."
|
2023-08-07 08:28:08 -03:00
|
|
|
)
|
2023-08-08 03:41:09 -03:00
|
|
|
|
|
|
|
# Append deprecation warning to docstring.
|
2023-08-19 04:13:35 -03:00
|
|
|
docstring = textwrap.fill(f"Note: {message}")
|
2023-08-08 03:41:09 -03:00
|
|
|
func.docstring += f"\n\n{docstring}\n"
|
2023-08-19 04:13:35 -03:00
|
|
|
# Format and return the code block.
|
|
|
|
code = self.DEPRECATION_WARNING_PROTOTYPE.format(
|
|
|
|
condition=condition,
|
|
|
|
errcheck="",
|
2023-12-22 20:37:39 -04:00
|
|
|
message=libclinic.wrapped_c_string_literal(message, width=64,
|
|
|
|
subsequent_indent=20),
|
2023-08-19 04:13:35 -03:00
|
|
|
)
|
2023-12-23 13:08:10 -04:00
|
|
|
return libclinic.normalize_snippet(code, indent=4)
|
2023-08-19 04:13:35 -03:00
|
|
|
|
|
|
|
def deprecate_keyword_use(
|
|
|
|
self,
|
|
|
|
func: Function,
|
|
|
|
params: dict[int, Parameter],
|
|
|
|
argname_fmt: str | None,
|
2023-08-28 10:04:27 -03:00
|
|
|
*,
|
2023-09-03 11:28:14 -03:00
|
|
|
fastcall: bool,
|
2023-08-28 10:04:27 -03:00
|
|
|
limited_capi: bool,
|
2023-08-31 18:42:34 -03:00
|
|
|
clinic: Clinic,
|
2023-08-19 04:13:35 -03:00
|
|
|
) -> str:
|
|
|
|
assert len(params) > 0
|
|
|
|
last_param = next(reversed(params.values()))
|
|
|
|
|
|
|
|
# Format the deprecation message.
|
|
|
|
containscheck = ""
|
|
|
|
conditions = []
|
|
|
|
for i, p in params.items():
|
|
|
|
if p.is_optional():
|
|
|
|
if argname_fmt:
|
|
|
|
conditions.append(f"nargs < {i+1} && {argname_fmt % i}")
|
2023-09-03 11:28:14 -03:00
|
|
|
elif fastcall:
|
2023-08-19 04:13:35 -03:00
|
|
|
conditions.append(f"nargs < {i+1} && PySequence_Contains(kwnames, &_Py_ID({p.name}))")
|
|
|
|
containscheck = "PySequence_Contains"
|
2023-08-31 18:42:34 -03:00
|
|
|
clinic.add_include('pycore_runtime.h', '_Py_ID()')
|
2023-09-03 11:28:14 -03:00
|
|
|
else:
|
|
|
|
conditions.append(f"nargs < {i+1} && PyDict_Contains(kwargs, &_Py_ID({p.name}))")
|
|
|
|
containscheck = "PyDict_Contains"
|
|
|
|
clinic.add_include('pycore_runtime.h', '_Py_ID()')
|
2023-08-19 04:13:35 -03:00
|
|
|
else:
|
|
|
|
conditions = [f"nargs < {i+1}"]
|
|
|
|
condition = ") || (".join(conditions)
|
|
|
|
if len(conditions) > 1:
|
|
|
|
condition = f"(({condition}))"
|
|
|
|
if last_param.is_optional():
|
2023-09-03 11:28:14 -03:00
|
|
|
if fastcall:
|
|
|
|
if limited_capi:
|
|
|
|
condition = f"kwnames && PyTuple_Size(kwnames) && {condition}"
|
|
|
|
else:
|
|
|
|
condition = f"kwnames && PyTuple_GET_SIZE(kwnames) && {condition}"
|
2023-08-19 04:13:35 -03:00
|
|
|
else:
|
2023-09-03 11:28:14 -03:00
|
|
|
if limited_capi:
|
|
|
|
condition = f"kwargs && PyDict_Size(kwargs) && {condition}"
|
|
|
|
else:
|
|
|
|
condition = f"kwargs && PyDict_GET_SIZE(kwargs) && {condition}"
|
2023-08-21 10:59:58 -03:00
|
|
|
names = [repr(p.name) for p in params.values()]
|
2023-12-22 20:37:39 -04:00
|
|
|
pstr = libclinic.pprint_words(names)
|
2023-08-21 10:59:58 -03:00
|
|
|
pl = 's' if len(params) != 1 else ''
|
2023-08-19 04:13:35 -03:00
|
|
|
message = (
|
2023-08-21 10:59:58 -03:00
|
|
|
f"Passing keyword argument{pl} {pstr} to "
|
|
|
|
f"{func.fulldisplayname}() is deprecated."
|
2023-08-19 04:13:35 -03:00
|
|
|
)
|
2023-08-21 10:59:58 -03:00
|
|
|
|
|
|
|
for (major, minor), group in itertools.groupby(
|
|
|
|
params.values(), key=attrgetter("deprecated_keyword")
|
|
|
|
):
|
|
|
|
names = [repr(p.name) for p in group]
|
2023-12-22 20:37:39 -04:00
|
|
|
pstr = libclinic.pprint_words(names)
|
2023-08-21 10:59:58 -03:00
|
|
|
pl = 's' if len(names) != 1 else ''
|
|
|
|
message += (
|
|
|
|
f" Parameter{pl} {pstr} will become positional-only "
|
|
|
|
f"in Python {major}.{minor}."
|
|
|
|
)
|
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
if containscheck:
|
|
|
|
errcheck = f"""
|
|
|
|
if (PyErr_Occurred()) {{{{ // {containscheck}() above can fail
|
|
|
|
goto exit;
|
|
|
|
}}}}"""
|
|
|
|
else:
|
|
|
|
errcheck = ""
|
|
|
|
if argname_fmt:
|
|
|
|
# Append deprecation warning to docstring.
|
|
|
|
docstring = textwrap.fill(f"Note: {message}")
|
|
|
|
func.docstring += f"\n\n{docstring}\n"
|
2023-08-07 08:28:08 -03:00
|
|
|
# Format and return the code block.
|
2023-08-19 04:13:35 -03:00
|
|
|
code = self.DEPRECATION_WARNING_PROTOTYPE.format(
|
2023-08-07 08:28:08 -03:00
|
|
|
condition=condition,
|
2023-08-19 04:13:35 -03:00
|
|
|
errcheck=errcheck,
|
2023-12-22 20:37:39 -04:00
|
|
|
message=libclinic.wrapped_c_string_literal(message, width=64,
|
|
|
|
subsequent_indent=20),
|
2023-08-07 08:28:08 -03:00
|
|
|
)
|
2023-12-23 13:08:10 -04:00
|
|
|
return libclinic.normalize_snippet(code, indent=4)
|
2023-08-07 08:28:08 -03:00
|
|
|
|
2023-07-14 09:20:58 -03:00
|
|
|
def output_templates(
|
|
|
|
self,
|
2023-07-29 15:47:42 -03:00
|
|
|
f: Function,
|
|
|
|
clinic: Clinic
|
2023-07-14 09:20:58 -03:00
|
|
|
) -> dict[str, str]:
|
2014-01-17 21:47:17 -04:00
|
|
|
parameters = list(f.parameters.values())
|
2014-01-24 10:17:25 -04:00
|
|
|
assert parameters
|
2023-07-14 09:20:58 -03:00
|
|
|
first_param = parameters.pop(0)
|
|
|
|
assert isinstance(first_param.converter, self_converter)
|
2022-04-30 07:15:02 -03:00
|
|
|
requires_defining_class = False
|
|
|
|
if parameters and isinstance(parameters[0].converter, defining_class_converter):
|
|
|
|
requires_defining_class = True
|
|
|
|
del parameters[0]
|
2014-01-17 21:47:17 -04:00
|
|
|
converters = [p.converter for p in parameters]
|
|
|
|
|
2023-11-18 21:13:58 -04:00
|
|
|
if f.critical_section:
|
|
|
|
clinic.add_include('pycore_critical_section.h', 'Py_BEGIN_CRITICAL_SECTION()')
|
2014-01-17 21:47:17 -04:00
|
|
|
has_option_groups = parameters and (parameters[0].group or parameters[-1].group)
|
2023-11-14 06:47:46 -04:00
|
|
|
simple_return = (f.return_converter.type == 'PyObject *'
|
|
|
|
and not f.critical_section)
|
2023-07-13 19:54:05 -03:00
|
|
|
new_or_init = f.kind.new_or_init
|
2014-01-19 03:50:21 -04:00
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
vararg: int | str = self.NO_VARARG
|
2021-07-16 12:43:02 -03:00
|
|
|
pos_only = min_pos = max_pos = min_kw_only = pseudo_args = 0
|
2019-03-14 05:32:22 -03:00
|
|
|
for i, p in enumerate(parameters, 1):
|
2022-11-24 15:56:50 -04:00
|
|
|
if p.is_keyword_only():
|
2019-03-14 05:32:22 -03:00
|
|
|
assert not p.is_positional_only()
|
|
|
|
if not p.is_optional():
|
|
|
|
min_kw_only = i - max_pos
|
2021-07-16 12:43:02 -03:00
|
|
|
elif p.is_vararg():
|
|
|
|
pseudo_args += 1
|
|
|
|
vararg = i - 1
|
2019-03-14 05:32:22 -03:00
|
|
|
else:
|
2023-12-22 20:37:39 -04:00
|
|
|
if vararg == self.NO_VARARG:
|
2021-07-16 12:43:02 -03:00
|
|
|
max_pos = i
|
2019-03-14 05:32:22 -03:00
|
|
|
if p.is_positional_only():
|
|
|
|
pos_only = i
|
|
|
|
if not p.is_optional():
|
|
|
|
min_pos = i
|
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
meth_o = (len(parameters) == 1 and
|
2016-06-09 10:30:29 -03:00
|
|
|
parameters[0].is_positional_only() and
|
2014-01-17 21:47:17 -04:00
|
|
|
not converters[0].is_optional() and
|
2020-05-07 10:39:59 -03:00
|
|
|
not requires_defining_class and
|
2014-01-19 03:50:21 -04:00
|
|
|
not new_or_init)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2014-02-01 02:03:12 -04:00
|
|
|
# we have to set these things before we're done:
|
2014-01-17 21:47:17 -04:00
|
|
|
#
|
|
|
|
# docstring_prototype
|
|
|
|
# docstring_definition
|
|
|
|
# impl_prototype
|
|
|
|
# methoddef_define
|
|
|
|
# parser_prototype
|
|
|
|
# parser_definition
|
|
|
|
# impl_definition
|
2014-02-01 02:03:12 -04:00
|
|
|
# cpp_if
|
|
|
|
# cpp_endif
|
|
|
|
# methoddef_ifndef
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
return_value_declaration = "PyObject *return_value = NULL;"
|
2023-08-02 16:37:36 -03:00
|
|
|
methoddef_define = self.METHODDEF_PROTOTYPE_DEFINE
|
2014-01-24 10:17:25 -04:00
|
|
|
if new_or_init and not f.docstring:
|
|
|
|
docstring_prototype = docstring_definition = ''
|
2023-11-30 06:40:53 -04:00
|
|
|
elif f.kind is GETTER:
|
|
|
|
methoddef_define = self.GETTERDEF_PROTOTYPE_DEFINE
|
2023-12-20 08:52:12 -04:00
|
|
|
if f.docstring:
|
|
|
|
docstring_prototype = ''
|
|
|
|
docstring_definition = self.GETSET_DOCSTRING_PROTOTYPE_STRVAR
|
|
|
|
else:
|
|
|
|
docstring_prototype = docstring_definition = ''
|
2023-12-13 10:00:34 -04:00
|
|
|
elif f.kind is SETTER:
|
2023-12-20 08:52:12 -04:00
|
|
|
if f.docstring:
|
|
|
|
fail("docstrings are only supported for @getter, not @setter")
|
2023-12-13 10:00:34 -04:00
|
|
|
return_value_declaration = "int {return_value};"
|
|
|
|
methoddef_define = self.SETTERDEF_PROTOTYPE_DEFINE
|
2023-12-20 08:52:12 -04:00
|
|
|
docstring_prototype = docstring_definition = ''
|
2014-01-24 10:17:25 -04:00
|
|
|
else:
|
2023-08-02 16:37:36 -03:00
|
|
|
docstring_prototype = self.DOCSTRING_PROTOTYPE_VAR
|
|
|
|
docstring_definition = self.DOCSTRING_PROTOTYPE_STRVAR
|
|
|
|
impl_definition = self.IMPL_DEFINITION_PROTOTYPE
|
2014-01-17 21:47:17 -04:00
|
|
|
impl_prototype = parser_prototype = parser_definition = None
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-02-01 02:03:12 -04:00
|
|
|
# parser_body_fields remembers the fields passed in to the
|
|
|
|
# previous call to parser_body. this is used for an awful hack.
|
2023-07-14 09:20:58 -03:00
|
|
|
parser_body_fields: tuple[str, ...] = ()
|
2023-07-12 19:49:30 -03:00
|
|
|
def parser_body(
|
|
|
|
prototype: str,
|
|
|
|
*fields: str,
|
|
|
|
declarations: str = ''
|
|
|
|
) -> str:
|
2023-05-05 18:35:24 -03:00
|
|
|
nonlocal parser_body_fields
|
2023-12-22 16:28:15 -04:00
|
|
|
lines = []
|
|
|
|
lines.append(prototype)
|
2014-01-19 03:50:21 -04:00
|
|
|
parser_body_fields = fields
|
2014-02-01 02:03:12 -04:00
|
|
|
|
2023-12-23 13:08:10 -04:00
|
|
|
preamble = libclinic.normalize_snippet("""
|
2014-02-01 02:03:12 -04:00
|
|
|
{{
|
|
|
|
{return_value_declaration}
|
2019-03-14 05:32:22 -03:00
|
|
|
{parser_declarations}
|
2014-02-01 02:03:12 -04:00
|
|
|
{declarations}
|
|
|
|
{initializers}
|
2023-07-12 19:49:30 -03:00
|
|
|
""") + "\n"
|
2023-12-23 13:08:10 -04:00
|
|
|
finale = libclinic.normalize_snippet("""
|
2014-02-01 02:03:12 -04:00
|
|
|
{modifications}
|
2023-11-14 06:47:46 -04:00
|
|
|
{lock}
|
2014-02-01 02:03:12 -04:00
|
|
|
{return_value} = {c_basename}_impl({impl_arguments});
|
2023-11-14 06:47:46 -04:00
|
|
|
{unlock}
|
2014-02-01 02:03:12 -04:00
|
|
|
{return_conversion}
|
2022-11-24 10:01:26 -04:00
|
|
|
{post_parsing}
|
2014-02-01 02:03:12 -04:00
|
|
|
|
|
|
|
{exit_label}
|
|
|
|
{cleanup}
|
|
|
|
return return_value;
|
|
|
|
}}
|
2023-07-12 19:49:30 -03:00
|
|
|
""")
|
|
|
|
for field in preamble, *fields, finale:
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append(field)
|
2024-02-15 18:52:20 -04:00
|
|
|
return libclinic.linear_format("\n".join(lines),
|
|
|
|
parser_declarations=declarations)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
fastcall = not new_or_init
|
2023-08-28 10:04:27 -03:00
|
|
|
limited_capi = clinic.limited_capi
|
2023-10-17 08:46:16 -03:00
|
|
|
if limited_capi and (pseudo_args or
|
2023-08-28 10:04:27 -03:00
|
|
|
(any(p.is_optional() for p in parameters) and
|
|
|
|
any(p.is_keyword_only() and not p.is_optional() for p in parameters)) or
|
|
|
|
any(c.broken_limited_capi for c in converters)):
|
|
|
|
warn(f"Function {f.full_name} cannot use limited C API")
|
|
|
|
limited_capi = False
|
|
|
|
|
2023-07-17 08:47:08 -03:00
|
|
|
parsearg: str | None
|
2014-01-17 21:47:17 -04:00
|
|
|
if not parameters:
|
2023-07-14 09:20:58 -03:00
|
|
|
parser_code: list[str] | None
|
2023-11-30 06:40:53 -04:00
|
|
|
if f.kind is GETTER:
|
|
|
|
flags = "" # This should end up unused
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_GETTER
|
|
|
|
parser_code = []
|
2023-12-13 10:00:34 -04:00
|
|
|
elif f.kind is SETTER:
|
|
|
|
flags = ""
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_SETTER
|
|
|
|
parser_code = []
|
2023-11-30 06:40:53 -04:00
|
|
|
elif not requires_defining_class:
|
2022-04-30 07:15:02 -03:00
|
|
|
# no parameters, METH_NOARGS
|
|
|
|
flags = "METH_NOARGS"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_NOARGS
|
2022-04-30 07:15:02 -03:00
|
|
|
parser_code = []
|
|
|
|
else:
|
2023-09-03 11:28:14 -03:00
|
|
|
assert fastcall
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2022-04-30 07:15:02 -03:00
|
|
|
flags = "METH_METHOD|METH_FASTCALL|METH_KEYWORDS"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_DEF_CLASS
|
2023-11-14 06:47:46 -04:00
|
|
|
return_error = ('return NULL;' if simple_return
|
2022-04-30 07:15:02 -03:00
|
|
|
else 'goto exit;')
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2024-02-05 16:49:17 -04:00
|
|
|
if (nargs || (kwnames && PyTuple_GET_SIZE(kwnames))) {{
|
2022-04-30 07:15:02 -03:00
|
|
|
PyErr_SetString(PyExc_TypeError, "{name}() takes no arguments");
|
|
|
|
%s
|
2014-02-01 02:03:12 -04:00
|
|
|
}}
|
2022-04-30 07:15:02 -03:00
|
|
|
""" % return_error, indent=4)]
|
|
|
|
|
2023-11-14 06:47:46 -04:00
|
|
|
if simple_return:
|
2022-04-30 07:15:02 -03:00
|
|
|
parser_definition = '\n'.join([
|
|
|
|
parser_prototype,
|
|
|
|
'{{',
|
|
|
|
*parser_code,
|
|
|
|
' return {c_basename}_impl({impl_arguments});',
|
|
|
|
'}}'])
|
2014-01-17 21:47:17 -04:00
|
|
|
else:
|
2022-04-30 07:15:02 -03:00
|
|
|
parser_definition = parser_body(parser_prototype, *parser_code)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
elif meth_o:
|
2014-01-19 03:50:21 -04:00
|
|
|
flags = "METH_O"
|
2014-02-01 02:03:12 -04:00
|
|
|
|
2015-04-03 18:12:11 -03:00
|
|
|
if (isinstance(converters[0], object_converter) and
|
|
|
|
converters[0].format_unit == 'O'):
|
2023-08-02 16:37:36 -03:00
|
|
|
meth_o_prototype = self.METH_O_PROTOTYPE
|
2015-04-03 18:12:11 -03:00
|
|
|
|
2023-11-14 06:47:46 -04:00
|
|
|
if simple_return:
|
2015-04-03 18:12:11 -03:00
|
|
|
# maps perfectly to METH_O, doesn't need a return converter.
|
|
|
|
# so we skip making a parse function
|
|
|
|
# and call directly into the impl function.
|
|
|
|
impl_prototype = parser_prototype = parser_definition = ''
|
|
|
|
impl_definition = meth_o_prototype
|
|
|
|
else:
|
|
|
|
# SLIGHT HACK
|
|
|
|
# use impl_parameters for the parser here!
|
|
|
|
parser_prototype = meth_o_prototype
|
|
|
|
parser_definition = parser_body(parser_prototype)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
else:
|
2015-04-03 18:12:11 -03:00
|
|
|
argname = 'arg'
|
|
|
|
if parameters[0].name == argname:
|
|
|
|
argname += '_'
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_prototype = libclinic.normalize_snippet("""
|
2015-04-03 18:12:11 -03:00
|
|
|
static PyObject *
|
|
|
|
{c_basename}({self_type}{self_name}, PyObject *%s)
|
|
|
|
""" % argname)
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
displayname = parameters[0].get_displayname(0)
|
|
|
|
parsearg = converters[0].parse_arg(argname, displayname, limited_capi=limited_capi)
|
2019-01-11 10:01:14 -04:00
|
|
|
if parsearg is None:
|
2024-03-14 09:57:02 -03:00
|
|
|
converters[0].use_converter()
|
2019-01-11 10:01:14 -04:00
|
|
|
parsearg = """
|
|
|
|
if (!PyArg_Parse(%s, "{format_units}:{name}", {parse_arguments})) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""" % argname
|
2018-12-25 07:23:47 -04:00
|
|
|
parser_definition = parser_body(parser_prototype,
|
2023-12-23 13:08:10 -04:00
|
|
|
libclinic.normalize_snippet(parsearg, indent=4))
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
elif has_option_groups:
|
|
|
|
# positional parameters with option groups
|
|
|
|
# (we have to generate lots of PyArg_ParseTuple calls
|
|
|
|
# in a big switch statement)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
flags = "METH_VARARGS"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_VARARGS
|
2014-02-01 02:03:12 -04:00
|
|
|
parser_definition = parser_body(parser_prototype, ' {option_group_parsing}')
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2021-07-16 12:43:02 -03:00
|
|
|
elif not requires_defining_class and pos_only == len(parameters) - pseudo_args:
|
2023-09-03 11:28:14 -03:00
|
|
|
if fastcall:
|
2017-01-16 20:42:54 -04:00
|
|
|
# positional-only, but no option groups
|
|
|
|
# we only need one call to _PyArg_ParseStack
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2017-01-16 20:42:54 -04:00
|
|
|
flags = "METH_FASTCALL"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_FASTCALL
|
2019-01-11 10:01:14 -04:00
|
|
|
nargs = 'nargs'
|
|
|
|
argname_fmt = 'args[%d]'
|
2017-01-16 20:42:54 -04:00
|
|
|
else:
|
|
|
|
# positional-only, but no option groups
|
|
|
|
# we only need one call to PyArg_ParseTuple
|
|
|
|
|
|
|
|
flags = "METH_VARARGS"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_VARARGS
|
2023-09-03 11:28:14 -03:00
|
|
|
if limited_capi:
|
|
|
|
nargs = 'PyTuple_Size(args)'
|
|
|
|
argname_fmt = 'PyTuple_GetItem(args, %d)'
|
|
|
|
else:
|
|
|
|
nargs = 'PyTuple_GET_SIZE(args)'
|
|
|
|
argname_fmt = 'PyTuple_GET_ITEM(args, %d)'
|
2019-01-11 10:01:14 -04:00
|
|
|
|
2023-05-20 17:16:49 -03:00
|
|
|
left_args = f"{nargs} - {max_pos}"
|
2023-12-22 20:37:39 -04:00
|
|
|
max_args = self.NO_VARARG if (vararg != self.NO_VARARG) else max_pos
|
2023-09-03 11:28:14 -03:00
|
|
|
if limited_capi:
|
|
|
|
parser_code = []
|
|
|
|
if nargs != 'nargs':
|
2023-12-23 13:08:10 -04:00
|
|
|
nargs_def = f'Py_ssize_t nargs = {nargs};'
|
|
|
|
parser_code.append(libclinic.normalize_snippet(nargs_def, indent=4))
|
2023-09-03 11:28:14 -03:00
|
|
|
nargs = 'nargs'
|
|
|
|
if min_pos == max_args:
|
|
|
|
pl = '' if min_pos == 1 else 's'
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(f"""
|
2023-09-03 11:28:14 -03:00
|
|
|
if ({nargs} != {min_pos}) {{{{
|
|
|
|
PyErr_Format(PyExc_TypeError, "{{name}} expected {min_pos} argument{pl}, got %zd", {nargs});
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
indent=4))
|
|
|
|
else:
|
|
|
|
if min_pos:
|
|
|
|
pl = '' if min_pos == 1 else 's'
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(f"""
|
2023-09-03 11:28:14 -03:00
|
|
|
if ({nargs} < {min_pos}) {{{{
|
|
|
|
PyErr_Format(PyExc_TypeError, "{{name}} expected at least {min_pos} argument{pl}, got %zd", {nargs});
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
indent=4))
|
2023-12-22 20:37:39 -04:00
|
|
|
if max_args != self.NO_VARARG:
|
2023-09-03 11:28:14 -03:00
|
|
|
pl = '' if max_args == 1 else 's'
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(f"""
|
2023-09-03 11:28:14 -03:00
|
|
|
if ({nargs} > {max_args}) {{{{
|
|
|
|
PyErr_Format(PyExc_TypeError, "{{name}} expected at most {max_args} argument{pl}, got %zd", {nargs});
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
indent=4))
|
|
|
|
else:
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_CheckPositional()')
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet(f"""
|
2023-09-03 11:28:14 -03:00
|
|
|
if (!_PyArg_CheckPositional("{{name}}", {nargs}, {min_pos}, {max_args})) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""", indent=4)]
|
2021-07-16 12:43:02 -03:00
|
|
|
|
2019-01-11 10:01:14 -04:00
|
|
|
has_optional = False
|
2019-03-14 05:32:22 -03:00
|
|
|
for i, p in enumerate(parameters):
|
2021-07-16 12:43:02 -03:00
|
|
|
if p.is_vararg():
|
2023-09-03 11:28:14 -03:00
|
|
|
if fastcall:
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2021-07-16 12:43:02 -03:00
|
|
|
%s = PyTuple_New(%s);
|
2022-12-28 00:16:28 -04:00
|
|
|
if (!%s) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
2021-07-16 12:43:02 -03:00
|
|
|
for (Py_ssize_t i = 0; i < %s; ++i) {{
|
2022-11-24 08:24:18 -04:00
|
|
|
PyTuple_SET_ITEM(%s, i, Py_NewRef(args[%d + i]));
|
2021-07-16 12:43:02 -03:00
|
|
|
}}
|
|
|
|
""" % (
|
|
|
|
p.converter.parser_name,
|
|
|
|
left_args,
|
2022-12-28 00:16:28 -04:00
|
|
|
p.converter.parser_name,
|
2021-07-16 12:43:02 -03:00
|
|
|
left_args,
|
|
|
|
p.converter.parser_name,
|
|
|
|
max_pos
|
|
|
|
), indent=4))
|
|
|
|
else:
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2021-07-16 12:43:02 -03:00
|
|
|
%s = PyTuple_GetSlice(%d, -1);
|
|
|
|
""" % (
|
|
|
|
p.converter.parser_name,
|
|
|
|
max_pos
|
|
|
|
), indent=4))
|
|
|
|
continue
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
displayname = p.get_displayname(i+1)
|
|
|
|
argname = argname_fmt % i
|
|
|
|
parsearg = p.converter.parse_arg(argname, displayname, limited_capi=limited_capi)
|
2019-01-11 10:01:14 -04:00
|
|
|
if parsearg is None:
|
|
|
|
parser_code = None
|
|
|
|
break
|
2019-03-14 05:32:22 -03:00
|
|
|
if has_optional or p.is_optional():
|
2019-01-11 10:01:14 -04:00
|
|
|
has_optional = True
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2019-01-11 10:01:14 -04:00
|
|
|
if (%s < %d) {{
|
|
|
|
goto skip_optional;
|
|
|
|
}}
|
|
|
|
""", indent=4) % (nargs, i + 1))
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(parsearg, indent=4))
|
2017-01-16 20:42:54 -04:00
|
|
|
|
2019-01-11 10:01:14 -04:00
|
|
|
if parser_code is not None:
|
|
|
|
if has_optional:
|
|
|
|
parser_code.append("skip_optional:")
|
|
|
|
else:
|
2024-03-14 09:57:02 -03:00
|
|
|
for parameter in parameters:
|
|
|
|
parameter.converter.use_converter()
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
if limited_capi:
|
|
|
|
fastcall = False
|
|
|
|
if fastcall:
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_ParseStack()')
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2019-01-11 10:01:14 -04:00
|
|
|
if (!_PyArg_ParseStack(args, nargs, "{format_units}:{name}",
|
|
|
|
{parse_arguments})) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""", indent=4)]
|
|
|
|
else:
|
2023-09-03 11:28:14 -03:00
|
|
|
flags = "METH_VARARGS"
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_VARARGS
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2019-01-11 10:01:14 -04:00
|
|
|
if (!PyArg_ParseTuple(args, "{format_units}:{name}",
|
|
|
|
{parse_arguments})) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""", indent=4)]
|
|
|
|
parser_definition = parser_body(parser_prototype, *parser_code)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
else:
|
2023-08-19 04:13:35 -03:00
|
|
|
deprecated_positionals: dict[int, Parameter] = {}
|
|
|
|
deprecated_keywords: dict[int, Parameter] = {}
|
|
|
|
for i, p in enumerate(parameters):
|
|
|
|
if p.deprecated_positional:
|
|
|
|
deprecated_positionals[i] = p
|
|
|
|
if p.deprecated_keyword:
|
|
|
|
deprecated_keywords[i] = p
|
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
has_optional_kw = (
|
|
|
|
max(pos_only, min_pos) + min_kw_only
|
|
|
|
< len(converters) - int(vararg != self.NO_VARARG)
|
|
|
|
)
|
2023-08-25 18:22:08 -03:00
|
|
|
|
2023-08-28 10:04:27 -03:00
|
|
|
if limited_capi:
|
2023-09-03 11:28:14 -03:00
|
|
|
parser_code = None
|
|
|
|
fastcall = False
|
2019-03-14 05:32:22 -03:00
|
|
|
else:
|
2023-12-22 20:37:39 -04:00
|
|
|
if vararg == self.NO_VARARG:
|
2023-10-20 18:42:02 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_UnpackKeywords()')
|
|
|
|
args_declaration = "_PyArg_UnpackKeywords", "%s, %s, %s" % (
|
|
|
|
min_pos,
|
|
|
|
max_pos,
|
|
|
|
min_kw_only
|
|
|
|
)
|
|
|
|
nargs = "nargs"
|
|
|
|
else:
|
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_UnpackKeywordsWithVararg()')
|
|
|
|
args_declaration = "_PyArg_UnpackKeywordsWithVararg", "%s, %s, %s, %s" % (
|
|
|
|
min_pos,
|
|
|
|
max_pos,
|
|
|
|
min_kw_only,
|
|
|
|
vararg
|
|
|
|
)
|
|
|
|
nargs = f"Py_MIN(nargs, {max_pos})" if max_pos else "0"
|
|
|
|
|
|
|
|
if fastcall:
|
|
|
|
flags = "METH_FASTCALL|METH_KEYWORDS"
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_FASTCALL_KEYWORDS
|
|
|
|
argname_fmt = 'args[%d]'
|
|
|
|
declarations = declare_parser(f, clinic=clinic,
|
|
|
|
limited_capi=clinic.limited_capi)
|
|
|
|
declarations += "\nPyObject *argsbuf[%s];" % len(converters)
|
|
|
|
if has_optional_kw:
|
|
|
|
declarations += "\nPy_ssize_t noptargs = %s + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - %d;" % (nargs, min_pos + min_kw_only)
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2023-10-20 18:42:02 -03:00
|
|
|
args = %s(args, nargs, NULL, kwnames, &_parser, %s, argsbuf);
|
|
|
|
if (!args) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""" % args_declaration, indent=4)]
|
|
|
|
else:
|
|
|
|
# positional-or-keyword arguments
|
|
|
|
flags = "METH_VARARGS|METH_KEYWORDS"
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_KEYWORD
|
|
|
|
argname_fmt = 'fastargs[%d]'
|
|
|
|
declarations = declare_parser(f, clinic=clinic,
|
|
|
|
limited_capi=clinic.limited_capi)
|
|
|
|
declarations += "\nPyObject *argsbuf[%s];" % len(converters)
|
|
|
|
declarations += "\nPyObject * const *fastargs;"
|
|
|
|
declarations += "\nPy_ssize_t nargs = PyTuple_GET_SIZE(args);"
|
|
|
|
if has_optional_kw:
|
|
|
|
declarations += "\nPy_ssize_t noptargs = %s + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - %d;" % (nargs, min_pos + min_kw_only)
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2023-10-20 18:42:02 -03:00
|
|
|
fastargs = %s(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, %s, argsbuf);
|
|
|
|
if (!fastargs) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""" % args_declaration, indent=4)]
|
2021-07-16 12:43:02 -03:00
|
|
|
|
2020-05-07 10:39:59 -03:00
|
|
|
if requires_defining_class:
|
|
|
|
flags = 'METH_METHOD|' + flags
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_DEF_CLASS
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
if parser_code is not None:
|
2023-08-28 10:04:27 -03:00
|
|
|
if deprecated_keywords:
|
|
|
|
code = self.deprecate_keyword_use(f, deprecated_keywords, argname_fmt,
|
2023-09-03 11:28:14 -03:00
|
|
|
clinic=clinic,
|
|
|
|
fastcall=fastcall,
|
|
|
|
limited_capi=limited_capi)
|
2023-08-28 10:04:27 -03:00
|
|
|
parser_code.append(code)
|
2023-08-19 04:13:35 -03:00
|
|
|
|
2023-08-28 10:04:27 -03:00
|
|
|
add_label: str | None = None
|
|
|
|
for i, p in enumerate(parameters):
|
|
|
|
if isinstance(p.converter, defining_class_converter):
|
|
|
|
raise ValueError("defining_class should be the first "
|
|
|
|
"parameter (after self)")
|
|
|
|
displayname = p.get_displayname(i+1)
|
2023-09-03 11:28:14 -03:00
|
|
|
parsearg = p.converter.parse_arg(argname_fmt % i, displayname, limited_capi=limited_capi)
|
2023-08-28 10:04:27 -03:00
|
|
|
if parsearg is None:
|
|
|
|
parser_code = None
|
|
|
|
break
|
|
|
|
if add_label and (i == pos_only or i == max_pos):
|
|
|
|
parser_code.append("%s:" % add_label)
|
|
|
|
add_label = None
|
|
|
|
if not p.is_optional():
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(parsearg, indent=4))
|
2023-08-28 10:04:27 -03:00
|
|
|
elif i < pos_only:
|
|
|
|
add_label = 'skip_optional_posonly'
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2023-08-28 10:04:27 -03:00
|
|
|
if (nargs < %d) {{
|
2019-03-14 05:32:22 -03:00
|
|
|
goto %s;
|
|
|
|
}}
|
2023-08-28 10:04:27 -03:00
|
|
|
""" % (i + 1, add_label), indent=4))
|
|
|
|
if has_optional_kw:
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2023-08-28 10:04:27 -03:00
|
|
|
noptargs--;
|
|
|
|
""", indent=4))
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(parsearg, indent=4))
|
2019-03-14 05:32:22 -03:00
|
|
|
else:
|
2023-08-28 10:04:27 -03:00
|
|
|
if i < max_pos:
|
|
|
|
label = 'skip_optional_pos'
|
|
|
|
first_opt = max(min_pos, pos_only)
|
|
|
|
else:
|
|
|
|
label = 'skip_optional_kwonly'
|
|
|
|
first_opt = max_pos + min_kw_only
|
2023-12-22 20:37:39 -04:00
|
|
|
if vararg != self.NO_VARARG:
|
2023-08-28 10:04:27 -03:00
|
|
|
first_opt += 1
|
|
|
|
if i == first_opt:
|
|
|
|
add_label = label
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2023-08-28 10:04:27 -03:00
|
|
|
if (!noptargs) {{
|
2019-03-14 05:32:22 -03:00
|
|
|
goto %s;
|
|
|
|
}}
|
2023-08-28 10:04:27 -03:00
|
|
|
""" % add_label, indent=4))
|
|
|
|
if i + 1 == len(parameters):
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(parsearg, indent=4))
|
2023-08-28 10:04:27 -03:00
|
|
|
else:
|
|
|
|
add_label = label
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2023-08-28 10:04:27 -03:00
|
|
|
if (%s) {{
|
|
|
|
""" % (argname_fmt % i), indent=4))
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code.append(libclinic.normalize_snippet(parsearg, indent=8))
|
|
|
|
parser_code.append(libclinic.normalize_snippet("""
|
2023-08-28 10:04:27 -03:00
|
|
|
if (!--noptargs) {{
|
|
|
|
goto %s;
|
|
|
|
}}
|
|
|
|
}}
|
|
|
|
""" % add_label, indent=4))
|
2014-02-01 02:03:12 -04:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
if parser_code is not None:
|
|
|
|
if add_label:
|
|
|
|
parser_code.append("%s:" % add_label)
|
|
|
|
else:
|
2024-03-14 09:57:02 -03:00
|
|
|
for parameter in parameters:
|
|
|
|
parameter.converter.use_converter()
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
declarations = declare_parser(f, clinic=clinic,
|
|
|
|
hasformat=True,
|
|
|
|
limited_capi=limited_capi)
|
|
|
|
if limited_capi:
|
|
|
|
# positional-or-keyword arguments
|
|
|
|
assert not fastcall
|
|
|
|
flags = "METH_VARARGS|METH_KEYWORDS"
|
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_KEYWORD
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2023-09-03 11:28:14 -03:00
|
|
|
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "{format_units}:{name}", _keywords,
|
|
|
|
{parse_arguments}))
|
|
|
|
goto exit;
|
|
|
|
""", indent=4)]
|
|
|
|
declarations = "static char *_keywords[] = {{{keywords_c} NULL}};"
|
|
|
|
if deprecated_positionals or deprecated_keywords:
|
|
|
|
declarations += "\nPy_ssize_t nargs = PyTuple_Size(args);"
|
|
|
|
|
|
|
|
elif fastcall:
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_ParseStackAndKeywords()')
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2023-09-03 11:28:14 -03:00
|
|
|
if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser{parse_arguments_comma}
|
|
|
|
{parse_arguments})) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""", indent=4)]
|
2019-03-14 05:32:22 -03:00
|
|
|
else:
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_ParseTupleAndKeywordsFast()')
|
2023-12-23 13:08:10 -04:00
|
|
|
parser_code = [libclinic.normalize_snippet("""
|
2023-09-03 11:28:14 -03:00
|
|
|
if (!_PyArg_ParseTupleAndKeywordsFast(args, kwargs, &_parser,
|
|
|
|
{parse_arguments})) {{
|
|
|
|
goto exit;
|
|
|
|
}}
|
|
|
|
""", indent=4)]
|
|
|
|
if deprecated_positionals or deprecated_keywords:
|
|
|
|
declarations += "\nPy_ssize_t nargs = PyTuple_GET_SIZE(args);"
|
|
|
|
if deprecated_keywords:
|
|
|
|
code = self.deprecate_keyword_use(f, deprecated_keywords, None,
|
|
|
|
clinic=clinic,
|
|
|
|
fastcall=fastcall,
|
|
|
|
limited_capi=limited_capi)
|
|
|
|
parser_code.append(code)
|
2023-08-19 04:13:35 -03:00
|
|
|
|
|
|
|
if deprecated_positionals:
|
|
|
|
code = self.deprecate_positional_use(f, deprecated_positionals)
|
|
|
|
# Insert the deprecation code before parameter parsing.
|
|
|
|
parser_code.insert(0, code)
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
assert parser_prototype is not None
|
2019-03-14 05:32:22 -03:00
|
|
|
parser_definition = parser_body(parser_prototype, *parser_code,
|
|
|
|
declarations=declarations)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2024-01-23 06:07:56 -04:00
|
|
|
# Copy includes from parameters to Clinic after parse_arg() has been
|
|
|
|
# called above.
|
|
|
|
for converter in converters:
|
|
|
|
for include in converter.includes:
|
|
|
|
clinic.add_include(include.filename, include.reason,
|
|
|
|
condition=include.condition)
|
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
if new_or_init:
|
|
|
|
methoddef_define = ''
|
|
|
|
|
2023-07-13 19:54:05 -03:00
|
|
|
if f.kind is METHOD_NEW:
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_KEYWORD
|
2014-01-19 03:50:21 -04:00
|
|
|
else:
|
|
|
|
return_value_declaration = "int return_value = -1;"
|
2023-08-02 16:37:36 -03:00
|
|
|
parser_prototype = self.PARSER_PROTOTYPE_KEYWORD___INIT__
|
2014-01-19 03:50:21 -04:00
|
|
|
|
|
|
|
fields = list(parser_body_fields)
|
|
|
|
parses_positional = 'METH_NOARGS' not in flags
|
|
|
|
parses_keywords = 'METH_KEYWORDS' in flags
|
|
|
|
if parses_keywords:
|
|
|
|
assert parses_positional
|
|
|
|
|
2020-05-07 10:39:59 -03:00
|
|
|
if requires_defining_class:
|
|
|
|
raise ValueError("Slot methods cannot access their defining class.")
|
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
if not parses_keywords:
|
2023-01-31 16:42:03 -04:00
|
|
|
declarations = '{base_type_ptr}'
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_NoKeywords()')
|
2023-12-23 13:08:10 -04:00
|
|
|
fields.insert(0, libclinic.normalize_snippet("""
|
2016-06-09 10:16:06 -03:00
|
|
|
if ({self_type_check}!_PyArg_NoKeywords("{name}", kwargs)) {{
|
2014-02-01 02:03:12 -04:00
|
|
|
goto exit;
|
2016-06-09 10:16:06 -03:00
|
|
|
}}
|
2014-02-01 02:03:12 -04:00
|
|
|
""", indent=4))
|
2014-01-19 03:50:21 -04:00
|
|
|
if not parses_positional:
|
2023-10-17 09:30:31 -03:00
|
|
|
clinic.add_include('pycore_modsupport.h',
|
|
|
|
'_PyArg_NoPositional()')
|
2023-12-23 13:08:10 -04:00
|
|
|
fields.insert(0, libclinic.normalize_snippet("""
|
2016-06-09 10:16:06 -03:00
|
|
|
if ({self_type_check}!_PyArg_NoPositional("{name}", args)) {{
|
2014-02-01 02:03:12 -04:00
|
|
|
goto exit;
|
2016-06-09 10:16:06 -03:00
|
|
|
}}
|
2014-02-01 02:03:12 -04:00
|
|
|
""", indent=4))
|
2014-01-19 03:50:21 -04:00
|
|
|
|
2019-03-14 05:32:22 -03:00
|
|
|
parser_definition = parser_body(parser_prototype, *fields,
|
2023-01-31 16:42:03 -04:00
|
|
|
declarations=declarations)
|
2014-01-19 03:50:21 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-10-17 08:46:16 -03:00
|
|
|
methoddef_cast_end = ""
|
2018-11-27 05:27:36 -04:00
|
|
|
if flags in ('METH_NOARGS', 'METH_O', 'METH_VARARGS'):
|
|
|
|
methoddef_cast = "(PyCFunction)"
|
2023-11-30 06:40:53 -04:00
|
|
|
elif f.kind is GETTER:
|
|
|
|
methoddef_cast = "" # This should end up unused
|
2023-09-03 11:28:14 -03:00
|
|
|
elif limited_capi:
|
|
|
|
methoddef_cast = "(PyCFunction)(void(*)(void))"
|
2018-11-27 05:27:36 -04:00
|
|
|
else:
|
2022-05-03 15:25:41 -03:00
|
|
|
methoddef_cast = "_PyCFunction_CAST("
|
|
|
|
methoddef_cast_end = ")"
|
2018-11-27 05:27:36 -04:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
if f.methoddef_flags:
|
|
|
|
flags += '|' + f.methoddef_flags
|
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
methoddef_define = methoddef_define.replace('{methoddef_flags}', flags)
|
2018-11-27 05:27:36 -04:00
|
|
|
methoddef_define = methoddef_define.replace('{methoddef_cast}', methoddef_cast)
|
2022-05-03 15:25:41 -03:00
|
|
|
methoddef_define = methoddef_define.replace('{methoddef_cast_end}', methoddef_cast_end)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2014-02-01 02:03:12 -04:00
|
|
|
methoddef_ifndef = ''
|
|
|
|
conditional = self.cpp.condition()
|
|
|
|
if not conditional:
|
|
|
|
cpp_if = cpp_endif = ''
|
|
|
|
else:
|
|
|
|
cpp_if = "#if " + conditional
|
|
|
|
cpp_endif = "#endif /* " + conditional + " */"
|
|
|
|
|
2017-11-03 06:09:00 -03:00
|
|
|
if methoddef_define and f.full_name not in clinic.ifndef_symbols:
|
|
|
|
clinic.ifndef_symbols.add(f.full_name)
|
2023-08-02 16:37:36 -03:00
|
|
|
methoddef_ifndef = self.METHODDEF_PROTOTYPE_IFNDEF
|
2014-02-01 02:03:12 -04:00
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
# add ';' to the end of parser_prototype and impl_prototype
|
|
|
|
# (they mustn't be None, but they could be an empty string.)
|
2014-01-17 21:47:17 -04:00
|
|
|
assert parser_prototype is not None
|
|
|
|
if parser_prototype:
|
2014-01-19 03:50:21 -04:00
|
|
|
assert not parser_prototype.endswith(';')
|
2014-01-17 21:47:17 -04:00
|
|
|
parser_prototype += ';'
|
|
|
|
|
|
|
|
if impl_prototype is None:
|
2014-01-19 03:50:21 -04:00
|
|
|
impl_prototype = impl_definition
|
|
|
|
if impl_prototype:
|
|
|
|
impl_prototype += ";"
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
parser_definition = parser_definition.replace("{return_value_declaration}", return_value_declaration)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
compiler_warning = self.compiler_deprecated_warning(f, parameters)
|
|
|
|
if compiler_warning:
|
|
|
|
parser_definition = compiler_warning + "\n\n" + parser_definition
|
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
d = {
|
|
|
|
"docstring_prototype" : docstring_prototype,
|
|
|
|
"docstring_definition" : docstring_definition,
|
|
|
|
"impl_prototype" : impl_prototype,
|
|
|
|
"methoddef_define" : methoddef_define,
|
|
|
|
"parser_prototype" : parser_prototype,
|
|
|
|
"parser_definition" : parser_definition,
|
|
|
|
"impl_definition" : impl_definition,
|
2014-02-01 02:03:12 -04:00
|
|
|
"cpp_if" : cpp_if,
|
|
|
|
"cpp_endif" : cpp_endif,
|
|
|
|
"methoddef_ifndef" : methoddef_ifndef,
|
2014-01-17 21:47:17 -04:00
|
|
|
}
|
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
# make sure we didn't forget to assign something,
|
|
|
|
# and wrap each non-empty value in \n's
|
2014-01-17 21:47:17 -04:00
|
|
|
d2 = {}
|
|
|
|
for name, value in d.items():
|
2014-01-19 03:50:21 -04:00
|
|
|
assert value is not None, "got a None value for template " + repr(name)
|
2014-01-17 21:47:17 -04:00
|
|
|
if value:
|
|
|
|
value = '\n' + value + '\n'
|
|
|
|
d2[name] = value
|
|
|
|
return d2
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
@staticmethod
|
2023-07-04 20:07:57 -03:00
|
|
|
def group_to_variable_name(group: int) -> str:
|
2013-10-19 04:09:25 -03:00
|
|
|
adjective = "left_" if group < 0 else "right_"
|
|
|
|
return "group_" + adjective + str(abs(group))
|
|
|
|
|
2023-07-20 18:33:33 -03:00
|
|
|
def render_option_group_parsing(
|
|
|
|
self,
|
|
|
|
f: Function,
|
2023-08-29 08:33:28 -03:00
|
|
|
template_dict: TemplateDict,
|
|
|
|
limited_capi: bool,
|
2023-07-20 18:33:33 -03:00
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
# positional only, grouped, optional arguments!
|
|
|
|
# can be optional on the left or right.
|
|
|
|
# here's an example:
|
|
|
|
#
|
|
|
|
# [ [ [ A1 A2 ] B1 B2 B3 ] C1 C2 ] D1 D2 D3 [ E1 E2 E3 [ F1 F2 F3 ] ]
|
|
|
|
#
|
|
|
|
# Here group D are required, and all other groups are optional.
|
|
|
|
# (Group D's "group" is actually None.)
|
|
|
|
# We can figure out which sets of arguments we have based on
|
|
|
|
# how many arguments are in the tuple.
|
|
|
|
#
|
|
|
|
# Note that you need to count up on both sides. For example,
|
|
|
|
# you could have groups C+D, or C+D+E, or C+D+E+F.
|
|
|
|
#
|
|
|
|
# What if the number of arguments leads us to an ambiguous result?
|
|
|
|
# Clinic prefers groups on the left. So in the above example,
|
|
|
|
# five arguments would map to B+C, not C+D.
|
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
out = []
|
2013-10-19 04:09:25 -03:00
|
|
|
parameters = list(f.parameters.values())
|
2014-01-24 10:17:25 -04:00
|
|
|
if isinstance(parameters[0].converter, self_converter):
|
|
|
|
del parameters[0]
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-20 18:33:33 -03:00
|
|
|
group: list[Parameter] | None = None
|
2013-10-19 04:09:25 -03:00
|
|
|
left = []
|
|
|
|
right = []
|
2023-07-20 18:33:33 -03:00
|
|
|
required: list[Parameter] = []
|
|
|
|
last: int | Literal[Sentinels.unspecified] = unspecified
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
for p in parameters:
|
|
|
|
group_id = p.group
|
|
|
|
if group_id != last:
|
|
|
|
last = group_id
|
|
|
|
group = []
|
|
|
|
if group_id < 0:
|
|
|
|
left.append(group)
|
|
|
|
elif group_id == 0:
|
|
|
|
group = required
|
|
|
|
else:
|
|
|
|
right.append(group)
|
2023-07-20 18:33:33 -03:00
|
|
|
assert group is not None
|
2013-10-19 04:09:25 -03:00
|
|
|
group.append(p)
|
|
|
|
|
|
|
|
count_min = sys.maxsize
|
|
|
|
count_max = -1
|
|
|
|
|
2023-08-29 08:33:28 -03:00
|
|
|
if limited_capi:
|
|
|
|
nargs = 'PyTuple_Size(args)'
|
|
|
|
else:
|
|
|
|
nargs = 'PyTuple_GET_SIZE(args)'
|
2023-12-22 16:28:15 -04:00
|
|
|
out.append(f"switch ({nargs}) {{\n")
|
2013-10-19 04:09:25 -03:00
|
|
|
for subset in permute_optional_groups(left, required, right):
|
|
|
|
count = len(subset)
|
|
|
|
count_min = min(count_min, count)
|
|
|
|
count_max = max(count_max, count)
|
|
|
|
|
2014-01-12 12:49:30 -04:00
|
|
|
if count == 0:
|
2023-12-22 16:28:15 -04:00
|
|
|
out.append(""" case 0:
|
2014-01-12 12:49:30 -04:00
|
|
|
break;
|
|
|
|
""")
|
|
|
|
continue
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
group_ids = {p.group for p in subset} # eliminate duplicates
|
2023-07-20 18:33:33 -03:00
|
|
|
d: dict[str, str | int] = {}
|
2013-10-19 04:09:25 -03:00
|
|
|
d['count'] = count
|
|
|
|
d['name'] = f.name
|
|
|
|
d['format_units'] = "".join(p.converter.format_unit for p in subset)
|
|
|
|
|
2023-07-20 18:33:33 -03:00
|
|
|
parse_arguments: list[str] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
for p in subset:
|
|
|
|
p.converter.parse_argument(parse_arguments)
|
|
|
|
d['parse_arguments'] = ", ".join(parse_arguments)
|
|
|
|
|
|
|
|
group_ids.discard(0)
|
2023-07-20 18:33:33 -03:00
|
|
|
lines = "\n".join([
|
|
|
|
self.group_to_variable_name(g) + " = 1;"
|
|
|
|
for g in group_ids
|
|
|
|
])
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2020-01-06 06:46:04 -04:00
|
|
|
s = """\
|
2013-10-19 04:09:25 -03:00
|
|
|
case {count}:
|
2016-06-09 10:16:06 -03:00
|
|
|
if (!PyArg_ParseTuple(args, "{format_units}:{name}", {parse_arguments})) {{
|
2014-01-22 07:05:49 -04:00
|
|
|
goto exit;
|
2016-06-09 10:16:06 -03:00
|
|
|
}}
|
2013-10-19 04:09:25 -03:00
|
|
|
{group_booleans}
|
|
|
|
break;
|
2020-01-06 06:46:04 -04:00
|
|
|
"""
|
2024-02-15 18:52:20 -04:00
|
|
|
s = libclinic.linear_format(s, group_booleans=lines)
|
2013-10-19 04:09:25 -03:00
|
|
|
s = s.format_map(d)
|
2023-12-22 16:28:15 -04:00
|
|
|
out.append(s)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
out.append(" default:\n")
|
2013-10-19 04:09:25 -03:00
|
|
|
s = ' PyErr_SetString(PyExc_TypeError, "{} requires {} to {} arguments");\n'
|
2023-12-22 16:28:15 -04:00
|
|
|
out.append(s.format(f.full_name, count_min, count_max))
|
|
|
|
out.append(' goto exit;\n')
|
|
|
|
out.append("}")
|
|
|
|
|
2023-12-23 13:08:10 -04:00
|
|
|
template_dict['option_group_parsing'] = libclinic.format_escape("".join(out))
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-04 20:07:57 -03:00
|
|
|
def render_function(
|
|
|
|
self,
|
2024-02-15 09:21:31 -04:00
|
|
|
clinic: Clinic,
|
2023-07-04 20:07:57 -03:00
|
|
|
f: Function | None
|
|
|
|
) -> str:
|
|
|
|
if f is None or clinic is None:
|
2013-10-19 04:09:25 -03:00
|
|
|
return ""
|
|
|
|
|
|
|
|
data = CRenderData()
|
|
|
|
|
2014-02-01 02:03:12 -04:00
|
|
|
assert f.parameters, "We should always have a 'self' at this point!"
|
|
|
|
parameters = f.render_parameters
|
2013-10-19 04:09:25 -03:00
|
|
|
converters = [p.converter for p in parameters]
|
|
|
|
|
2023-07-29 15:47:42 -03:00
|
|
|
templates = self.output_templates(f, clinic)
|
2014-01-24 10:17:25 -04:00
|
|
|
|
|
|
|
f_self = parameters[0]
|
|
|
|
selfless = parameters[1:]
|
|
|
|
assert isinstance(f_self.converter, self_converter), "No self parameter in " + repr(f.full_name) + "!"
|
|
|
|
|
2023-11-14 06:47:46 -04:00
|
|
|
if f.critical_section:
|
2023-11-18 19:05:49 -04:00
|
|
|
match len(f.target_critical_section):
|
|
|
|
case 0:
|
|
|
|
lock = 'Py_BEGIN_CRITICAL_SECTION({self_name});'
|
|
|
|
unlock = 'Py_END_CRITICAL_SECTION();'
|
|
|
|
case 1:
|
|
|
|
lock = 'Py_BEGIN_CRITICAL_SECTION({target_critical_section});'
|
|
|
|
unlock = 'Py_END_CRITICAL_SECTION();'
|
|
|
|
case _:
|
|
|
|
lock = 'Py_BEGIN_CRITICAL_SECTION2({target_critical_section});'
|
|
|
|
unlock = 'Py_END_CRITICAL_SECTION2();'
|
|
|
|
data.lock.append(lock)
|
|
|
|
data.unlock.append(unlock)
|
2023-11-14 06:47:46 -04:00
|
|
|
|
2014-01-24 10:17:25 -04:00
|
|
|
last_group = 0
|
|
|
|
first_optional = len(selfless)
|
2016-06-09 10:30:29 -03:00
|
|
|
positional = selfless and selfless[-1].is_positional_only()
|
2014-01-24 10:17:25 -04:00
|
|
|
has_option_groups = False
|
|
|
|
|
|
|
|
# offset i by -1 because first_optional needs to ignore self
|
|
|
|
for i, p in enumerate(parameters, -1):
|
|
|
|
c = p.converter
|
|
|
|
|
|
|
|
if (i != -1) and (p.default is not unspecified):
|
|
|
|
first_optional = min(first_optional, i)
|
|
|
|
|
2021-07-16 12:43:02 -03:00
|
|
|
if p.is_vararg():
|
2023-05-20 17:16:49 -03:00
|
|
|
data.cleanup.append(f"Py_XDECREF({c.parser_name});")
|
2021-07-16 12:43:02 -03:00
|
|
|
|
2014-01-24 10:17:25 -04:00
|
|
|
# insert group variable
|
|
|
|
group = p.group
|
|
|
|
if last_group != group:
|
|
|
|
last_group = group
|
|
|
|
if group:
|
|
|
|
group_name = self.group_to_variable_name(group)
|
|
|
|
data.impl_arguments.append(group_name)
|
|
|
|
data.declarations.append("int " + group_name + " = 0;")
|
|
|
|
data.impl_parameters.append("int " + group_name)
|
|
|
|
has_option_groups = True
|
|
|
|
|
|
|
|
c.render(p, data)
|
|
|
|
|
|
|
|
if has_option_groups and (not positional):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("You cannot use optional groups ('[' and ']') "
|
|
|
|
"unless all parameters are positional-only ('/').")
|
2014-01-24 10:17:25 -04:00
|
|
|
|
|
|
|
# HACK
|
|
|
|
# when we're METH_O, but have a custom return converter,
|
|
|
|
# we use "impl_parameters" for the parsing function
|
|
|
|
# because that works better. but that means we must
|
2014-10-19 12:04:38 -03:00
|
|
|
# suppress actually declaring the impl's parameters
|
2014-01-24 10:17:25 -04:00
|
|
|
# as variables in the parsing function. but since it's
|
|
|
|
# METH_O, we have exactly one anyway, so we know exactly
|
|
|
|
# where it is.
|
|
|
|
if ("METH_O" in templates['methoddef_define'] and
|
2015-04-03 18:12:11 -03:00
|
|
|
'{impl_parameters}' in templates['parser_prototype']):
|
2014-01-24 10:17:25 -04:00
|
|
|
data.declarations.pop(0)
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
full_name = f.full_name
|
2023-07-26 07:54:03 -03:00
|
|
|
template_dict = {'full_name': full_name}
|
2023-08-09 10:28:18 -03:00
|
|
|
template_dict['name'] = f.displayname
|
2023-12-13 10:00:34 -04:00
|
|
|
if f.kind in {GETTER, SETTER}:
|
|
|
|
template_dict['getset_name'] = f.c_basename.upper()
|
|
|
|
template_dict['getset_basename'] = f.c_basename
|
|
|
|
if f.kind is GETTER:
|
|
|
|
template_dict['c_basename'] = f.c_basename + "_get"
|
|
|
|
elif f.kind is SETTER:
|
|
|
|
template_dict['c_basename'] = f.c_basename + "_set"
|
|
|
|
# Implicitly add the setter value parameter.
|
|
|
|
data.impl_parameters.append("PyObject *value")
|
|
|
|
data.impl_arguments.append("value")
|
2023-11-30 06:40:53 -04:00
|
|
|
else:
|
|
|
|
template_dict['methoddef_name'] = f.c_basename.upper() + "_METHODDEF"
|
|
|
|
template_dict['c_basename'] = f.c_basename
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
template_dict['docstring'] = libclinic.docstring_for_c_string(f.docstring)
|
2014-01-26 00:43:29 -04:00
|
|
|
template_dict['self_name'] = template_dict['self_type'] = template_dict['self_type_check'] = ''
|
2023-11-18 19:05:49 -04:00
|
|
|
template_dict['target_critical_section'] = ', '.join(f.target_critical_section)
|
2020-05-13 19:31:31 -03:00
|
|
|
for converter in converters:
|
|
|
|
converter.set_template_dict(template_dict)
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2024-03-04 08:51:28 -04:00
|
|
|
if f.kind not in {SETTER, METHOD_INIT}:
|
|
|
|
f.return_converter.render(f, data)
|
|
|
|
template_dict['impl_return_type'] = f.return_converter.type
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-23 13:08:10 -04:00
|
|
|
template_dict['declarations'] = libclinic.format_escape("\n".join(data.declarations))
|
2013-10-19 04:09:25 -03:00
|
|
|
template_dict['initializers'] = "\n\n".join(data.initializers)
|
2014-01-26 00:43:29 -04:00
|
|
|
template_dict['modifications'] = '\n\n'.join(data.modifications)
|
2022-08-11 18:25:49 -03:00
|
|
|
template_dict['keywords_c'] = ' '.join('"' + k + '",'
|
|
|
|
for k in data.keywords)
|
|
|
|
keywords = [k for k in data.keywords if k]
|
|
|
|
template_dict['keywords_py'] = ' '.join('&_Py_ID(' + k + '),'
|
|
|
|
for k in keywords)
|
2013-10-19 04:09:25 -03:00
|
|
|
template_dict['format_units'] = ''.join(data.format_units)
|
|
|
|
template_dict['parse_arguments'] = ', '.join(data.parse_arguments)
|
2020-05-07 10:39:59 -03:00
|
|
|
if data.parse_arguments:
|
|
|
|
template_dict['parse_arguments_comma'] = ',';
|
|
|
|
else:
|
|
|
|
template_dict['parse_arguments_comma'] = '';
|
2013-10-19 04:09:25 -03:00
|
|
|
template_dict['impl_parameters'] = ", ".join(data.impl_parameters)
|
|
|
|
template_dict['impl_arguments'] = ", ".join(data.impl_arguments)
|
2023-12-23 13:08:10 -04:00
|
|
|
|
|
|
|
template_dict['return_conversion'] = libclinic.format_escape("".join(data.return_conversion).rstrip())
|
|
|
|
template_dict['post_parsing'] = libclinic.format_escape("".join(data.post_parsing).rstrip())
|
|
|
|
template_dict['cleanup'] = libclinic.format_escape("".join(data.cleanup))
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
template_dict['return_value'] = data.return_value
|
2023-11-14 06:47:46 -04:00
|
|
|
template_dict['lock'] = "\n".join(data.lock)
|
|
|
|
template_dict['unlock'] = "\n".join(data.unlock)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-24 10:17:25 -04:00
|
|
|
# used by unpack tuple code generator
|
|
|
|
unpack_min = first_optional
|
|
|
|
unpack_max = len(selfless)
|
|
|
|
template_dict['unpack_min'] = str(unpack_min)
|
|
|
|
template_dict['unpack_max'] = str(unpack_max)
|
2014-01-19 03:50:21 -04:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
if has_option_groups:
|
2023-08-29 08:33:28 -03:00
|
|
|
self.render_option_group_parsing(f, template_dict,
|
|
|
|
limited_capi=clinic.limited_capi)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
# buffers, not destination
|
|
|
|
for name, destination in clinic.destination_buffers.items():
|
2014-01-17 21:47:17 -04:00
|
|
|
template = templates[name]
|
|
|
|
if has_option_groups:
|
2024-02-15 18:52:20 -04:00
|
|
|
template = libclinic.linear_format(template,
|
2014-01-17 21:47:17 -04:00
|
|
|
option_group_parsing=template_dict['option_group_parsing'])
|
2024-02-15 18:52:20 -04:00
|
|
|
template = libclinic.linear_format(template,
|
2014-01-17 21:47:17 -04:00
|
|
|
declarations=template_dict['declarations'],
|
|
|
|
return_conversion=template_dict['return_conversion'],
|
|
|
|
initializers=template_dict['initializers'],
|
2014-01-26 00:43:29 -04:00
|
|
|
modifications=template_dict['modifications'],
|
2022-11-24 10:01:26 -04:00
|
|
|
post_parsing=template_dict['post_parsing'],
|
2014-01-17 21:47:17 -04:00
|
|
|
cleanup=template_dict['cleanup'],
|
2023-11-14 06:47:46 -04:00
|
|
|
lock=template_dict['lock'],
|
|
|
|
unlock=template_dict['unlock'],
|
2014-01-17 21:47:17 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
# Only generate the "exit:" label
|
|
|
|
# if we have any gotos
|
2024-02-15 18:52:20 -04:00
|
|
|
label = "exit:" if "goto exit;" in template else ""
|
|
|
|
template = libclinic.linear_format(template, exit_label=label)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
s = template.format_map(template_dict)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2015-04-14 19:07:59 -03:00
|
|
|
# mild hack:
|
|
|
|
# reflow long impl declarations
|
|
|
|
if name in {"impl_prototype", "impl_definition"}:
|
2023-12-23 13:08:10 -04:00
|
|
|
s = libclinic.wrap_declarations(s)
|
2015-04-14 19:07:59 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
if clinic.line_prefix:
|
2023-12-22 20:37:39 -04:00
|
|
|
s = libclinic.indent_all_lines(s, clinic.line_prefix)
|
2014-01-17 21:47:17 -04:00
|
|
|
if clinic.line_suffix:
|
2023-12-22 20:37:39 -04:00
|
|
|
s = libclinic.suffix_all_lines(s, clinic.line_suffix)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
destination.append(s)
|
|
|
|
|
|
|
|
return clinic.get_destination('block').dump()
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-07-06 18:17:12 -03:00
|
|
|
@dc.dataclass(slots=True)
|
2013-10-19 04:09:25 -03:00
|
|
|
class BlockPrinter:
|
2023-07-06 18:17:12 -03:00
|
|
|
language: Language
|
|
|
|
f: io.StringIO = dc.field(default_factory=io.StringIO)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-22 20:37:39 -04:00
|
|
|
# '#include "header.h" // reason': column of '//' comment
|
|
|
|
INCLUDE_COMMENT_COLUMN: Final[int] = 35
|
|
|
|
|
2023-07-17 08:47:08 -03:00
|
|
|
def print_block(
|
|
|
|
self,
|
|
|
|
block: Block,
|
|
|
|
*,
|
2023-08-25 18:22:08 -03:00
|
|
|
core_includes: bool = False,
|
2023-08-28 18:31:45 -03:00
|
|
|
limited_capi: bool,
|
2023-08-31 18:42:34 -03:00
|
|
|
header_includes: dict[str, Include],
|
2023-07-17 08:47:08 -03:00
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
input = block.input
|
|
|
|
output = block.output
|
|
|
|
dsl_name = block.dsl_name
|
|
|
|
write = self.f.write
|
|
|
|
|
2021-08-31 10:59:52 -03:00
|
|
|
assert not ((dsl_name is None) ^ (output is None)), "you must specify dsl_name and output together, dsl_name " + repr(dsl_name)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
if not dsl_name:
|
|
|
|
write(input)
|
|
|
|
return
|
|
|
|
|
|
|
|
write(self.language.start_line.format(dsl_name=dsl_name))
|
|
|
|
write("\n")
|
|
|
|
|
|
|
|
body_prefix = self.language.body_prefix.format(dsl_name=dsl_name)
|
|
|
|
if not body_prefix:
|
|
|
|
write(input)
|
|
|
|
else:
|
|
|
|
for line in input.split('\n'):
|
|
|
|
write(body_prefix)
|
|
|
|
write(line)
|
|
|
|
write("\n")
|
|
|
|
|
|
|
|
write(self.language.stop_line.format(dsl_name=dsl_name))
|
|
|
|
write("\n")
|
|
|
|
|
2022-08-11 18:25:49 -03:00
|
|
|
output = ''
|
2023-08-31 18:42:34 -03:00
|
|
|
if core_includes and header_includes:
|
2023-08-28 18:31:45 -03:00
|
|
|
# Emit optional "#include" directives for C headers
|
2023-08-31 18:42:34 -03:00
|
|
|
output += '\n'
|
|
|
|
|
|
|
|
current_condition: str | None = None
|
|
|
|
includes = sorted(header_includes.values(), key=Include.sort_key)
|
|
|
|
for include in includes:
|
|
|
|
if include.condition != current_condition:
|
|
|
|
if current_condition:
|
|
|
|
output += '#endif\n'
|
|
|
|
current_condition = include.condition
|
|
|
|
if include.condition:
|
|
|
|
output += f'{include.condition}\n'
|
|
|
|
|
|
|
|
if current_condition:
|
|
|
|
line = f'# include "{include.filename}"'
|
|
|
|
else:
|
|
|
|
line = f'#include "{include.filename}"'
|
|
|
|
if include.reason:
|
|
|
|
comment = f'// {include.reason}\n'
|
2023-12-22 20:37:39 -04:00
|
|
|
line = line.ljust(self.INCLUDE_COMMENT_COLUMN - 1) + comment
|
2023-08-28 18:31:45 -03:00
|
|
|
output += line
|
2022-08-11 18:25:49 -03:00
|
|
|
|
2023-08-31 18:42:34 -03:00
|
|
|
if current_condition:
|
|
|
|
output += '#endif\n'
|
|
|
|
|
2014-01-28 09:00:08 -04:00
|
|
|
input = ''.join(block.input)
|
2022-08-11 18:25:49 -03:00
|
|
|
output += ''.join(block.output)
|
2013-10-19 04:09:25 -03:00
|
|
|
if output:
|
|
|
|
if not output.endswith('\n'):
|
2014-01-17 21:47:17 -04:00
|
|
|
output += '\n'
|
|
|
|
write(output)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-20 17:16:49 -03:00
|
|
|
arguments = "output={output} input={input}".format(
|
2024-01-14 14:26:09 -04:00
|
|
|
output=libclinic.compute_checksum(output, 16),
|
|
|
|
input=libclinic.compute_checksum(input, 16)
|
2023-05-20 17:16:49 -03:00
|
|
|
)
|
2014-01-28 09:00:08 -04:00
|
|
|
write(self.language.checksum_line.format(dsl_name=dsl_name, arguments=arguments))
|
2013-10-19 04:09:25 -03:00
|
|
|
write("\n")
|
|
|
|
|
2023-07-17 08:47:08 -03:00
|
|
|
def write(self, text: str) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
self.f.write(text)
|
|
|
|
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
class BufferSeries:
|
|
|
|
"""
|
|
|
|
Behaves like a "defaultlist".
|
|
|
|
When you ask for an index that doesn't exist yet,
|
|
|
|
the object grows the list until that item exists.
|
|
|
|
So o[n] will always work.
|
|
|
|
|
|
|
|
Supports negative indices for actual items.
|
|
|
|
e.g. o[-1] is an element immediately preceding o[0].
|
|
|
|
"""
|
|
|
|
|
2023-07-22 07:46:42 -03:00
|
|
|
def __init__(self) -> None:
|
2015-04-03 17:09:02 -03:00
|
|
|
self._start = 0
|
2023-12-22 18:35:16 -04:00
|
|
|
self._array: list[list[str]] = []
|
2015-04-03 17:09:02 -03:00
|
|
|
|
2023-12-22 18:35:16 -04:00
|
|
|
def __getitem__(self, i: int) -> list[str]:
|
2015-04-03 17:09:02 -03:00
|
|
|
i -= self._start
|
|
|
|
if i < 0:
|
|
|
|
self._start += i
|
2023-12-22 18:35:16 -04:00
|
|
|
prefix: list[list[str]] = [[] for x in range(-i)]
|
2015-04-03 17:09:02 -03:00
|
|
|
self._array = prefix + self._array
|
|
|
|
i = 0
|
|
|
|
while i >= len(self._array):
|
2023-12-22 16:28:15 -04:00
|
|
|
self._array.append([])
|
2015-04-03 17:09:02 -03:00
|
|
|
return self._array[i]
|
|
|
|
|
2023-07-22 07:46:42 -03:00
|
|
|
def clear(self) -> None:
|
2015-04-03 17:09:02 -03:00
|
|
|
for ta in self._array:
|
2023-12-22 16:28:15 -04:00
|
|
|
ta.clear()
|
2015-04-03 17:09:02 -03:00
|
|
|
|
2023-07-22 07:46:42 -03:00
|
|
|
def dump(self) -> str:
|
2023-12-22 16:28:15 -04:00
|
|
|
texts = ["".join(ta) for ta in self._array]
|
|
|
|
self.clear()
|
2015-04-03 17:09:02 -03:00
|
|
|
return "".join(texts)
|
|
|
|
|
|
|
|
|
2023-07-12 18:33:47 -03:00
|
|
|
@dc.dataclass(slots=True, repr=False)
|
2014-01-17 21:47:17 -04:00
|
|
|
class Destination:
|
2023-07-12 18:33:47 -03:00
|
|
|
name: str
|
|
|
|
type: str
|
|
|
|
clinic: Clinic
|
|
|
|
buffers: BufferSeries = dc.field(init=False, default_factory=BufferSeries)
|
|
|
|
filename: str = dc.field(init=False) # set in __post_init__
|
|
|
|
|
|
|
|
args: dc.InitVar[tuple[str, ...]] = ()
|
2023-07-11 20:08:28 -03:00
|
|
|
|
2023-07-12 18:33:47 -03:00
|
|
|
def __post_init__(self, args: tuple[str, ...]) -> None:
|
2015-04-03 17:09:02 -03:00
|
|
|
valid_types = ('buffer', 'file', 'suppress')
|
2023-07-12 18:33:47 -03:00
|
|
|
if self.type not in valid_types:
|
2023-07-11 20:08:28 -03:00
|
|
|
fail(
|
2023-07-12 18:33:47 -03:00
|
|
|
f"Invalid destination type {self.type!r} for {self.name}, "
|
2023-07-11 20:08:28 -03:00
|
|
|
f"must be {', '.join(valid_types)}"
|
|
|
|
)
|
2023-07-12 18:33:47 -03:00
|
|
|
extra_arguments = 1 if self.type == "file" else 0
|
2014-01-17 21:47:17 -04:00
|
|
|
if len(args) < extra_arguments:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Not enough arguments for destination "
|
|
|
|
f"{self.name!r} new {self.type!r}")
|
2014-01-17 21:47:17 -04:00
|
|
|
if len(args) > extra_arguments:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Too many arguments for destination {self.name!r} new {self.type!r}")
|
2023-07-12 18:33:47 -03:00
|
|
|
if self.type =='file':
|
2014-01-17 21:47:17 -04:00
|
|
|
d = {}
|
2023-07-12 18:33:47 -03:00
|
|
|
filename = self.clinic.filename
|
2014-01-26 00:43:29 -04:00
|
|
|
d['path'] = filename
|
|
|
|
dirname, basename = os.path.split(filename)
|
|
|
|
if not dirname:
|
|
|
|
dirname = '.'
|
|
|
|
d['dirname'] = dirname
|
|
|
|
d['basename'] = basename
|
|
|
|
d['basename_root'], d['basename_extension'] = os.path.splitext(filename)
|
2014-01-17 21:47:17 -04:00
|
|
|
self.filename = args[0].format_map(d)
|
|
|
|
|
2023-07-12 18:33:47 -03:00
|
|
|
def __repr__(self) -> str:
|
2014-01-17 21:47:17 -04:00
|
|
|
if self.type == 'file':
|
2023-08-05 17:58:38 -03:00
|
|
|
type_repr = f"type='file' file={self.filename!r}"
|
2014-01-17 21:47:17 -04:00
|
|
|
else:
|
2023-08-05 17:58:38 -03:00
|
|
|
type_repr = f"type={self.type!r}"
|
|
|
|
return f"<clinic.Destination {self.name!r} {type_repr}>"
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-07-12 18:33:47 -03:00
|
|
|
def clear(self) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
if self.type != 'buffer':
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Can't clear destination {self.name!r}: it's not of type 'buffer'")
|
2015-04-03 17:09:02 -03:00
|
|
|
self.buffers.clear()
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-07-12 18:33:47 -03:00
|
|
|
def dump(self) -> str:
|
2015-04-03 17:09:02 -03:00
|
|
|
return self.buffers.dump()
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-04 11:56:50 -03:00
|
|
|
# "extensions" maps the file extension ("c", "py") to Language classes.
|
2023-05-15 05:49:28 -03:00
|
|
|
LangDict = dict[str, Callable[[str], Language]]
|
|
|
|
extensions: LangDict = { name: CLanguage for name in "c cc cpp cxx h hh hpp hxx".split() }
|
2014-01-05 06:50:45 -04:00
|
|
|
extensions['py'] = PythonLanguage
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
DestinationDict = dict[str, Destination]
|
2023-07-16 21:04:10 -03:00
|
|
|
|
|
|
|
|
|
|
|
class Parser(Protocol):
|
|
|
|
def __init__(self, clinic: Clinic) -> None: ...
|
|
|
|
def parse(self, block: Block) -> None: ...
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class Clinic:
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
presets_text = """
|
2014-02-01 02:03:12 -04:00
|
|
|
preset block
|
|
|
|
everything block
|
2015-04-03 17:09:02 -03:00
|
|
|
methoddef_ifndef buffer 1
|
2014-02-01 02:03:12 -04:00
|
|
|
docstring_prototype suppress
|
|
|
|
parser_prototype suppress
|
|
|
|
cpp_if suppress
|
|
|
|
cpp_endif suppress
|
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
preset original
|
|
|
|
everything block
|
2015-04-03 17:09:02 -03:00
|
|
|
methoddef_ifndef buffer 1
|
2014-01-17 21:47:17 -04:00
|
|
|
docstring_prototype suppress
|
|
|
|
parser_prototype suppress
|
2014-02-01 02:03:12 -04:00
|
|
|
cpp_if suppress
|
|
|
|
cpp_endif suppress
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
preset file
|
|
|
|
everything file
|
2015-04-03 17:09:02 -03:00
|
|
|
methoddef_ifndef file 1
|
2014-01-17 21:47:17 -04:00
|
|
|
docstring_prototype suppress
|
|
|
|
parser_prototype suppress
|
|
|
|
impl_definition block
|
|
|
|
|
|
|
|
preset buffer
|
|
|
|
everything buffer
|
2015-04-03 17:09:02 -03:00
|
|
|
methoddef_ifndef buffer 1
|
|
|
|
impl_definition block
|
2014-01-17 21:47:17 -04:00
|
|
|
docstring_prototype suppress
|
|
|
|
impl_prototype suppress
|
|
|
|
parser_prototype suppress
|
|
|
|
|
|
|
|
preset partial-buffer
|
|
|
|
everything buffer
|
2015-04-03 17:09:02 -03:00
|
|
|
methoddef_ifndef buffer 1
|
2014-01-17 21:47:17 -04:00
|
|
|
docstring_prototype block
|
|
|
|
impl_prototype suppress
|
|
|
|
methoddef_define block
|
|
|
|
parser_prototype block
|
|
|
|
impl_definition block
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
language: CLanguage,
|
|
|
|
printer: BlockPrinter | None = None,
|
|
|
|
*,
|
2023-07-29 15:46:52 -03:00
|
|
|
filename: str,
|
2023-08-28 15:25:16 -03:00
|
|
|
limited_capi: bool,
|
2023-05-21 17:49:34 -03:00
|
|
|
verify: bool = True,
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
# maps strings to Parser objects.
|
|
|
|
# (instantiated from the "parsers" global.)
|
2023-07-16 21:04:10 -03:00
|
|
|
self.parsers: dict[str, Parser] = {}
|
2023-05-21 17:49:34 -03:00
|
|
|
self.language: CLanguage = language
|
2014-01-17 21:47:17 -04:00
|
|
|
if printer:
|
|
|
|
fail("Custom printers are broken right now")
|
2013-10-19 04:09:25 -03:00
|
|
|
self.printer = printer or BlockPrinter(language)
|
|
|
|
self.verify = verify
|
2023-08-25 18:22:08 -03:00
|
|
|
self.limited_capi = limited_capi
|
2013-10-19 04:09:25 -03:00
|
|
|
self.filename = filename
|
2023-05-21 17:49:34 -03:00
|
|
|
self.modules: ModuleDict = {}
|
|
|
|
self.classes: ClassDict = {}
|
|
|
|
self.functions: list[Function] = []
|
2023-08-31 18:42:34 -03:00
|
|
|
# dict: include name => Include instance
|
|
|
|
self.includes: dict[str, Include] = {}
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-17 21:47:17 -04:00
|
|
|
self.line_prefix = self.line_suffix = ''
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
self.destinations: DestinationDict = {}
|
2014-01-17 21:47:17 -04:00
|
|
|
self.add_destination("block", "buffer")
|
|
|
|
self.add_destination("suppress", "suppress")
|
|
|
|
self.add_destination("buffer", "buffer")
|
|
|
|
if filename:
|
2014-01-26 00:43:29 -04:00
|
|
|
self.add_destination("file", "file", "{dirname}/clinic/{basename}.h")
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
d = self.get_destination_buffer
|
2023-05-20 07:24:00 -03:00
|
|
|
self.destination_buffers = {
|
|
|
|
'cpp_if': d('file'),
|
|
|
|
'docstring_prototype': d('suppress'),
|
|
|
|
'docstring_definition': d('file'),
|
|
|
|
'methoddef_define': d('file'),
|
|
|
|
'impl_prototype': d('file'),
|
|
|
|
'parser_prototype': d('suppress'),
|
|
|
|
'parser_definition': d('file'),
|
|
|
|
'cpp_endif': d('file'),
|
|
|
|
'methoddef_ifndef': d('file', 1),
|
|
|
|
'impl_definition': d('block'),
|
|
|
|
}
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-12-22 18:35:16 -04:00
|
|
|
DestBufferType = dict[str, list[str]]
|
2023-05-21 17:49:34 -03:00
|
|
|
DestBufferList = list[DestBufferType]
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
self.destination_buffers_stack: DestBufferList = []
|
|
|
|
self.ifndef_symbols: set[str] = set()
|
|
|
|
|
|
|
|
self.presets: dict[str, dict[Any, Any]] = {}
|
2014-01-17 21:47:17 -04:00
|
|
|
preset = None
|
|
|
|
for line in self.presets_text.strip().split('\n'):
|
|
|
|
line = line.strip()
|
|
|
|
if not line:
|
|
|
|
continue
|
2015-04-03 17:09:02 -03:00
|
|
|
name, value, *options = line.split()
|
2014-01-17 21:47:17 -04:00
|
|
|
if name == 'preset':
|
2023-05-20 07:24:00 -03:00
|
|
|
self.presets[value] = preset = {}
|
2014-01-17 21:47:17 -04:00
|
|
|
continue
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if len(options):
|
|
|
|
index = int(options[0])
|
|
|
|
else:
|
|
|
|
index = 0
|
|
|
|
buffer = self.get_destination_buffer(value, index)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
if name == 'everything':
|
2015-04-03 17:09:02 -03:00
|
|
|
for name in self.destination_buffers:
|
|
|
|
preset[name] = buffer
|
2014-01-17 21:47:17 -04:00
|
|
|
continue
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
assert name in self.destination_buffers
|
|
|
|
preset[name] = buffer
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-08-31 18:42:34 -03:00
|
|
|
def add_include(self, name: str, reason: str,
|
|
|
|
*, condition: str | None = None) -> None:
|
|
|
|
try:
|
|
|
|
existing = self.includes[name]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if existing.condition and not condition:
|
|
|
|
# If the previous include has a condition and the new one is
|
|
|
|
# unconditional, override the include.
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# Already included, do nothing. Only mention a single reason,
|
|
|
|
# no need to list all of them.
|
|
|
|
return
|
|
|
|
|
|
|
|
self.includes[name] = Include(name, reason, condition)
|
2023-08-25 19:01:10 -03:00
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
def add_destination(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
type: str,
|
2023-07-12 18:33:47 -03:00
|
|
|
*args: str
|
2023-05-21 17:49:34 -03:00
|
|
|
) -> None:
|
2015-04-03 17:09:02 -03:00
|
|
|
if name in self.destinations:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Destination already exists: {name!r}")
|
2023-07-12 18:33:47 -03:00
|
|
|
self.destinations[name] = Destination(name, type, self, args)
|
2015-04-03 17:09:02 -03:00
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
def get_destination(self, name: str) -> Destination:
|
2014-01-17 21:47:17 -04:00
|
|
|
d = self.destinations.get(name)
|
|
|
|
if not d:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Destination does not exist: {name!r}")
|
2014-01-17 21:47:17 -04:00
|
|
|
return d
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
def get_destination_buffer(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
item: int = 0
|
2023-12-22 18:35:16 -04:00
|
|
|
) -> list[str]:
|
2015-04-03 17:09:02 -03:00
|
|
|
d = self.get_destination(name)
|
|
|
|
return d.buffers[item]
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-07-16 21:04:10 -03:00
|
|
|
def parse(self, input: str) -> str:
|
2013-10-19 04:09:25 -03:00
|
|
|
printer = self.printer
|
|
|
|
self.block_parser = BlockParser(input, self.language, verify=self.verify)
|
|
|
|
for block in self.block_parser:
|
|
|
|
dsl_name = block.dsl_name
|
|
|
|
if dsl_name:
|
|
|
|
if dsl_name not in self.parsers:
|
2023-05-20 17:16:49 -03:00
|
|
|
assert dsl_name in parsers, f"No parser to handle {dsl_name!r} block."
|
2013-10-19 04:09:25 -03:00
|
|
|
self.parsers[dsl_name] = parsers[dsl_name](self)
|
|
|
|
parser = self.parsers[dsl_name]
|
2023-08-02 21:00:06 -03:00
|
|
|
parser.parse(block)
|
2023-08-28 18:31:45 -03:00
|
|
|
printer.print_block(block,
|
|
|
|
limited_capi=self.limited_capi,
|
|
|
|
header_includes=self.includes)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
# these are destinations not buffers
|
2014-01-17 21:47:17 -04:00
|
|
|
for name, destination in self.destinations.items():
|
|
|
|
if destination.type == 'suppress':
|
|
|
|
continue
|
2015-04-03 17:09:02 -03:00
|
|
|
output = destination.dump()
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
if output:
|
|
|
|
block = Block("", dsl_name="clinic", output=output)
|
|
|
|
|
|
|
|
if destination.type == 'buffer':
|
|
|
|
block.input = "dump " + name + "\n"
|
|
|
|
warn("Destination buffer " + repr(name) + " not empty at end of file, emptying.")
|
|
|
|
printer.write("\n")
|
2023-08-28 18:31:45 -03:00
|
|
|
printer.print_block(block,
|
|
|
|
limited_capi=self.limited_capi,
|
|
|
|
header_includes=self.includes)
|
2014-01-17 21:47:17 -04:00
|
|
|
continue
|
|
|
|
|
|
|
|
if destination.type == 'file':
|
|
|
|
try:
|
2014-01-26 00:43:29 -04:00
|
|
|
dirname = os.path.dirname(destination.filename)
|
|
|
|
try:
|
|
|
|
os.makedirs(dirname)
|
|
|
|
except FileExistsError:
|
|
|
|
if not os.path.isdir(dirname):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Can't write to destination "
|
|
|
|
f"{destination.filename!r}; "
|
|
|
|
f"can't make directory {dirname!r}!")
|
2014-01-28 09:00:08 -04:00
|
|
|
if self.verify:
|
2023-05-20 17:16:49 -03:00
|
|
|
with open(destination.filename) as f:
|
2014-01-28 09:00:08 -04:00
|
|
|
parser_2 = BlockParser(f.read(), language=self.language)
|
|
|
|
blocks = list(parser_2)
|
|
|
|
if (len(blocks) != 1) or (blocks[0].input != 'preserve\n'):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Modified destination file "
|
|
|
|
f"{destination.filename!r}; not overwriting!")
|
2014-01-17 21:47:17 -04:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
block.input = 'preserve\n'
|
|
|
|
printer_2 = BlockPrinter(self.language)
|
2023-08-28 18:31:45 -03:00
|
|
|
printer_2.print_block(block,
|
|
|
|
core_includes=True,
|
|
|
|
limited_capi=self.limited_capi,
|
|
|
|
header_includes=self.includes)
|
2024-01-14 14:26:09 -04:00
|
|
|
libclinic.write_file(destination.filename,
|
|
|
|
printer_2.f.getvalue())
|
2014-01-17 21:47:17 -04:00
|
|
|
continue
|
2023-05-03 21:11:29 -03:00
|
|
|
|
2023-07-05 08:23:22 -03:00
|
|
|
return printer.f.getvalue()
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-07-28 17:27:21 -03:00
|
|
|
def _module_and_class(
|
2023-08-28 09:41:05 -03:00
|
|
|
self, fields: Sequence[str]
|
2023-07-28 17:27:21 -03:00
|
|
|
) -> tuple[Module | Clinic, Class | None]:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
fields should be an iterable of field names.
|
|
|
|
returns a tuple of (module, class).
|
|
|
|
the module object could actually be self (a clinic object).
|
|
|
|
this function is only ever used to find the parent of where
|
|
|
|
a new class/module should go.
|
|
|
|
"""
|
2023-08-28 09:41:05 -03:00
|
|
|
parent: Clinic | Module | Class = self
|
|
|
|
module: Clinic | Module = self
|
2023-07-28 17:27:21 -03:00
|
|
|
cls: Class | None = None
|
|
|
|
|
2023-08-28 09:41:05 -03:00
|
|
|
for idx, field in enumerate(fields):
|
2023-07-28 17:27:21 -03:00
|
|
|
if not isinstance(parent, Class):
|
2023-08-28 09:41:05 -03:00
|
|
|
if field in parent.modules:
|
|
|
|
parent = module = parent.modules[field]
|
2013-10-19 04:09:25 -03:00
|
|
|
continue
|
2023-08-28 09:41:05 -03:00
|
|
|
if field in parent.classes:
|
|
|
|
parent = cls = parent.classes[field]
|
|
|
|
else:
|
|
|
|
fullname = ".".join(fields[idx:])
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Parent class or module {fullname!r} does not exist.")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
return module, cls
|
|
|
|
|
2023-08-07 10:26:49 -03:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
return "<clinic.Clinic object>"
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-18 19:57:26 -03:00
|
|
|
def parse_file(
|
|
|
|
filename: str,
|
|
|
|
*,
|
2023-08-28 15:25:16 -03:00
|
|
|
limited_capi: bool,
|
2023-08-25 18:22:08 -03:00
|
|
|
output: str | None = None,
|
2023-08-28 15:25:16 -03:00
|
|
|
verify: bool = True,
|
2023-05-18 19:57:26 -03:00
|
|
|
) -> None:
|
2020-11-18 10:36:27 -04:00
|
|
|
if not output:
|
|
|
|
output = filename
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
extension = os.path.splitext(filename)[1][1:]
|
|
|
|
if not extension:
|
2024-02-15 08:10:32 -04:00
|
|
|
raise ClinicError(f"Can't extract file type for file {filename!r}")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
try:
|
2014-02-01 02:03:12 -04:00
|
|
|
language = extensions[extension](filename)
|
2013-10-19 04:09:25 -03:00
|
|
|
except KeyError:
|
2024-02-15 08:10:32 -04:00
|
|
|
raise ClinicError(f"Can't identify file type for file {filename!r}")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-20 17:16:49 -03:00
|
|
|
with open(filename, encoding="utf-8") as f:
|
2013-11-23 18:58:45 -04:00
|
|
|
raw = f.read()
|
|
|
|
|
2014-02-09 02:15:29 -04:00
|
|
|
# exit quickly if there are no clinic markers in the file
|
|
|
|
find_start_re = BlockParser("", language).find_start_re
|
|
|
|
if not find_start_re.search(raw):
|
|
|
|
return
|
|
|
|
|
2023-08-25 19:39:24 -03:00
|
|
|
if LIMITED_CAPI_REGEX.search(raw):
|
|
|
|
limited_capi = True
|
|
|
|
|
2023-05-21 17:49:34 -03:00
|
|
|
assert isinstance(language, CLanguage)
|
2023-08-25 18:22:08 -03:00
|
|
|
clinic = Clinic(language,
|
|
|
|
verify=verify,
|
|
|
|
filename=filename,
|
|
|
|
limited_capi=limited_capi)
|
2023-07-05 08:23:22 -03:00
|
|
|
cooked = clinic.parse(raw)
|
|
|
|
|
2024-01-14 14:26:09 -04:00
|
|
|
libclinic.write_file(output, cooked)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
|
|
|
class PythonParser:
|
2023-05-18 19:57:26 -03:00
|
|
|
def __init__(self, clinic: Clinic) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
pass
|
|
|
|
|
2023-05-18 19:57:26 -03:00
|
|
|
def parse(self, block: Block) -> None:
|
2023-07-06 10:23:02 -03:00
|
|
|
with contextlib.redirect_stdout(io.StringIO()) as s:
|
2013-10-19 04:09:25 -03:00
|
|
|
exec(block.input)
|
2023-07-06 10:23:02 -03:00
|
|
|
block.output = s.getvalue()
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-05-18 19:57:26 -03:00
|
|
|
unsupported_special_methods: set[str] = set("""
|
2014-01-12 18:12:59 -04:00
|
|
|
|
|
|
|
__abs__
|
|
|
|
__add__
|
|
|
|
__and__
|
|
|
|
__call__
|
|
|
|
__delitem__
|
|
|
|
__divmod__
|
|
|
|
__eq__
|
|
|
|
__float__
|
|
|
|
__floordiv__
|
|
|
|
__ge__
|
|
|
|
__getattr__
|
|
|
|
__getattribute__
|
|
|
|
__getitem__
|
|
|
|
__gt__
|
|
|
|
__hash__
|
|
|
|
__iadd__
|
|
|
|
__iand__
|
|
|
|
__ifloordiv__
|
|
|
|
__ilshift__
|
2015-03-12 17:01:30 -03:00
|
|
|
__imatmul__
|
2014-01-12 18:12:59 -04:00
|
|
|
__imod__
|
|
|
|
__imul__
|
|
|
|
__index__
|
|
|
|
__int__
|
|
|
|
__invert__
|
|
|
|
__ior__
|
|
|
|
__ipow__
|
|
|
|
__irshift__
|
|
|
|
__isub__
|
|
|
|
__iter__
|
|
|
|
__itruediv__
|
|
|
|
__ixor__
|
|
|
|
__le__
|
|
|
|
__len__
|
|
|
|
__lshift__
|
|
|
|
__lt__
|
2015-03-12 17:01:30 -03:00
|
|
|
__matmul__
|
2014-01-12 18:12:59 -04:00
|
|
|
__mod__
|
|
|
|
__mul__
|
|
|
|
__neg__
|
|
|
|
__next__
|
|
|
|
__or__
|
|
|
|
__pos__
|
|
|
|
__pow__
|
|
|
|
__radd__
|
|
|
|
__rand__
|
|
|
|
__rdivmod__
|
|
|
|
__repr__
|
|
|
|
__rfloordiv__
|
|
|
|
__rlshift__
|
2015-03-12 17:01:30 -03:00
|
|
|
__rmatmul__
|
2014-01-12 18:12:59 -04:00
|
|
|
__rmod__
|
|
|
|
__rmul__
|
|
|
|
__ror__
|
|
|
|
__rpow__
|
|
|
|
__rrshift__
|
|
|
|
__rshift__
|
|
|
|
__rsub__
|
|
|
|
__rtruediv__
|
|
|
|
__rxor__
|
|
|
|
__setattr__
|
|
|
|
__setitem__
|
|
|
|
__str__
|
|
|
|
__sub__
|
|
|
|
__truediv__
|
|
|
|
__xor__
|
2013-11-18 13:32:13 -04:00
|
|
|
|
2014-01-12 18:12:59 -04:00
|
|
|
""".strip().split())
|
|
|
|
|
|
|
|
|
2023-05-21 18:24:26 -03:00
|
|
|
ReturnConverterType = Callable[..., "CReturnConverter"]
|
|
|
|
|
2023-07-07 10:10:07 -03:00
|
|
|
|
2023-07-04 19:13:30 -03:00
|
|
|
def add_legacy_c_converter(
|
|
|
|
format_unit: str,
|
2023-07-25 05:18:19 -03:00
|
|
|
**kwargs: Any
|
|
|
|
) -> Callable[[CConverterClassT], CConverterClassT]:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Adds a legacy converter.
|
|
|
|
"""
|
2023-07-25 05:18:19 -03:00
|
|
|
def closure(f: CConverterClassT) -> CConverterClassT:
|
|
|
|
added_f: Callable[..., CConverter]
|
2013-10-19 04:09:25 -03:00
|
|
|
if not kwargs:
|
|
|
|
added_f = f
|
|
|
|
else:
|
2023-11-10 12:00:50 -04:00
|
|
|
added_f = functools.partial(f, **kwargs)
|
2014-02-01 02:03:12 -04:00
|
|
|
if format_unit:
|
|
|
|
legacy_converters[format_unit] = added_f
|
2013-10-19 04:09:25 -03:00
|
|
|
return f
|
|
|
|
return closure
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
# maps strings to callables.
|
|
|
|
# these callables must be of the form:
|
|
|
|
# def foo(*, ...)
|
|
|
|
# The callable may have any number of keyword-only parameters.
|
|
|
|
# The callable must return a CReturnConverter object.
|
|
|
|
# The callable should not call builtins.print.
|
|
|
|
ReturnConverterDict = dict[str, ReturnConverterType]
|
|
|
|
return_converters: ReturnConverterDict = {}
|
|
|
|
|
2023-12-10 11:30:02 -04:00
|
|
|
TypeSet = set[bltns.type[object]]
|
2023-05-17 18:05:22 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class bool_converter(CConverter):
|
|
|
|
type = 'int'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = bool
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'p'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = '0'
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(self, *, accept: TypeSet = {object}) -> None:
|
2017-03-12 05:10:47 -03:00
|
|
|
if accept == {int}:
|
|
|
|
self.format_unit = 'i'
|
|
|
|
elif accept != {object}:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"bool_converter: illegal 'accept' argument {accept!r}")
|
2023-12-14 07:28:37 -04:00
|
|
|
if self.default is not unspecified and self.default is not unknown:
|
2014-01-16 15:32:01 -04:00
|
|
|
self.default = bool(self.default)
|
|
|
|
self.c_default = str(int(self.default))
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'i':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2023-08-24 19:51:22 -03:00
|
|
|
{paramname} = PyLong_AsInt({argname});
|
2018-12-25 07:23:47 -04:00
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
elif self.format_unit == 'p':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = PyObject_IsTrue({argname});
|
|
|
|
if ({paramname} < 0) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2020-05-07 10:39:59 -03:00
|
|
|
class defining_class_converter(CConverter):
|
|
|
|
"""
|
|
|
|
A special-case converter:
|
|
|
|
this is the default converter used for the defining class.
|
|
|
|
"""
|
|
|
|
type = 'PyTypeObject *'
|
|
|
|
format_unit = ''
|
|
|
|
show_in_signature = False
|
|
|
|
|
2023-07-25 05:49:07 -03:00
|
|
|
def converter_init(self, *, type: str | None = None) -> None:
|
2020-05-07 10:39:59 -03:00
|
|
|
self.specified_type = type
|
|
|
|
|
2023-07-25 18:08:52 -03:00
|
|
|
def render(self, parameter: Parameter, data: CRenderData) -> None:
|
2020-05-07 10:39:59 -03:00
|
|
|
self._render_self(parameter, data)
|
|
|
|
|
2023-07-25 18:08:52 -03:00
|
|
|
def set_template_dict(self, template_dict: TemplateDict) -> None:
|
2020-05-07 10:39:59 -03:00
|
|
|
template_dict['defining_class_name'] = self.name
|
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class char_converter(CConverter):
|
|
|
|
type = 'char'
|
2015-04-16 00:02:12 -03:00
|
|
|
default_type = (bytes, bytearray)
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'c'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "'\0'"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self) -> None:
|
2018-07-06 07:17:38 -03:00
|
|
|
if isinstance(self.default, self.default_type):
|
|
|
|
if len(self.default) != 1:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"char_converter: illegal default value {self.default!r}")
|
2018-07-06 07:17:38 -03:00
|
|
|
|
2018-12-25 05:10:05 -04:00
|
|
|
self.c_default = repr(bytes(self.default))[1:]
|
|
|
|
if self.c_default == '"\'"':
|
|
|
|
self.c_default = r"'\''"
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'c':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (PyBytes_Check({argname}) && PyBytes_GET_SIZE({argname}) == 1) {{{{
|
|
|
|
{paramname} = PyBytes_AS_STRING({argname})[0];
|
|
|
|
}}}}
|
|
|
|
else if (PyByteArray_Check({argname}) && PyByteArray_GET_SIZE({argname}) == 1) {{{{
|
|
|
|
{paramname} = PyByteArray_AS_STRING({argname})[0];
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'a byte string of length 1', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
@add_legacy_c_converter('B', bitwise=True)
|
2014-01-19 03:50:21 -04:00
|
|
|
class unsigned_char_converter(CConverter):
|
2014-01-18 18:38:36 -04:00
|
|
|
type = 'unsigned char'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'b'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "'\0'"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self, *, bitwise: bool = False) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
if bitwise:
|
2013-11-23 18:54:00 -04:00
|
|
|
self.format_unit = 'B'
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'b':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{{{{
|
|
|
|
long ival = PyLong_AsLong({argname});
|
|
|
|
if (ival == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else if (ival < 0) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"unsigned byte integer is less than minimum");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else if (ival > UCHAR_MAX) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"unsigned byte integer is greater than maximum");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
{paramname} = (unsigned char) ival;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
elif self.format_unit == 'B':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{{{{
|
2020-05-26 12:43:38 -03:00
|
|
|
unsigned long ival = PyLong_AsUnsignedLongMask({argname});
|
|
|
|
if (ival == (unsigned long)-1 && PyErr_Occurred()) {{{{
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
{paramname} = (unsigned char) ival;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2014-01-19 03:50:21 -04:00
|
|
|
class byte_converter(unsigned_char_converter): pass
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class short_converter(CConverter):
|
|
|
|
type = 'short'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'h'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'h':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{{{{
|
|
|
|
long ival = PyLong_AsLong({argname});
|
|
|
|
if (ival == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else if (ival < SHRT_MIN) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"signed short integer is less than minimum");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else if (ival > SHRT_MAX) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"signed short integer is greater than maximum");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
{paramname} = (short) ival;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class unsigned_short_converter(CConverter):
|
|
|
|
type = 'unsigned short'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self, *, bitwise: bool = False) -> None:
|
2018-07-26 07:22:16 -03:00
|
|
|
if bitwise:
|
|
|
|
self.format_unit = 'H'
|
|
|
|
else:
|
|
|
|
self.converter = '_PyLong_UnsignedShort_Converter'
|
2024-03-14 09:57:02 -03:00
|
|
|
|
|
|
|
def use_converter(self) -> None:
|
|
|
|
if self.converter == '_PyLong_UnsignedShort_Converter':
|
2023-08-25 21:24:27 -03:00
|
|
|
self.add_include('pycore_long.h',
|
|
|
|
'_PyLong_UnsignedShort_Converter()')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2019-01-11 10:01:14 -04:00
|
|
|
if self.format_unit == 'H':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2019-01-11 10:01:14 -04:00
|
|
|
{paramname} = (unsigned short)PyLong_AsUnsignedLongMask({argname});
|
|
|
|
if ({paramname} == (unsigned short)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
# NOTE: Raises OverflowError for negative integer.
|
|
|
|
return self.format_code("""
|
|
|
|
{{{{
|
|
|
|
unsigned long uval = PyLong_AsUnsignedLong({argname});
|
|
|
|
if (uval == (unsigned long)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
if (uval > USHRT_MAX) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"Python int too large for C unsigned short");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = (unsigned short) uval;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2019-01-11 10:01:14 -04:00
|
|
|
|
2015-05-04 10:59:46 -03:00
|
|
|
@add_legacy_c_converter('C', accept={str})
|
2013-10-19 04:09:25 -03:00
|
|
|
class int_converter(CConverter):
|
|
|
|
type = 'int'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'i'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-25 05:49:07 -03:00
|
|
|
def converter_init(
|
|
|
|
self, *, accept: TypeSet = {int}, type: str | None = None
|
|
|
|
) -> None:
|
2015-05-04 10:59:46 -03:00
|
|
|
if accept == {str}:
|
2013-11-23 18:54:00 -04:00
|
|
|
self.format_unit = 'C'
|
2015-05-04 10:59:46 -03:00
|
|
|
elif accept != {int}:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"int_converter: illegal 'accept' argument {accept!r}")
|
2021-08-31 10:59:52 -03:00
|
|
|
if type is not None:
|
2014-10-13 06:39:41 -03:00
|
|
|
self.type = type
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'i':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2023-08-24 19:51:22 -03:00
|
|
|
{paramname} = PyLong_AsInt({argname});
|
2018-12-25 07:23:47 -04:00
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
elif self.format_unit == 'C':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyUnicode_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
if (PyUnicode_GET_LENGTH({argname}) != 1) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = PyUnicode_READ_CHAR({argname}, 0);
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'a unicode character', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class unsigned_int_converter(CConverter):
|
|
|
|
type = 'unsigned int'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self, *, bitwise: bool = False) -> None:
|
2018-07-26 07:22:16 -03:00
|
|
|
if bitwise:
|
|
|
|
self.format_unit = 'I'
|
|
|
|
else:
|
|
|
|
self.converter = '_PyLong_UnsignedInt_Converter'
|
2024-03-14 09:57:02 -03:00
|
|
|
|
|
|
|
def use_converter(self) -> None:
|
|
|
|
if self.converter == '_PyLong_UnsignedInt_Converter':
|
2023-08-25 21:24:27 -03:00
|
|
|
self.add_include('pycore_long.h',
|
|
|
|
'_PyLong_UnsignedInt_Converter()')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'I':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = (unsigned int)PyLong_AsUnsignedLongMask({argname});
|
|
|
|
if ({paramname} == (unsigned int)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
# NOTE: Raises OverflowError for negative integer.
|
|
|
|
return self.format_code("""
|
|
|
|
{{{{
|
|
|
|
unsigned long uval = PyLong_AsUnsignedLong({argname});
|
|
|
|
if (uval == (unsigned long)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
if (uval > UINT_MAX) {{{{
|
|
|
|
PyErr_SetString(PyExc_OverflowError,
|
|
|
|
"Python int too large for C unsigned int");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = (unsigned int) uval;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class long_converter(CConverter):
|
|
|
|
type = 'long'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'l'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'l':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = PyLong_AsLong({argname});
|
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class unsigned_long_converter(CConverter):
|
|
|
|
type = 'unsigned long'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self, *, bitwise: bool = False) -> None:
|
2018-07-26 07:22:16 -03:00
|
|
|
if bitwise:
|
|
|
|
self.format_unit = 'k'
|
|
|
|
else:
|
|
|
|
self.converter = '_PyLong_UnsignedLong_Converter'
|
2024-03-14 09:57:02 -03:00
|
|
|
|
|
|
|
def use_converter(self) -> None:
|
|
|
|
if self.converter == '_PyLong_UnsignedLong_Converter':
|
2023-08-25 21:24:27 -03:00
|
|
|
self.add_include('pycore_long.h',
|
|
|
|
'_PyLong_UnsignedLong_Converter()')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'k':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyLong_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = PyLong_AsUnsignedLongMask({argname});
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'int', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
# NOTE: Raises OverflowError for negative integer.
|
|
|
|
return self.format_code("""
|
|
|
|
{paramname} = PyLong_AsUnsignedLong({argname});
|
|
|
|
if ({paramname} == (unsigned long)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2016-09-08 13:29:11 -03:00
|
|
|
class long_long_converter(CConverter):
|
|
|
|
type = 'long long'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'L'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'L':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = PyLong_AsLongLong({argname});
|
2019-10-21 03:49:48 -03:00
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2016-09-08 13:29:11 -03:00
|
|
|
class unsigned_long_long_converter(CConverter):
|
|
|
|
type = 'unsigned long long'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = int
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-16 19:32:11 -03:00
|
|
|
def converter_init(self, *, bitwise: bool = False) -> None:
|
2018-07-26 07:22:16 -03:00
|
|
|
if bitwise:
|
|
|
|
self.format_unit = 'K'
|
|
|
|
else:
|
|
|
|
self.converter = '_PyLong_UnsignedLongLong_Converter'
|
2024-03-14 09:57:02 -03:00
|
|
|
|
|
|
|
def use_converter(self) -> None:
|
|
|
|
if self.converter == '_PyLong_UnsignedLongLong_Converter':
|
2023-08-25 21:24:27 -03:00
|
|
|
self.add_include('pycore_long.h',
|
|
|
|
'_PyLong_UnsignedLongLong_Converter()')
|
2017-03-30 03:15:31 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'K':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyLong_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = PyLong_AsUnsignedLongLongMask({argname});
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'int', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
# NOTE: Raises OverflowError for negative integer.
|
|
|
|
return self.format_code("""
|
|
|
|
{paramname} = PyLong_AsUnsignedLongLong({argname});
|
|
|
|
if ({paramname} == (unsigned long long)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class Py_ssize_t_converter(CConverter):
|
|
|
|
type = 'Py_ssize_t'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(self, *, accept: TypeSet = {int}) -> None:
|
2017-03-30 03:15:31 -03:00
|
|
|
if accept == {int}:
|
|
|
|
self.format_unit = 'n'
|
|
|
|
self.default_type = int
|
|
|
|
elif accept == {int, NoneType}:
|
|
|
|
self.converter = '_Py_convert_optional_to_ssize_t'
|
|
|
|
else:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Py_ssize_t_converter: illegal 'accept' argument {accept!r}")
|
2017-03-30 03:15:31 -03:00
|
|
|
|
2024-03-14 09:57:02 -03:00
|
|
|
def use_converter(self) -> None:
|
|
|
|
if self.converter == '_Py_convert_optional_to_ssize_t':
|
|
|
|
self.add_include('pycore_abstract.h',
|
|
|
|
'_Py_convert_optional_to_ssize_t()')
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'n':
|
2023-09-03 11:28:14 -03:00
|
|
|
if limited_capi:
|
|
|
|
PyNumber_Index = 'PyNumber_Index'
|
|
|
|
else:
|
|
|
|
PyNumber_Index = '_PyNumber_Index'
|
2024-03-14 09:57:02 -03:00
|
|
|
self.add_include('pycore_abstract.h', '_PyNumber_Index()')
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{{{{
|
|
|
|
Py_ssize_t ival = -1;
|
2023-09-03 11:28:14 -03:00
|
|
|
PyObject *iobj = {PyNumber_Index}({argname});
|
2018-12-25 07:23:47 -04:00
|
|
|
if (iobj != NULL) {{{{
|
|
|
|
ival = PyLong_AsSsize_t(iobj);
|
|
|
|
Py_DECREF(iobj);
|
|
|
|
}}}}
|
|
|
|
if (ival == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = ival;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
PyNumber_Index=PyNumber_Index)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
return self.format_code("""
|
|
|
|
if ({argname} != Py_None) {{{{
|
|
|
|
if (PyIndex_Check({argname})) {{{{
|
|
|
|
{paramname} = PyNumber_AsSsize_t({argname}, PyExc_OverflowError);
|
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
{bad_argument}
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'integer or None', limited_capi=limited_capi),
|
|
|
|
)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2017-03-19 14:37:40 -03:00
|
|
|
class slice_index_converter(CConverter):
|
|
|
|
type = 'Py_ssize_t'
|
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(self, *, accept: TypeSet = {int, NoneType}) -> None:
|
2017-03-19 14:37:40 -03:00
|
|
|
if accept == {int}:
|
2017-03-30 12:29:23 -03:00
|
|
|
self.converter = '_PyEval_SliceIndexNotNone'
|
2023-09-03 11:28:14 -03:00
|
|
|
self.nullable = False
|
2017-03-19 14:37:40 -03:00
|
|
|
elif accept == {int, NoneType}:
|
2017-03-30 12:29:23 -03:00
|
|
|
self.converter = '_PyEval_SliceIndex'
|
2023-09-03 11:28:14 -03:00
|
|
|
self.nullable = True
|
2017-03-19 14:37:40 -03:00
|
|
|
else:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"slice_index_converter: illegal 'accept' argument {accept!r}")
|
2017-03-19 14:37:40 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
if self.nullable:
|
|
|
|
return self.format_code("""
|
|
|
|
if (!Py_IsNone({argname})) {{{{
|
|
|
|
if (PyIndex_Check({argname})) {{{{
|
|
|
|
{paramname} = PyNumber_AsSsize_t({argname}, NULL);
|
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
return 0;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
PyErr_SetString(PyExc_TypeError,
|
|
|
|
"slice indices must be integers or "
|
|
|
|
"None or have an __index__ method");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
else:
|
|
|
|
return self.format_code("""
|
|
|
|
if (PyIndex_Check({argname})) {{{{
|
|
|
|
{paramname} = PyNumber_AsSsize_t({argname}, NULL);
|
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
|
|
|
PyErr_SetString(PyExc_TypeError,
|
|
|
|
"slice indices must be integers or "
|
|
|
|
"have an __index__ method");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
|
2018-07-26 07:22:16 -03:00
|
|
|
class size_t_converter(CConverter):
|
|
|
|
type = 'size_t'
|
|
|
|
converter = '_PyLong_Size_t_Converter'
|
|
|
|
c_ignored_default = "0"
|
|
|
|
|
2024-03-14 09:57:02 -03:00
|
|
|
def use_converter(self) -> None:
|
2023-08-25 22:18:09 -03:00
|
|
|
self.add_include('pycore_long.h',
|
|
|
|
'_PyLong_Size_t_Converter()')
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'n':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = PyNumber_AsSsize_t({argname}, PyExc_OverflowError);
|
|
|
|
if ({paramname} == -1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
if not limited_capi:
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
|
|
|
# NOTE: Raises OverflowError for negative integer.
|
|
|
|
return self.format_code("""
|
|
|
|
{paramname} = PyLong_AsSize_t({argname});
|
|
|
|
if ({paramname} == (size_t)-1 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2017-03-19 14:37:40 -03:00
|
|
|
|
2020-10-09 17:00:45 -03:00
|
|
|
class fildes_converter(CConverter):
|
|
|
|
type = 'int'
|
|
|
|
converter = '_PyLong_FileDescriptor_Converter'
|
|
|
|
|
2024-03-14 09:57:02 -03:00
|
|
|
def use_converter(self) -> None:
|
|
|
|
self.add_include('pycore_fileutils.h',
|
|
|
|
'_PyLong_FileDescriptor_Converter()')
|
|
|
|
|
2024-03-14 06:28:58 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2024-03-14 10:58:07 -03:00
|
|
|
return self.format_code("""
|
|
|
|
{paramname} = PyObject_AsFileDescriptor({argname});
|
|
|
|
if ({paramname} < 0) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
2020-10-09 17:00:45 -03:00
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class float_converter(CConverter):
|
|
|
|
type = 'float'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = float
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'f'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0.0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'f':
|
2024-03-10 16:42:40 -03:00
|
|
|
if not limited_capi:
|
|
|
|
return self.format_code("""
|
|
|
|
if (PyFloat_CheckExact({argname})) {{{{
|
|
|
|
{paramname} = (float) (PyFloat_AS_DOUBLE({argname}));
|
|
|
|
}}}}
|
|
|
|
else
|
|
|
|
{{{{
|
|
|
|
{paramname} = (float) PyFloat_AsDouble({argname});
|
|
|
|
if ({paramname} == -1.0 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
else:
|
|
|
|
return self.format_code("""
|
2019-08-24 23:10:39 -03:00
|
|
|
{paramname} = (float) PyFloat_AsDouble({argname});
|
|
|
|
if ({paramname} == -1.0 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2024-03-10 16:42:40 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
2023-09-03 11:28:14 -03:00
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class double_converter(CConverter):
|
|
|
|
type = 'double'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = float
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'd'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "0.0"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'd':
|
2024-03-10 16:42:40 -03:00
|
|
|
if not limited_capi:
|
|
|
|
return self.format_code("""
|
|
|
|
if (PyFloat_CheckExact({argname})) {{{{
|
|
|
|
{paramname} = PyFloat_AS_DOUBLE({argname});
|
|
|
|
}}}}
|
|
|
|
else
|
|
|
|
{{{{
|
|
|
|
{paramname} = PyFloat_AsDouble({argname});
|
|
|
|
if ({paramname} == -1.0 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
else:
|
|
|
|
return self.format_code("""
|
2019-08-24 23:10:39 -03:00
|
|
|
{paramname} = PyFloat_AsDouble({argname});
|
|
|
|
if ({paramname} == -1.0 && PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2024-03-10 16:42:40 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
2023-09-03 11:28:14 -03:00
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
class Py_complex_converter(CConverter):
|
|
|
|
type = 'Py_complex'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = complex
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'D'
|
2013-11-20 13:13:52 -04:00
|
|
|
c_ignored_default = "{0.0, 0.0}"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'D':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
{paramname} = PyComplex_AsCComplex({argname});
|
|
|
|
if (PyErr_Occurred()) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
class object_converter(CConverter):
|
|
|
|
type = 'PyObject *'
|
|
|
|
format_unit = 'O'
|
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(
|
|
|
|
self, *,
|
2023-07-22 19:30:42 -03:00
|
|
|
converter: str | None = None,
|
|
|
|
type: str | None = None,
|
|
|
|
subclass_of: str | None = None
|
2023-05-17 18:05:22 -03:00
|
|
|
) -> None:
|
2014-01-12 15:09:57 -04:00
|
|
|
if converter:
|
|
|
|
if subclass_of:
|
|
|
|
fail("object: Cannot pass in both 'converter' and 'subclass_of'")
|
|
|
|
self.format_unit = 'O&'
|
|
|
|
self.converter = converter
|
|
|
|
elif subclass_of:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.format_unit = 'O!'
|
2014-01-07 16:13:13 -04:00
|
|
|
self.subclass_of = subclass_of
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2014-01-07 16:13:13 -04:00
|
|
|
if type is not None:
|
|
|
|
self.type = type
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2015-04-16 00:02:12 -03:00
|
|
|
#
|
2015-05-04 10:59:46 -03:00
|
|
|
# We define three conventions for buffer types in the 'accept' argument:
|
|
|
|
#
|
|
|
|
# buffer : any object supporting the buffer interface
|
|
|
|
# rwbuffer: any object supporting the buffer interface, but must be writeable
|
|
|
|
# robuffer: any object supporting the buffer interface, but must not be writeable
|
2015-04-16 00:02:12 -03:00
|
|
|
#
|
|
|
|
|
2015-05-04 10:59:46 -03:00
|
|
|
class buffer: pass
|
|
|
|
class rwbuffer: pass
|
|
|
|
class robuffer: pass
|
|
|
|
|
2023-12-10 11:30:02 -04:00
|
|
|
StrConverterKeyType = tuple[frozenset[type[object]], bool, bool]
|
2023-07-26 17:12:18 -03:00
|
|
|
|
|
|
|
def str_converter_key(
|
|
|
|
types: TypeSet, encoding: bool | str | None, zeroes: bool
|
|
|
|
) -> StrConverterKeyType:
|
2015-05-08 03:30:09 -03:00
|
|
|
return (frozenset(types), bool(encoding), bool(zeroes))
|
|
|
|
|
2023-07-26 17:12:18 -03:00
|
|
|
str_converter_argument_map: dict[StrConverterKeyType, str] = {}
|
2015-05-08 03:30:09 -03:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class str_converter(CConverter):
|
|
|
|
type = 'const char *'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = (str, Null, NoneType)
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 's'
|
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(
|
|
|
|
self,
|
|
|
|
*,
|
|
|
|
accept: TypeSet = {str},
|
|
|
|
encoding: str | None = None,
|
|
|
|
zeroes: bool = False
|
|
|
|
) -> None:
|
2015-04-16 00:02:12 -03:00
|
|
|
|
2015-05-08 03:30:09 -03:00
|
|
|
key = str_converter_key(accept, encoding, zeroes)
|
|
|
|
format_unit = str_converter_argument_map.get(key)
|
|
|
|
if not format_unit:
|
|
|
|
fail("str_converter: illegal combination of arguments", key)
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2015-05-08 03:30:09 -03:00
|
|
|
self.format_unit = format_unit
|
|
|
|
self.length = bool(zeroes)
|
2013-11-23 18:54:00 -04:00
|
|
|
if encoding:
|
2015-05-08 03:30:09 -03:00
|
|
|
if self.default not in (Null, None, unspecified):
|
|
|
|
fail("str_converter: Argument Clinic doesn't support default values for encoded strings")
|
2013-11-23 18:54:00 -04:00
|
|
|
self.encoding = encoding
|
2015-05-08 03:30:09 -03:00
|
|
|
self.type = 'char *'
|
|
|
|
# sorry, clinic can't support preallocated buffers
|
|
|
|
# for es# and et#
|
|
|
|
self.c_default = "NULL"
|
2019-09-14 06:24:05 -03:00
|
|
|
if NoneType in accept and self.c_default == "Py_None":
|
|
|
|
self.c_default = "NULL"
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2023-07-25 19:33:03 -03:00
|
|
|
def post_parsing(self) -> str:
|
2015-05-08 03:30:09 -03:00
|
|
|
if self.encoding:
|
2018-12-25 07:23:47 -04:00
|
|
|
name = self.name
|
2022-11-24 10:01:26 -04:00
|
|
|
return f"PyMem_FREE({name});\n"
|
2023-07-25 19:33:03 -03:00
|
|
|
else:
|
|
|
|
return ""
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 's':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyUnicode_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-11-07 18:36:13 -04:00
|
|
|
Py_ssize_t {length_name};
|
|
|
|
{paramname} = PyUnicode_AsUTF8AndSize({argname}, &{length_name});
|
2018-12-25 07:23:47 -04:00
|
|
|
if ({paramname} == NULL) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-11-07 18:36:13 -04:00
|
|
|
if (strlen({paramname}) != (size_t){length_name}) {{{{
|
|
|
|
PyErr_SetString(PyExc_ValueError, "embedded null character");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
2023-11-07 18:36:13 -04:00
|
|
|
bad_argument=self.bad_argument(displayname, 'str', limited_capi=limited_capi),
|
|
|
|
length_name=self.length_name)
|
2019-01-11 10:01:14 -04:00
|
|
|
if self.format_unit == 'z':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2019-01-11 10:01:14 -04:00
|
|
|
if ({argname} == Py_None) {{{{
|
|
|
|
{paramname} = NULL;
|
|
|
|
}}}}
|
|
|
|
else if (PyUnicode_Check({argname})) {{{{
|
2023-11-07 18:36:13 -04:00
|
|
|
Py_ssize_t {length_name};
|
|
|
|
{paramname} = PyUnicode_AsUTF8AndSize({argname}, &{length_name});
|
2019-01-11 10:01:14 -04:00
|
|
|
if ({paramname} == NULL) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-11-07 18:36:13 -04:00
|
|
|
if (strlen({paramname}) != (size_t){length_name}) {{{{
|
|
|
|
PyErr_SetString(PyExc_ValueError, "embedded null character");
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2019-01-11 10:01:14 -04:00
|
|
|
}}}}
|
|
|
|
else {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2019-01-11 10:01:14 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
2023-11-07 18:36:13 -04:00
|
|
|
bad_argument=self.bad_argument(displayname, 'str or None', limited_capi=limited_capi),
|
|
|
|
length_name=self.length_name)
|
2023-09-03 11:28:14 -03:00
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2015-05-08 03:30:09 -03:00
|
|
|
#
|
|
|
|
# This is the fourth or fifth rewrite of registering all the
|
2018-09-14 01:17:40 -03:00
|
|
|
# string converter format units. Previous approaches hid
|
2015-05-08 03:30:09 -03:00
|
|
|
# bugs--generally mismatches between the semantics of the format
|
|
|
|
# unit and the arguments necessary to represent those semantics
|
|
|
|
# properly. Hopefully with this approach we'll get it 100% right.
|
|
|
|
#
|
|
|
|
# The r() function (short for "register") both registers the
|
|
|
|
# mapping from arguments to format unit *and* registers the
|
|
|
|
# legacy C converter for that format unit.
|
|
|
|
#
|
2023-05-17 18:05:22 -03:00
|
|
|
def r(format_unit: str,
|
|
|
|
*,
|
|
|
|
accept: TypeSet,
|
|
|
|
encoding: bool = False,
|
|
|
|
zeroes: bool = False
|
|
|
|
) -> None:
|
2015-05-08 03:30:09 -03:00
|
|
|
if not encoding and format_unit != 's':
|
|
|
|
# add the legacy c converters here too.
|
|
|
|
#
|
|
|
|
# note: add_legacy_c_converter can't work for
|
|
|
|
# es, es#, et, or et#
|
|
|
|
# because of their extra encoding argument
|
|
|
|
#
|
|
|
|
# also don't add the converter for 's' because
|
|
|
|
# the metaclass for CConverter adds it for us.
|
2024-02-23 05:00:07 -04:00
|
|
|
kwargs: dict[str, Any] = {}
|
2015-05-08 03:30:09 -03:00
|
|
|
if accept != {str}:
|
|
|
|
kwargs['accept'] = accept
|
|
|
|
if zeroes:
|
|
|
|
kwargs['zeroes'] = True
|
|
|
|
added_f = functools.partial(str_converter, **kwargs)
|
|
|
|
legacy_converters[format_unit] = added_f
|
|
|
|
|
|
|
|
d = str_converter_argument_map
|
|
|
|
key = str_converter_key(accept, encoding, zeroes)
|
|
|
|
if key in d:
|
|
|
|
sys.exit("Duplicate keys specified for str_converter_argument_map!")
|
|
|
|
d[key] = format_unit
|
|
|
|
|
|
|
|
r('es', encoding=True, accept={str})
|
|
|
|
r('es#', encoding=True, zeroes=True, accept={str})
|
|
|
|
r('et', encoding=True, accept={bytes, bytearray, str})
|
|
|
|
r('et#', encoding=True, zeroes=True, accept={bytes, bytearray, str})
|
|
|
|
r('s', accept={str})
|
|
|
|
r('s#', zeroes=True, accept={robuffer, str})
|
|
|
|
r('y', accept={robuffer})
|
|
|
|
r('y#', zeroes=True, accept={robuffer})
|
|
|
|
r('z', accept={str, NoneType})
|
|
|
|
r('z#', zeroes=True, accept={robuffer, str, NoneType})
|
|
|
|
del r
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
|
|
|
class PyBytesObject_converter(CConverter):
|
|
|
|
type = 'PyBytesObject *'
|
|
|
|
format_unit = 'S'
|
2015-05-04 10:59:46 -03:00
|
|
|
# accept = {bytes}
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'S':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyBytes_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = ({type}){argname};
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'bytes', limited_capi=limited_capi),
|
|
|
|
type=self.type)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class PyByteArrayObject_converter(CConverter):
|
|
|
|
type = 'PyByteArrayObject *'
|
|
|
|
format_unit = 'Y'
|
2015-05-04 10:59:46 -03:00
|
|
|
# accept = {bytearray}
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'Y':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyByteArray_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = ({type}){argname};
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'bytearray', limited_capi=limited_capi),
|
|
|
|
type=self.type)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class unicode_converter(CConverter):
|
|
|
|
type = 'PyObject *'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = (str, Null, NoneType)
|
2013-10-19 04:09:25 -03:00
|
|
|
format_unit = 'U'
|
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'U':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (!PyUnicode_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = {argname};
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'str', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2020-06-30 03:03:15 -03:00
|
|
|
@add_legacy_c_converter('u')
|
2015-05-08 03:30:09 -03:00
|
|
|
@add_legacy_c_converter('u#', zeroes=True)
|
2015-05-04 10:59:46 -03:00
|
|
|
@add_legacy_c_converter('Z', accept={str, NoneType})
|
2015-05-08 03:30:09 -03:00
|
|
|
@add_legacy_c_converter('Z#', accept={str, NoneType}, zeroes=True)
|
2013-10-19 04:09:25 -03:00
|
|
|
class Py_UNICODE_converter(CConverter):
|
2023-05-31 14:52:33 -03:00
|
|
|
type = 'const wchar_t *'
|
2014-01-12 15:09:57 -04:00
|
|
|
default_type = (str, Null, NoneType)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(
|
|
|
|
self, *,
|
|
|
|
accept: TypeSet = {str},
|
|
|
|
zeroes: bool = False
|
|
|
|
) -> None:
|
2015-05-04 10:59:46 -03:00
|
|
|
format_unit = 'Z' if accept=={str, NoneType} else 'u'
|
2015-05-08 03:30:09 -03:00
|
|
|
if zeroes:
|
2013-11-23 18:54:00 -04:00
|
|
|
format_unit += '#'
|
|
|
|
self.length = True
|
2020-06-30 03:03:15 -03:00
|
|
|
self.format_unit = format_unit
|
|
|
|
else:
|
|
|
|
self.accept = accept
|
|
|
|
if accept == {str}:
|
|
|
|
self.converter = '_PyUnicode_WideCharString_Converter'
|
|
|
|
elif accept == {str, NoneType}:
|
|
|
|
self.converter = '_PyUnicode_WideCharString_Opt_Converter'
|
|
|
|
else:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Py_UNICODE_converter: illegal 'accept' argument {accept!r}")
|
2022-10-03 04:42:54 -03:00
|
|
|
self.c_default = "NULL"
|
2020-06-30 03:03:15 -03:00
|
|
|
|
2023-07-25 19:33:03 -03:00
|
|
|
def cleanup(self) -> str:
|
|
|
|
if self.length:
|
|
|
|
return ""
|
|
|
|
else:
|
2023-09-03 11:28:14 -03:00
|
|
|
return f"""PyMem_Free((void *){self.parser_name});\n"""
|
2020-06-30 03:03:15 -03:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2020-06-30 03:03:15 -03:00
|
|
|
if not self.length:
|
|
|
|
if self.accept == {str}:
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2020-06-30 03:03:15 -03:00
|
|
|
if (!PyUnicode_Check({argname})) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2020-06-30 03:03:15 -03:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
{paramname} = PyUnicode_AsWideCharString({argname}, NULL);
|
|
|
|
if ({paramname} == NULL) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'str', limited_capi=limited_capi),
|
|
|
|
)
|
2020-06-30 03:03:15 -03:00
|
|
|
elif self.accept == {str, NoneType}:
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2020-06-30 03:03:15 -03:00
|
|
|
if ({argname} == Py_None) {{{{
|
|
|
|
{paramname} = NULL;
|
|
|
|
}}}}
|
|
|
|
else if (PyUnicode_Check({argname})) {{{{
|
|
|
|
{paramname} = PyUnicode_AsWideCharString({argname}, NULL);
|
|
|
|
if ({paramname} == NULL) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
|
|
|
else {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2020-06-30 03:03:15 -03:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'str or None', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2015-05-04 10:59:46 -03:00
|
|
|
@add_legacy_c_converter('s*', accept={str, buffer})
|
|
|
|
@add_legacy_c_converter('z*', accept={str, buffer, NoneType})
|
|
|
|
@add_legacy_c_converter('w*', accept={rwbuffer})
|
2013-10-19 04:09:25 -03:00
|
|
|
class Py_buffer_converter(CConverter):
|
|
|
|
type = 'Py_buffer'
|
|
|
|
format_unit = 'y*'
|
|
|
|
impl_by_reference = True
|
2014-01-12 15:09:57 -04:00
|
|
|
c_ignored_default = "{NULL, NULL}"
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-17 18:05:22 -03:00
|
|
|
def converter_init(self, *, accept: TypeSet = {buffer}) -> None:
|
2014-01-12 15:09:57 -04:00
|
|
|
if self.default not in (unspecified, None):
|
|
|
|
fail("The only legal default value for Py_buffer is None.")
|
2015-05-04 10:59:46 -03:00
|
|
|
|
2014-01-06 14:34:00 -04:00
|
|
|
self.c_default = self.c_ignored_default
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2015-05-04 10:59:46 -03:00
|
|
|
if accept == {str, buffer, NoneType}:
|
|
|
|
format_unit = 'z*'
|
|
|
|
elif accept == {str, buffer}:
|
|
|
|
format_unit = 's*'
|
|
|
|
elif accept == {buffer}:
|
|
|
|
format_unit = 'y*'
|
|
|
|
elif accept == {rwbuffer}:
|
|
|
|
format_unit = 'w*'
|
2013-10-19 04:09:25 -03:00
|
|
|
else:
|
2013-11-23 18:54:00 -04:00
|
|
|
fail("Py_buffer_converter: illegal combination of arguments")
|
|
|
|
|
|
|
|
self.format_unit = format_unit
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-24 18:23:58 -03:00
|
|
|
def cleanup(self) -> str:
|
2018-12-25 07:23:47 -04:00
|
|
|
name = self.name
|
2016-06-09 10:16:06 -03:00
|
|
|
return "".join(["if (", name, ".obj) {\n PyBuffer_Release(&", name, ");\n}\n"])
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2023-09-03 11:28:14 -03:00
|
|
|
def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None:
|
2023-10-23 06:54:46 -03:00
|
|
|
# PyBUF_SIMPLE guarantees that the format units of the buffers are C-contiguous.
|
2018-12-25 07:23:47 -04:00
|
|
|
if self.format_unit == 'y*':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (PyObject_GetBuffer({argname}, &{paramname}, PyBUF_SIMPLE) != 0) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'contiguous buffer', limited_capi=limited_capi),
|
|
|
|
)
|
2018-12-25 07:23:47 -04:00
|
|
|
elif self.format_unit == 's*':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (PyUnicode_Check({argname})) {{{{
|
|
|
|
Py_ssize_t len;
|
|
|
|
const char *ptr = PyUnicode_AsUTF8AndSize({argname}, &len);
|
|
|
|
if (ptr == NULL) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2024-02-05 06:45:09 -04:00
|
|
|
if (PyBuffer_FillInfo(&{paramname}, {argname}, (void *)ptr, len, 1, PyBUF_SIMPLE) < 0) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
2018-12-25 07:23:47 -04:00
|
|
|
}}}}
|
|
|
|
else {{{{ /* any bytes-like object */
|
|
|
|
if (PyObject_GetBuffer({argname}, &{paramname}, PyBUF_SIMPLE) != 0) {{{{
|
|
|
|
goto exit;
|
|
|
|
}}}}
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'contiguous buffer', limited_capi=limited_capi),
|
|
|
|
)
|
2018-12-25 07:23:47 -04:00
|
|
|
elif self.format_unit == 'w*':
|
2023-09-03 11:28:14 -03:00
|
|
|
return self.format_code("""
|
2018-12-25 07:23:47 -04:00
|
|
|
if (PyObject_GetBuffer({argname}, &{paramname}, PyBUF_WRITABLE) < 0) {{{{
|
2023-09-03 11:28:14 -03:00
|
|
|
{bad_argument}
|
2018-12-25 07:23:47 -04:00
|
|
|
goto exit;
|
|
|
|
}}}}
|
2023-09-03 11:28:14 -03:00
|
|
|
""",
|
|
|
|
argname=argname,
|
|
|
|
bad_argument=self.bad_argument(displayname, 'read-write bytes-like object', limited_capi=limited_capi),
|
|
|
|
bad_argument2=self.bad_argument(displayname, 'contiguous buffer', limited_capi=limited_capi),
|
|
|
|
)
|
|
|
|
return super().parse_arg(argname, displayname, limited_capi=limited_capi)
|
2018-12-25 07:23:47 -04:00
|
|
|
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2023-07-04 19:13:30 -03:00
|
|
|
def correct_name_for_self(
|
|
|
|
f: Function
|
|
|
|
) -> tuple[str, str]:
|
2023-12-13 10:00:34 -04:00
|
|
|
if f.kind in {CALLABLE, METHOD_INIT, GETTER, SETTER}:
|
2014-01-24 10:17:25 -04:00
|
|
|
if f.cls:
|
|
|
|
return "PyObject *", "self"
|
2016-07-07 11:35:15 -03:00
|
|
|
return "PyObject *", "module"
|
2023-07-13 19:54:05 -03:00
|
|
|
if f.kind is STATIC_METHOD:
|
2014-01-24 10:17:25 -04:00
|
|
|
return "void *", "null"
|
|
|
|
if f.kind in (CLASS_METHOD, METHOD_NEW):
|
|
|
|
return "PyTypeObject *", "type"
|
2023-08-06 16:40:55 -03:00
|
|
|
raise AssertionError(f"Unhandled type of function f: {f.kind!r}")
|
2014-01-24 10:17:25 -04:00
|
|
|
|
|
|
|
|
2013-11-23 18:54:00 -04:00
|
|
|
class self_converter(CConverter):
|
|
|
|
"""
|
|
|
|
A special-case converter:
|
|
|
|
this is the default converter used for "self".
|
|
|
|
"""
|
2023-07-25 05:49:07 -03:00
|
|
|
type: str | None = None
|
2014-01-24 10:17:25 -04:00
|
|
|
format_unit = ''
|
|
|
|
|
2023-07-22 19:30:42 -03:00
|
|
|
def converter_init(self, *, type: str | None = None) -> None:
|
2014-02-01 02:03:12 -04:00
|
|
|
self.specified_type = type
|
|
|
|
|
2023-07-25 05:49:07 -03:00
|
|
|
def pre_render(self) -> None:
|
2013-11-23 18:54:00 -04:00
|
|
|
f = self.function
|
2014-01-24 10:17:25 -04:00
|
|
|
default_type, default_name = correct_name_for_self(f)
|
|
|
|
self.signature_name = default_name
|
2014-02-01 02:03:12 -04:00
|
|
|
self.type = self.specified_type or self.type or default_type
|
2014-01-24 10:17:25 -04:00
|
|
|
|
|
|
|
kind = self.function.kind
|
|
|
|
|
2023-07-13 19:54:05 -03:00
|
|
|
if kind is STATIC_METHOD or kind.new_or_init:
|
2014-01-24 10:17:25 -04:00
|
|
|
self.show_in_signature = False
|
|
|
|
|
|
|
|
# tp_new (METHOD_NEW) functions are of type newfunc:
|
2022-02-24 12:51:59 -04:00
|
|
|
# typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
|
2014-01-24 10:17:25 -04:00
|
|
|
#
|
|
|
|
# tp_init (METHOD_INIT) functions are of type initproc:
|
|
|
|
# typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
|
|
|
|
#
|
|
|
|
# All other functions generated by Argument Clinic are stored in
|
|
|
|
# PyMethodDef structures, in the ml_meth slot, which is of type PyCFunction:
|
|
|
|
# typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
|
|
|
|
# However! We habitually cast these functions to PyCFunction,
|
|
|
|
# since functions that accept keyword arguments don't fit this signature
|
|
|
|
# but are stored there anyway. So strict type equality isn't important
|
|
|
|
# for these functions.
|
|
|
|
#
|
|
|
|
# So:
|
|
|
|
#
|
|
|
|
# * The name of the first parameter to the impl and the parsing function will always
|
|
|
|
# be self.name.
|
|
|
|
#
|
|
|
|
# * The type of the first parameter to the impl will always be of self.type.
|
|
|
|
#
|
|
|
|
# * If the function is neither tp_new (METHOD_NEW) nor tp_init (METHOD_INIT):
|
|
|
|
# * The type of the first parameter to the parsing function is also self.type.
|
|
|
|
# This means that if you step into the parsing function, your "self" parameter
|
|
|
|
# is of the correct type, which may make debugging more pleasant.
|
|
|
|
#
|
|
|
|
# * Else if the function is tp_new (METHOD_NEW):
|
|
|
|
# * The type of the first parameter to the parsing function is "PyTypeObject *",
|
|
|
|
# so the type signature of the function call is an exact match.
|
|
|
|
# * If self.type != "PyTypeObject *", we cast the first parameter to self.type
|
|
|
|
# in the impl call.
|
|
|
|
#
|
|
|
|
# * Else if the function is tp_init (METHOD_INIT):
|
|
|
|
# * The type of the first parameter to the parsing function is "PyObject *",
|
|
|
|
# so the type signature of the function call is an exact match.
|
|
|
|
# * If self.type != "PyObject *", we cast the first parameter to self.type
|
|
|
|
# in the impl call.
|
|
|
|
|
|
|
|
@property
|
2023-07-25 05:49:07 -03:00
|
|
|
def parser_type(self) -> str:
|
|
|
|
assert self.type is not None
|
2024-02-15 12:03:58 -04:00
|
|
|
if self.function.kind in {METHOD_INIT, METHOD_NEW, STATIC_METHOD, CLASS_METHOD}:
|
|
|
|
tp, _ = correct_name_for_self(self.function)
|
|
|
|
return tp
|
|
|
|
return self.type
|
2014-01-04 16:44:57 -04:00
|
|
|
|
2023-07-25 18:08:52 -03:00
|
|
|
def render(self, parameter: Parameter, data: CRenderData) -> None:
|
2014-01-24 10:17:25 -04:00
|
|
|
"""
|
|
|
|
parameter is a clinic.Parameter instance.
|
|
|
|
data is a CRenderData instance.
|
|
|
|
"""
|
2023-07-13 19:54:05 -03:00
|
|
|
if self.function.kind is STATIC_METHOD:
|
2014-01-24 10:17:25 -04:00
|
|
|
return
|
|
|
|
|
|
|
|
self._render_self(parameter, data)
|
|
|
|
|
|
|
|
if self.type != self.parser_type:
|
|
|
|
# insert cast to impl_argument[0], aka self.
|
|
|
|
# we know we're in the first slot in all the CRenderData lists,
|
|
|
|
# because we render parameters in order, and self is always first.
|
|
|
|
assert len(data.impl_arguments) == 1
|
|
|
|
assert data.impl_arguments[0] == self.name
|
2023-07-25 18:08:52 -03:00
|
|
|
assert self.type is not None
|
2014-01-24 10:17:25 -04:00
|
|
|
data.impl_arguments[0] = '(' + self.type + ")" + data.impl_arguments[0]
|
|
|
|
|
2023-07-22 19:30:42 -03:00
|
|
|
def set_template_dict(self, template_dict: TemplateDict) -> None:
|
2014-01-24 10:17:25 -04:00
|
|
|
template_dict['self_name'] = self.name
|
|
|
|
template_dict['self_type'] = self.parser_type
|
2014-01-26 02:01:12 -04:00
|
|
|
kind = self.function.kind
|
|
|
|
cls = self.function.cls
|
|
|
|
|
2023-07-13 19:54:05 -03:00
|
|
|
if kind.new_or_init and cls and cls.typedef:
|
|
|
|
if kind is METHOD_NEW:
|
2023-01-31 16:42:03 -04:00
|
|
|
type_check = (
|
|
|
|
'({0} == base_tp || {0}->tp_init == base_tp->tp_init)'
|
|
|
|
).format(self.name)
|
2014-01-26 02:01:12 -04:00
|
|
|
else:
|
2023-01-31 16:42:03 -04:00
|
|
|
type_check = ('(Py_IS_TYPE({0}, base_tp) ||\n '
|
|
|
|
' Py_TYPE({0})->tp_new == base_tp->tp_new)'
|
|
|
|
).format(self.name)
|
2020-02-14 03:50:19 -04:00
|
|
|
|
2023-05-20 17:16:49 -03:00
|
|
|
line = f'{type_check} &&\n '
|
2020-02-14 03:50:19 -04:00
|
|
|
template_dict['self_type_check'] = line
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2023-07-22 19:30:42 -03:00
|
|
|
type_object = cls.type_object
|
2023-01-31 16:42:03 -04:00
|
|
|
type_ptr = f'PyTypeObject *base_tp = {type_object};'
|
|
|
|
template_dict['base_type_ptr'] = type_ptr
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def add_c_return_converter(
|
|
|
|
f: ReturnConverterType,
|
|
|
|
name: str | None = None
|
|
|
|
) -> ReturnConverterType:
|
2013-10-19 04:09:25 -03:00
|
|
|
if not name:
|
|
|
|
name = f.__name__
|
|
|
|
if not name.endswith('_return_converter'):
|
|
|
|
return f
|
2023-05-20 08:08:28 -03:00
|
|
|
name = name.removesuffix('_return_converter')
|
2013-10-19 04:09:25 -03:00
|
|
|
return_converters[name] = f
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
class CReturnConverterAutoRegister(type):
|
2023-05-21 17:23:14 -03:00
|
|
|
def __init__(
|
|
|
|
cls: ReturnConverterType,
|
|
|
|
name: str,
|
2023-12-10 11:30:02 -04:00
|
|
|
bases: tuple[type[object], ...],
|
2023-05-21 17:23:14 -03:00
|
|
|
classdict: dict[str, Any]
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
add_c_return_converter(cls)
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class CReturnConverter(metaclass=CReturnConverterAutoRegister):
|
|
|
|
|
2014-01-04 16:44:57 -04:00
|
|
|
# The C type to use for this variable.
|
|
|
|
# 'type' should be a Python string specifying the type, e.g. "int".
|
|
|
|
# If this is a pointer type, the type string should end with ' *'.
|
2013-10-19 04:09:25 -03:00
|
|
|
type = 'PyObject *'
|
2014-01-04 16:44:57 -04:00
|
|
|
|
|
|
|
# The Python default value for this parameter, as a Python value.
|
|
|
|
# Or the magic value "unspecified" if there is no default.
|
2023-05-18 18:58:42 -03:00
|
|
|
default: object = None
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
*,
|
|
|
|
py_default: str | None = None,
|
2023-07-24 18:23:58 -03:00
|
|
|
**kwargs: Any
|
2023-05-21 17:23:14 -03:00
|
|
|
) -> None:
|
2014-01-16 15:32:01 -04:00
|
|
|
self.py_default = py_default
|
2013-10-19 04:09:25 -03:00
|
|
|
try:
|
|
|
|
self.return_converter_init(**kwargs)
|
|
|
|
except TypeError as e:
|
|
|
|
s = ', '.join(name + '=' + repr(value) for name, value in kwargs.items())
|
|
|
|
sys.exit(self.__class__.__name__ + '(' + s + ')\n' + str(e))
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def return_converter_init(self) -> None: ...
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def declare(self, data: CRenderData) -> None:
|
|
|
|
line: list[str] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
add = line.append
|
|
|
|
add(self.type)
|
|
|
|
if not self.type.endswith('*'):
|
|
|
|
add(' ')
|
2023-05-07 18:55:37 -03:00
|
|
|
add(data.converter_retval + ';')
|
2013-10-19 04:09:25 -03:00
|
|
|
data.declarations.append(''.join(line))
|
2023-05-07 18:55:37 -03:00
|
|
|
data.return_value = data.converter_retval
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def err_occurred_if(
|
|
|
|
self,
|
|
|
|
expr: str,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None:
|
2023-05-20 17:16:49 -03:00
|
|
|
line = f'if (({expr}) && PyErr_Occurred()) {{\n goto exit;\n}}\n'
|
|
|
|
data.return_conversion.append(line)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def err_occurred_if_null_pointer(
|
|
|
|
self,
|
|
|
|
variable: str,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None:
|
2023-05-20 17:16:49 -03:00
|
|
|
line = f'if ({variable} == NULL) {{\n goto exit;\n}}\n'
|
|
|
|
data.return_conversion.append(line)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def render(
|
|
|
|
self,
|
|
|
|
function: Function,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None: ...
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
add_c_return_converter(CReturnConverter, 'object')
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class bool_return_converter(CReturnConverter):
|
2013-10-19 04:09:25 -03:00
|
|
|
type = 'int'
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def render(
|
|
|
|
self,
|
|
|
|
function: Function,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.declare(data)
|
2023-05-07 18:55:37 -03:00
|
|
|
self.err_occurred_if(f"{data.converter_retval} == -1", data)
|
|
|
|
data.return_conversion.append(
|
|
|
|
f'return_value = PyBool_FromLong((long){data.converter_retval});\n'
|
|
|
|
)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class long_return_converter(CReturnConverter):
|
|
|
|
type = 'long'
|
2014-01-12 15:09:57 -04:00
|
|
|
conversion_fn = 'PyLong_FromLong'
|
|
|
|
cast = ''
|
2014-08-05 06:55:21 -03:00
|
|
|
unsigned_cast = ''
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def render(
|
|
|
|
self,
|
|
|
|
function: Function,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.declare(data)
|
2023-05-07 18:55:37 -03:00
|
|
|
self.err_occurred_if(f"{data.converter_retval} == {self.unsigned_cast}-1", data)
|
2013-10-19 04:09:25 -03:00
|
|
|
data.return_conversion.append(
|
2023-05-07 18:55:37 -03:00
|
|
|
f'return_value = {self.conversion_fn}({self.cast}{data.converter_retval});\n'
|
|
|
|
)
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class int_return_converter(long_return_converter):
|
|
|
|
type = 'int'
|
|
|
|
cast = '(long)'
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class unsigned_long_return_converter(long_return_converter):
|
|
|
|
type = 'unsigned long'
|
|
|
|
conversion_fn = 'PyLong_FromUnsignedLong'
|
2014-08-05 06:55:21 -03:00
|
|
|
unsigned_cast = '(unsigned long)'
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class unsigned_int_return_converter(unsigned_long_return_converter):
|
|
|
|
type = 'unsigned int'
|
|
|
|
cast = '(unsigned long)'
|
2014-08-05 06:55:21 -03:00
|
|
|
unsigned_cast = '(unsigned int)'
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class Py_ssize_t_return_converter(long_return_converter):
|
2013-10-19 04:09:25 -03:00
|
|
|
type = 'Py_ssize_t'
|
2014-01-12 15:09:57 -04:00
|
|
|
conversion_fn = 'PyLong_FromSsize_t'
|
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class size_t_return_converter(long_return_converter):
|
|
|
|
type = 'size_t'
|
|
|
|
conversion_fn = 'PyLong_FromSize_t'
|
2014-08-05 06:55:21 -03:00
|
|
|
unsigned_cast = '(size_t)'
|
2014-01-12 15:09:57 -04:00
|
|
|
|
|
|
|
|
|
|
|
class double_return_converter(CReturnConverter):
|
|
|
|
type = 'double'
|
|
|
|
cast = ''
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
def render(
|
|
|
|
self,
|
|
|
|
function: Function,
|
|
|
|
data: CRenderData
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.declare(data)
|
2023-05-07 18:55:37 -03:00
|
|
|
self.err_occurred_if(f"{data.converter_retval} == -1.0", data)
|
2013-10-19 04:09:25 -03:00
|
|
|
data.return_conversion.append(
|
2023-05-07 18:55:37 -03:00
|
|
|
f'return_value = PyFloat_FromDouble({self.cast}{data.converter_retval});\n'
|
|
|
|
)
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2023-05-21 17:23:14 -03:00
|
|
|
|
2014-01-12 15:09:57 -04:00
|
|
|
class float_return_converter(double_return_converter):
|
|
|
|
type = 'float'
|
|
|
|
cast = '(double)'
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-07-04 19:13:30 -03:00
|
|
|
def eval_ast_expr(
|
|
|
|
node: ast.expr,
|
|
|
|
globals: dict[str, Any],
|
|
|
|
*,
|
|
|
|
filename: str = '-'
|
2023-07-29 09:39:21 -03:00
|
|
|
) -> Any:
|
2015-05-04 10:59:46 -03:00
|
|
|
"""
|
2023-07-29 09:39:21 -03:00
|
|
|
Takes an ast.Expr node. Compiles it into a function object,
|
|
|
|
then calls the function object with 0 arguments.
|
|
|
|
Returns the result of that function call.
|
2015-05-04 10:59:46 -03:00
|
|
|
|
|
|
|
globals represents the globals dict the expression
|
|
|
|
should see. (There's no equivalent for "locals" here.)
|
|
|
|
"""
|
|
|
|
|
|
|
|
if isinstance(node, ast.Expr):
|
|
|
|
node = node.value
|
|
|
|
|
2023-07-04 19:13:30 -03:00
|
|
|
expr = ast.Expression(node)
|
|
|
|
co = compile(expr, filename, 'eval')
|
2023-05-16 09:02:18 -03:00
|
|
|
fn = FunctionType(co, globals)
|
2015-05-04 10:59:46 -03:00
|
|
|
return fn()
|
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class IndentStack:
|
2023-07-22 19:30:42 -03:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self.indents: list[int] = []
|
|
|
|
self.margin: str | None = None
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-22 19:30:42 -03:00
|
|
|
def _ensure(self) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
if not self.indents:
|
|
|
|
fail('IndentStack expected indents, but none are defined.')
|
|
|
|
|
2023-07-20 20:19:11 -03:00
|
|
|
def measure(self, line: str) -> int:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Returns the length of the line's margin.
|
|
|
|
"""
|
|
|
|
if '\t' in line:
|
2014-02-09 02:15:29 -04:00
|
|
|
fail('Tab characters are illegal in the Argument Clinic DSL.')
|
2013-10-19 04:09:25 -03:00
|
|
|
stripped = line.lstrip()
|
|
|
|
if not len(stripped):
|
|
|
|
# we can't tell anything from an empty line
|
|
|
|
# so just pretend it's indented like our current indent
|
|
|
|
self._ensure()
|
|
|
|
return self.indents[-1]
|
|
|
|
return len(line) - len(stripped)
|
|
|
|
|
2023-07-20 20:19:11 -03:00
|
|
|
def infer(self, line: str) -> int:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Infer what is now the current margin based on this line.
|
|
|
|
Returns:
|
|
|
|
1 if we have indented (or this is the first margin)
|
|
|
|
0 if the margin has not changed
|
|
|
|
-N if we have dedented N times
|
|
|
|
"""
|
|
|
|
indent = self.measure(line)
|
|
|
|
margin = ' ' * indent
|
|
|
|
if not self.indents:
|
|
|
|
self.indents.append(indent)
|
|
|
|
self.margin = margin
|
|
|
|
return 1
|
|
|
|
current = self.indents[-1]
|
|
|
|
if indent == current:
|
|
|
|
return 0
|
|
|
|
if indent > current:
|
|
|
|
self.indents.append(indent)
|
|
|
|
self.margin = margin
|
|
|
|
return 1
|
|
|
|
# indent < current
|
|
|
|
if indent not in self.indents:
|
|
|
|
fail("Illegal outdent.")
|
|
|
|
outdent_count = 0
|
|
|
|
while indent != current:
|
|
|
|
self.indents.pop()
|
|
|
|
current = self.indents[-1]
|
|
|
|
outdent_count -= 1
|
|
|
|
self.margin = margin
|
|
|
|
return outdent_count
|
|
|
|
|
|
|
|
@property
|
2023-07-20 20:19:11 -03:00
|
|
|
def depth(self) -> int:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Returns how many margins are currently defined.
|
|
|
|
"""
|
|
|
|
return len(self.indents)
|
|
|
|
|
2023-07-20 20:19:11 -03:00
|
|
|
def dedent(self, line: str) -> str:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Dedents a line by the currently defined margin.
|
|
|
|
"""
|
2023-08-03 21:17:17 -03:00
|
|
|
assert self.margin is not None, "Cannot call .dedent() before calling .infer()"
|
2013-10-19 04:09:25 -03:00
|
|
|
margin = self.margin
|
|
|
|
indent = self.indents[-1]
|
|
|
|
if not line.startswith(margin):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail('Cannot dedent; line does not start with the previous margin.')
|
2013-10-19 04:09:25 -03:00
|
|
|
return line[indent:]
|
|
|
|
|
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
StateKeeper = Callable[[str], None]
|
2023-07-03 10:14:59 -03:00
|
|
|
ConverterArgs = dict[str, Any]
|
2023-05-20 18:55:02 -03:00
|
|
|
|
2023-07-03 18:16:21 -03:00
|
|
|
class ParamState(enum.IntEnum):
|
|
|
|
"""Parameter parsing state.
|
|
|
|
|
|
|
|
[ [ a, b, ] c, ] d, e, f=3, [ g, h, [ i ] ] <- line
|
|
|
|
01 2 3 4 5 6 <- state transitions
|
|
|
|
"""
|
|
|
|
# Before we've seen anything.
|
|
|
|
# Legal transitions: to LEFT_SQUARE_BEFORE or REQUIRED
|
|
|
|
START = 0
|
|
|
|
|
|
|
|
# Left square backets before required params.
|
|
|
|
LEFT_SQUARE_BEFORE = 1
|
|
|
|
|
|
|
|
# In a group, before required params.
|
|
|
|
GROUP_BEFORE = 2
|
|
|
|
|
|
|
|
# Required params, positional-or-keyword or positional-only (we
|
|
|
|
# don't know yet). Renumber left groups!
|
|
|
|
REQUIRED = 3
|
|
|
|
|
|
|
|
# Positional-or-keyword or positional-only params that now must have
|
|
|
|
# default values.
|
|
|
|
OPTIONAL = 4
|
|
|
|
|
|
|
|
# In a group, after required params.
|
|
|
|
GROUP_AFTER = 5
|
|
|
|
|
|
|
|
# Right square brackets after required params.
|
|
|
|
RIGHT_SQUARE_AFTER = 6
|
|
|
|
|
|
|
|
|
2023-08-16 10:47:15 -03:00
|
|
|
class FunctionNames(NamedTuple):
|
|
|
|
full_name: str
|
|
|
|
c_basename: str
|
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
class DSLParser:
|
2023-07-03 07:06:54 -03:00
|
|
|
function: Function | None
|
|
|
|
state: StateKeeper
|
|
|
|
keyword_only: bool
|
|
|
|
positional_only: bool
|
2023-08-07 08:28:08 -03:00
|
|
|
deprecated_positional: VersionTuple | None
|
2023-08-19 04:13:35 -03:00
|
|
|
deprecated_keyword: VersionTuple | None
|
2023-07-03 07:06:54 -03:00
|
|
|
group: int
|
2023-08-04 10:28:13 -03:00
|
|
|
parameter_state: ParamState
|
2023-07-03 07:06:54 -03:00
|
|
|
indent: IndentStack
|
2023-07-13 19:54:05 -03:00
|
|
|
kind: FunctionKind
|
2023-07-03 07:06:54 -03:00
|
|
|
coexist: bool
|
2023-11-24 11:58:39 -04:00
|
|
|
forced_text_signature: str | None
|
2023-07-03 07:06:54 -03:00
|
|
|
parameter_continuation: str
|
|
|
|
preserve_output: bool
|
2023-11-14 06:47:46 -04:00
|
|
|
critical_section: bool
|
2023-11-24 11:58:39 -04:00
|
|
|
target_critical_section: list[str]
|
2023-08-19 04:13:35 -03:00
|
|
|
from_version_re = re.compile(r'([*/]) +\[from +(.+)\]')
|
2023-07-03 07:06:54 -03:00
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def __init__(self, clinic: Clinic) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.clinic = clinic
|
|
|
|
|
|
|
|
self.directives = {}
|
|
|
|
for name in dir(self):
|
|
|
|
# functions that start with directive_ are added to directives
|
|
|
|
_, s, key = name.partition("directive_")
|
|
|
|
if s:
|
|
|
|
self.directives[key] = getattr(self, name)
|
|
|
|
|
|
|
|
# functions that start with at_ are too, with an @ in front
|
|
|
|
_, s, key = name.partition("at_")
|
|
|
|
if s:
|
|
|
|
self.directives['@' + key] = getattr(self, name)
|
|
|
|
|
|
|
|
self.reset()
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def reset(self) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.function = None
|
2023-07-03 07:06:54 -03:00
|
|
|
self.state = self.state_dsl_start
|
2013-10-19 04:09:25 -03:00
|
|
|
self.keyword_only = False
|
2016-06-09 10:30:29 -03:00
|
|
|
self.positional_only = False
|
2023-08-07 08:28:08 -03:00
|
|
|
self.deprecated_positional = None
|
2023-08-19 04:13:35 -03:00
|
|
|
self.deprecated_keyword = None
|
2013-10-19 04:09:25 -03:00
|
|
|
self.group = 0
|
2023-07-03 18:16:21 -03:00
|
|
|
self.parameter_state: ParamState = ParamState.START
|
2013-10-19 04:09:25 -03:00
|
|
|
self.indent = IndentStack()
|
|
|
|
self.kind = CALLABLE
|
|
|
|
self.coexist = False
|
2023-11-24 11:58:39 -04:00
|
|
|
self.forced_text_signature = None
|
2014-01-16 15:32:01 -04:00
|
|
|
self.parameter_continuation = ''
|
2014-01-17 21:47:17 -04:00
|
|
|
self.preserve_output = False
|
2023-11-14 06:47:46 -04:00
|
|
|
self.critical_section = False
|
2023-11-24 11:58:39 -04:00
|
|
|
self.target_critical_section = []
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_module(self, name: str) -> None:
|
2023-05-20 07:52:32 -03:00
|
|
|
fields = name.split('.')[:-1]
|
2013-10-19 04:09:25 -03:00
|
|
|
module, cls = self.clinic._module_and_class(fields)
|
|
|
|
if cls:
|
|
|
|
fail("Can't nest a module inside a class!")
|
2014-01-26 00:43:29 -04:00
|
|
|
|
2023-08-04 02:28:25 -03:00
|
|
|
if name in module.modules:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Already defined module {name!r}!")
|
2014-01-26 00:43:29 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
m = Module(name, module)
|
|
|
|
module.modules[name] = m
|
|
|
|
self.block.signatures.append(m)
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_class(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
typedef: str,
|
|
|
|
type_object: str
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
fields = name.split('.')
|
|
|
|
name = fields.pop()
|
|
|
|
module, cls = self.clinic._module_and_class(fields)
|
|
|
|
|
2014-01-26 00:43:29 -04:00
|
|
|
parent = cls or module
|
|
|
|
if name in parent.classes:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Already defined class {name!r}!")
|
2014-01-26 00:43:29 -04:00
|
|
|
|
|
|
|
c = Class(name, module, cls, typedef, type_object)
|
|
|
|
parent.classes[name] = c
|
2013-10-19 04:09:25 -03:00
|
|
|
self.block.signatures.append(c)
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_set(self, name: str, value: str) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
if name not in ("line_prefix", "line_suffix"):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"unknown variable {name!r}")
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
value = value.format_map({
|
|
|
|
'block comment start': '/*',
|
|
|
|
'block comment end': '*/',
|
|
|
|
})
|
|
|
|
|
|
|
|
self.clinic.__dict__[name] = value
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_destination(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
command: str,
|
2023-07-24 18:23:58 -03:00
|
|
|
*args: str
|
2023-05-20 18:55:02 -03:00
|
|
|
) -> None:
|
2023-07-22 04:43:13 -03:00
|
|
|
match command:
|
|
|
|
case "new":
|
|
|
|
self.clinic.add_destination(name, *args)
|
|
|
|
case "clear":
|
|
|
|
self.clinic.get_destination(name).clear()
|
|
|
|
case _:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"unknown destination command {command!r}")
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_output(
|
|
|
|
self,
|
|
|
|
command_or_name: str,
|
|
|
|
destination: str = ''
|
|
|
|
) -> None:
|
2015-04-03 17:09:02 -03:00
|
|
|
fd = self.clinic.destination_buffers
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name == "preset":
|
2014-01-17 21:47:17 -04:00
|
|
|
preset = self.clinic.presets.get(destination)
|
|
|
|
if not preset:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Unknown preset {destination!r}!")
|
2014-01-17 21:47:17 -04:00
|
|
|
fd.update(preset)
|
|
|
|
return
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name == "push":
|
|
|
|
self.clinic.destination_buffers_stack.append(fd.copy())
|
2014-01-17 21:47:17 -04:00
|
|
|
return
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name == "pop":
|
|
|
|
if not self.clinic.destination_buffers_stack:
|
2014-01-17 21:47:17 -04:00
|
|
|
fail("Can't 'output pop', stack is empty!")
|
2015-04-03 17:09:02 -03:00
|
|
|
previous_fd = self.clinic.destination_buffers_stack.pop()
|
2014-01-17 21:47:17 -04:00
|
|
|
fd.update(previous_fd)
|
|
|
|
return
|
|
|
|
|
|
|
|
# secret command for debugging!
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name == "print":
|
2014-01-17 21:47:17 -04:00
|
|
|
self.block.output.append(pprint.pformat(fd))
|
|
|
|
self.block.output.append('\n')
|
|
|
|
return
|
|
|
|
|
2022-07-05 06:06:04 -03:00
|
|
|
d = self.clinic.get_destination_buffer(destination)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name == "everything":
|
2014-01-17 21:47:17 -04:00
|
|
|
for name in list(fd):
|
|
|
|
fd[name] = d
|
|
|
|
return
|
|
|
|
|
2015-04-03 17:09:02 -03:00
|
|
|
if command_or_name not in fd:
|
2023-08-04 09:13:10 -03:00
|
|
|
allowed = ["preset", "push", "pop", "print", "everything"]
|
|
|
|
allowed.extend(fd)
|
|
|
|
fail(f"Invalid command or destination name {command_or_name!r}. "
|
|
|
|
"Must be one of:\n -",
|
|
|
|
"\n - ".join([repr(word) for word in allowed]))
|
2015-04-03 17:09:02 -03:00
|
|
|
fd[command_or_name] = d
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_dump(self, name: str) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
self.block.output.append(self.clinic.get_destination(name).dump())
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_printout(self, *args: str) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
self.block.output.append(' '.join(args))
|
|
|
|
self.block.output.append('\n')
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def directive_preserve(self) -> None:
|
2014-01-17 21:47:17 -04:00
|
|
|
if self.preserve_output:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("Can't have 'preserve' twice in one block!")
|
2014-01-17 21:47:17 -04:00
|
|
|
self.preserve_output = True
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def at_classmethod(self) -> None:
|
2014-01-16 15:32:01 -04:00
|
|
|
if self.kind is not CALLABLE:
|
|
|
|
fail("Can't set @classmethod, function is not a normal callable")
|
2013-10-19 04:09:25 -03:00
|
|
|
self.kind = CLASS_METHOD
|
|
|
|
|
2023-11-18 19:05:49 -04:00
|
|
|
def at_critical_section(self, *args: str) -> None:
|
|
|
|
if len(args) > 2:
|
|
|
|
fail("Up to 2 critical section variables are supported")
|
|
|
|
self.target_critical_section.extend(args)
|
2023-11-14 06:47:46 -04:00
|
|
|
self.critical_section = True
|
|
|
|
|
2023-11-30 06:40:53 -04:00
|
|
|
def at_getter(self) -> None:
|
2023-12-13 10:00:34 -04:00
|
|
|
match self.kind:
|
|
|
|
case FunctionKind.GETTER:
|
|
|
|
fail("Cannot apply @getter twice to the same function!")
|
|
|
|
case FunctionKind.SETTER:
|
|
|
|
fail("Cannot apply both @getter and @setter to the same function!")
|
|
|
|
case _:
|
|
|
|
self.kind = FunctionKind.GETTER
|
|
|
|
|
|
|
|
def at_setter(self) -> None:
|
|
|
|
match self.kind:
|
|
|
|
case FunctionKind.SETTER:
|
|
|
|
fail("Cannot apply @setter twice to the same function!")
|
|
|
|
case FunctionKind.GETTER:
|
|
|
|
fail("Cannot apply both @getter and @setter to the same function!")
|
|
|
|
case _:
|
|
|
|
self.kind = FunctionKind.SETTER
|
2023-11-30 06:40:53 -04:00
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def at_staticmethod(self) -> None:
|
2014-01-16 15:32:01 -04:00
|
|
|
if self.kind is not CALLABLE:
|
|
|
|
fail("Can't set @staticmethod, function is not a normal callable")
|
2013-10-19 04:09:25 -03:00
|
|
|
self.kind = STATIC_METHOD
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def at_coexist(self) -> None:
|
2014-01-16 15:32:01 -04:00
|
|
|
if self.coexist:
|
|
|
|
fail("Called @coexist twice!")
|
2013-10-19 04:09:25 -03:00
|
|
|
self.coexist = True
|
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
def at_text_signature(self, text_signature: str) -> None:
|
|
|
|
if self.forced_text_signature:
|
|
|
|
fail("Called @text_signature twice!")
|
|
|
|
self.forced_text_signature = text_signature
|
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def parse(self, block: Block) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.reset()
|
|
|
|
self.block = block
|
2014-01-17 21:47:17 -04:00
|
|
|
self.saved_output = self.block.output
|
|
|
|
block.output = []
|
2013-10-19 04:09:25 -03:00
|
|
|
block_start = self.clinic.block_parser.line_number
|
|
|
|
lines = block.input.split('\n')
|
|
|
|
for line_number, line in enumerate(lines, self.clinic.block_parser.block_start_line_number):
|
|
|
|
if '\t' in line:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f'Tab characters are illegal in the Clinic DSL: {line!r}',
|
|
|
|
line_number=block_start)
|
2023-08-02 21:00:06 -03:00
|
|
|
try:
|
|
|
|
self.state(line)
|
|
|
|
except ClinicError as exc:
|
|
|
|
exc.lineno = line_number
|
2024-02-15 08:22:21 -04:00
|
|
|
exc.filename = self.clinic.filename
|
2023-08-02 21:00:06 -03:00
|
|
|
raise
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
self.do_post_block_processing_cleanup(line_number)
|
2023-07-29 15:47:42 -03:00
|
|
|
block.output.extend(self.clinic.language.render(self.clinic, block.signatures))
|
2014-01-17 21:47:17 -04:00
|
|
|
|
|
|
|
if self.preserve_output:
|
|
|
|
if block.output:
|
2024-02-15 08:22:21 -04:00
|
|
|
fail("'preserve' only works for blocks that don't produce any output!",
|
|
|
|
line_number=line_number)
|
2014-01-17 21:47:17 -04:00
|
|
|
block.output = self.saved_output
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 20:32:27 -03:00
|
|
|
def in_docstring(self) -> bool:
|
|
|
|
"""Return true if we are processing a docstring."""
|
|
|
|
return self.state in {
|
|
|
|
self.state_parameter_docstring,
|
|
|
|
self.state_function_docstring,
|
|
|
|
}
|
|
|
|
|
|
|
|
def valid_line(self, line: str) -> bool:
|
2013-10-19 04:09:25 -03:00
|
|
|
# ignore comment-only lines
|
|
|
|
if line.lstrip().startswith('#'):
|
2023-07-02 20:42:38 -03:00
|
|
|
return False
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
# Ignore empty lines too
|
|
|
|
# (but not in docstring sections!)
|
2023-08-01 20:32:27 -03:00
|
|
|
if not self.in_docstring() and not line.strip():
|
2023-07-02 20:42:38 -03:00
|
|
|
return False
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-02 20:42:38 -03:00
|
|
|
return True
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-20 18:55:02 -03:00
|
|
|
def next(
|
|
|
|
self,
|
|
|
|
state: StateKeeper,
|
|
|
|
line: str | None = None
|
|
|
|
) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.state = state
|
|
|
|
if line is not None:
|
|
|
|
self.state(line)
|
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_dsl_start(self, line: str) -> None:
|
2023-07-02 20:42:38 -03:00
|
|
|
if not self.valid_line(line):
|
2013-10-19 04:09:25 -03:00
|
|
|
return
|
2014-02-01 02:03:12 -04:00
|
|
|
|
|
|
|
# is it a directive?
|
|
|
|
fields = shlex.split(line)
|
|
|
|
directive_name = fields[0]
|
|
|
|
directive = self.directives.get(directive_name, None)
|
|
|
|
if directive:
|
|
|
|
try:
|
|
|
|
directive(*fields[1:])
|
|
|
|
except TypeError as e:
|
|
|
|
fail(str(e))
|
|
|
|
return
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
self.next(self.state_modulename_name, line)
|
|
|
|
|
2024-02-15 04:45:21 -04:00
|
|
|
def parse_function_names(self, line: str) -> FunctionNames:
|
2023-08-16 10:47:15 -03:00
|
|
|
left, as_, right = line.partition(' as ')
|
|
|
|
full_name = left.strip()
|
|
|
|
c_basename = right.strip()
|
|
|
|
if as_ and not c_basename:
|
|
|
|
fail("No C basename provided after 'as' keyword")
|
|
|
|
if not c_basename:
|
|
|
|
fields = full_name.split(".")
|
|
|
|
if fields[-1] == '__new__':
|
|
|
|
fields.pop()
|
|
|
|
c_basename = "_".join(fields)
|
2024-02-16 02:42:15 -04:00
|
|
|
if not libclinic.is_legal_py_identifier(full_name):
|
2023-08-16 10:47:15 -03:00
|
|
|
fail(f"Illegal function name: {full_name!r}")
|
2024-02-16 02:42:15 -04:00
|
|
|
if not libclinic.is_legal_c_identifier(c_basename):
|
2023-08-16 10:47:15 -03:00
|
|
|
fail(f"Illegal C basename: {c_basename!r}")
|
2024-02-15 04:45:21 -04:00
|
|
|
names = FunctionNames(full_name=full_name, c_basename=c_basename)
|
|
|
|
self.normalize_function_kind(names.full_name)
|
|
|
|
return names
|
2023-08-16 10:47:15 -03:00
|
|
|
|
2024-02-15 04:45:21 -04:00
|
|
|
def normalize_function_kind(self, fullname: str) -> None:
|
|
|
|
# Fetch the method name and possibly class.
|
2023-08-15 11:00:52 -03:00
|
|
|
fields = fullname.split('.')
|
|
|
|
name = fields.pop()
|
|
|
|
_, cls = self.clinic._module_and_class(fields)
|
2024-02-15 04:45:21 -04:00
|
|
|
|
|
|
|
# Check special method requirements.
|
2023-08-15 11:00:52 -03:00
|
|
|
if name in unsupported_special_methods:
|
|
|
|
fail(f"{name!r} is a special method and cannot be converted to Argument Clinic!")
|
2024-02-15 04:45:21 -04:00
|
|
|
if name == '__init__' and (self.kind is not CALLABLE or not cls):
|
|
|
|
fail(f"{name!r} must be a normal method; got '{self.kind}'!")
|
|
|
|
if name == '__new__' and (self.kind is not CLASS_METHOD or not cls):
|
|
|
|
fail("'__new__' must be a class method!")
|
|
|
|
if self.kind in {GETTER, SETTER} and not cls:
|
|
|
|
fail("@getter and @setter must be methods")
|
|
|
|
|
|
|
|
# Normalise self.kind.
|
2023-08-15 11:00:52 -03:00
|
|
|
if name == '__new__':
|
2024-02-15 04:45:21 -04:00
|
|
|
self.kind = METHOD_NEW
|
2023-08-15 11:00:52 -03:00
|
|
|
elif name == '__init__':
|
2024-02-15 04:45:21 -04:00
|
|
|
self.kind = METHOD_INIT
|
|
|
|
|
|
|
|
def resolve_return_converter(
|
|
|
|
self, full_name: str, forced_converter: str
|
|
|
|
) -> CReturnConverter:
|
|
|
|
if forced_converter:
|
|
|
|
if self.kind in {GETTER, SETTER}:
|
|
|
|
fail(f"@{self.kind.name.lower()} method cannot define a return type")
|
2024-03-01 13:41:20 -04:00
|
|
|
if self.kind is METHOD_INIT:
|
|
|
|
fail("__init__ methods cannot define a return type")
|
2024-02-15 04:45:21 -04:00
|
|
|
ast_input = f"def x() -> {forced_converter}: pass"
|
|
|
|
try:
|
|
|
|
module_node = ast.parse(ast_input)
|
|
|
|
except SyntaxError:
|
|
|
|
fail(f"Badly formed annotation for {full_name!r}: {forced_converter!r}")
|
|
|
|
function_node = module_node.body[0]
|
|
|
|
assert isinstance(function_node, ast.FunctionDef)
|
|
|
|
try:
|
|
|
|
name, legacy, kwargs = self.parse_converter(function_node.returns)
|
|
|
|
if legacy:
|
|
|
|
fail(f"Legacy converter {name!r} not allowed as a return converter")
|
|
|
|
if name not in return_converters:
|
|
|
|
fail(f"No available return converter called {name!r}")
|
|
|
|
return return_converters[name](**kwargs)
|
|
|
|
except ValueError:
|
|
|
|
fail(f"Badly formed annotation for {full_name!r}: {forced_converter!r}")
|
|
|
|
|
2024-03-04 08:51:28 -04:00
|
|
|
if self.kind in {METHOD_INIT, SETTER}:
|
|
|
|
return int_return_converter()
|
2024-02-15 04:45:21 -04:00
|
|
|
return CReturnConverter()
|
|
|
|
|
|
|
|
def parse_cloned_function(self, names: FunctionNames, existing: str) -> None:
|
|
|
|
full_name, c_basename = names
|
|
|
|
fields = [x.strip() for x in existing.split('.')]
|
|
|
|
function_name = fields.pop()
|
|
|
|
module, cls = self.clinic._module_and_class(fields)
|
|
|
|
parent = cls or module
|
|
|
|
|
|
|
|
for existing_function in parent.functions:
|
|
|
|
if existing_function.name == function_name:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
print(f"{cls=}, {module=}, {existing=}", file=sys.stderr)
|
|
|
|
print(f"{(cls or module).functions=}", file=sys.stderr)
|
|
|
|
fail(f"Couldn't find existing function {existing!r}!")
|
|
|
|
|
|
|
|
fields = [x.strip() for x in full_name.split('.')]
|
|
|
|
function_name = fields.pop()
|
|
|
|
module, cls = self.clinic._module_and_class(fields)
|
|
|
|
|
|
|
|
overrides: dict[str, Any] = {
|
|
|
|
"name": function_name,
|
|
|
|
"full_name": full_name,
|
|
|
|
"module": module,
|
|
|
|
"cls": cls,
|
|
|
|
"c_basename": c_basename,
|
|
|
|
"docstring": "",
|
|
|
|
}
|
|
|
|
if not (existing_function.kind is self.kind and
|
|
|
|
existing_function.coexist == self.coexist):
|
|
|
|
# Allow __new__ or __init__ methods.
|
|
|
|
if existing_function.kind.new_or_init:
|
|
|
|
overrides["kind"] = self.kind
|
|
|
|
# Future enhancement: allow custom return converters
|
|
|
|
overrides["return_converter"] = CReturnConverter()
|
2023-11-30 06:40:53 -04:00
|
|
|
else:
|
2024-02-15 04:45:21 -04:00
|
|
|
fail("'kind' of function and cloned function don't match! "
|
|
|
|
"(@classmethod/@staticmethod/@coexist)")
|
|
|
|
function = existing_function.copy(**overrides)
|
|
|
|
self.function = function
|
|
|
|
self.block.signatures.append(function)
|
|
|
|
(cls or module).functions.append(function)
|
|
|
|
self.next(self.state_function_docstring)
|
2023-08-15 11:00:52 -03:00
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_modulename_name(self, line: str) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
# looking for declaration, which establishes the leftmost column
|
|
|
|
# line should be
|
|
|
|
# modulename.fnname [as c_basename] [-> return annotation]
|
|
|
|
# square brackets denote optional syntax.
|
|
|
|
#
|
2014-01-15 02:22:41 -04:00
|
|
|
# alternatively:
|
|
|
|
# modulename.fnname [as c_basename] = modulename.existing_fn_name
|
|
|
|
# clones the parameters and return converter from that
|
|
|
|
# function. you can't modify them. you must enter a
|
|
|
|
# new docstring.
|
|
|
|
#
|
2013-10-19 04:09:25 -03:00
|
|
|
# (but we might find a directive first!)
|
|
|
|
#
|
|
|
|
# this line is permitted to start with whitespace.
|
|
|
|
# we'll call this number of spaces F (for "function").
|
|
|
|
|
2023-08-04 16:41:04 -03:00
|
|
|
assert self.valid_line(line)
|
2013-10-19 04:09:25 -03:00
|
|
|
self.indent.infer(line)
|
|
|
|
|
2014-01-15 02:22:41 -04:00
|
|
|
# are we cloning?
|
|
|
|
before, equals, existing = line.rpartition('=')
|
|
|
|
if equals:
|
|
|
|
existing = existing.strip()
|
2024-02-16 02:42:15 -04:00
|
|
|
if libclinic.is_legal_py_identifier(existing):
|
2014-01-15 02:22:41 -04:00
|
|
|
# we're cloning!
|
2024-02-15 04:45:21 -04:00
|
|
|
names = self.parse_function_names(before)
|
|
|
|
return self.parse_cloned_function(names, existing)
|
2014-01-15 02:22:41 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
line, _, returns = line.partition('->')
|
2023-07-27 18:51:18 -03:00
|
|
|
returns = returns.strip()
|
2023-08-16 10:47:15 -03:00
|
|
|
full_name, c_basename = self.parse_function_names(line)
|
2024-02-15 04:45:21 -04:00
|
|
|
return_converter = self.resolve_return_converter(full_name, returns)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
fields = [x.strip() for x in full_name.split('.')]
|
|
|
|
function_name = fields.pop()
|
|
|
|
module, cls = self.clinic._module_and_class(fields)
|
|
|
|
|
2024-02-15 04:45:21 -04:00
|
|
|
func = Function(
|
|
|
|
name=function_name,
|
|
|
|
full_name=full_name,
|
|
|
|
module=module,
|
|
|
|
cls=cls,
|
|
|
|
c_basename=c_basename,
|
|
|
|
return_converter=return_converter,
|
|
|
|
kind=self.kind,
|
|
|
|
coexist=self.coexist,
|
|
|
|
critical_section=self.critical_section,
|
|
|
|
target_critical_section=self.target_critical_section
|
|
|
|
)
|
|
|
|
self.add_function(func)
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
self.next(self.state_parameters_start)
|
|
|
|
|
2024-02-15 04:45:21 -04:00
|
|
|
def add_function(self, func: Function) -> None:
|
|
|
|
# Insert a self converter automatically.
|
|
|
|
tp, name = correct_name_for_self(func)
|
|
|
|
if func.cls and tp == "PyObject *":
|
|
|
|
func.self_converter = self_converter(name, name, func,
|
|
|
|
type=func.cls.typedef)
|
|
|
|
else:
|
|
|
|
func.self_converter = self_converter(name, name, func)
|
|
|
|
func.parameters[name] = Parameter(
|
|
|
|
name,
|
|
|
|
inspect.Parameter.POSITIONAL_ONLY,
|
|
|
|
function=func,
|
|
|
|
converter=func.self_converter
|
|
|
|
)
|
|
|
|
|
|
|
|
self.block.signatures.append(func)
|
|
|
|
self.function = func
|
|
|
|
(func.cls or func.module).functions.append(func)
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
# Now entering the parameters section. The rules, formally stated:
|
|
|
|
#
|
|
|
|
# * All lines must be indented with spaces only.
|
|
|
|
# * The first line must be a parameter declaration.
|
|
|
|
# * The first line must be indented.
|
|
|
|
# * This first line establishes the indent for parameters.
|
|
|
|
# * We'll call this number of spaces P (for "parameter").
|
|
|
|
# * Thenceforth:
|
|
|
|
# * Lines indented with P spaces specify a parameter.
|
|
|
|
# * Lines indented with > P spaces are docstrings for the previous
|
|
|
|
# parameter.
|
|
|
|
# * We'll call this number of spaces D (for "docstring").
|
|
|
|
# * All subsequent lines indented with >= D spaces are stored as
|
|
|
|
# part of the per-parameter docstring.
|
|
|
|
# * All lines will have the first D spaces of the indent stripped
|
|
|
|
# before they are stored.
|
|
|
|
# * It's illegal to have a line starting with a number of spaces X
|
|
|
|
# such that P < X < D.
|
|
|
|
# * A line with < P spaces is the first line of the function
|
|
|
|
# docstring, which ends processing for parameters and per-parameter
|
|
|
|
# docstrings.
|
|
|
|
# * The first line of the function docstring must be at the same
|
|
|
|
# indent as the function declaration.
|
|
|
|
# * It's illegal to have any line in the parameters section starting
|
|
|
|
# with X spaces such that F < X < P. (As before, F is the indent
|
|
|
|
# of the function declaration.)
|
|
|
|
#
|
|
|
|
# Also, currently Argument Clinic places the following restrictions on groups:
|
|
|
|
# * Each group must contain at least one parameter.
|
|
|
|
# * Each group may contain at most one group, which must be the furthest
|
|
|
|
# thing in the group from the required parameters. (The nested group
|
|
|
|
# must be the first in the group when it's before the required
|
|
|
|
# parameters, and the last thing in the group when after the required
|
|
|
|
# parameters.)
|
|
|
|
# * There may be at most one (top-level) group to the left or right of
|
|
|
|
# the required parameters.
|
|
|
|
# * You must specify a slash, and it must be after all parameters.
|
|
|
|
# (In other words: either all parameters are positional-only,
|
|
|
|
# or none are.)
|
|
|
|
#
|
|
|
|
# Said another way:
|
|
|
|
# * Each group must contain at least one parameter.
|
|
|
|
# * All left square brackets before the required parameters must be
|
|
|
|
# consecutive. (You can't have a left square bracket followed
|
|
|
|
# by a parameter, then another left square bracket. You can't
|
|
|
|
# have a left square bracket, a parameter, a right square bracket,
|
|
|
|
# and then a left square bracket.)
|
|
|
|
# * All right square brackets after the required parameters must be
|
|
|
|
# consecutive.
|
|
|
|
#
|
|
|
|
# These rules are enforced with a single state variable:
|
|
|
|
# "parameter_state". (Previously the code was a miasma of ifs and
|
2023-07-03 18:16:21 -03:00
|
|
|
# separate boolean state variables.) The states are defined in the
|
|
|
|
# ParamState class.
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_parameters_start(self, line: str) -> None:
|
2023-07-02 20:42:38 -03:00
|
|
|
if not self.valid_line(line):
|
2013-10-19 04:09:25 -03:00
|
|
|
return
|
|
|
|
|
|
|
|
# if this line is not indented, we have no parameters
|
|
|
|
if not self.indent.infer(line):
|
|
|
|
return self.next(self.state_function_docstring, line)
|
|
|
|
|
2024-03-04 08:51:28 -04:00
|
|
|
assert self.function is not None
|
|
|
|
if self.function.kind in {GETTER, SETTER}:
|
|
|
|
getset = self.function.kind.name.lower()
|
|
|
|
fail(f"@{getset} methods cannot define parameters")
|
|
|
|
|
2014-01-16 15:32:01 -04:00
|
|
|
self.parameter_continuation = ''
|
2013-10-19 04:09:25 -03:00
|
|
|
return self.next(self.state_parameter, line)
|
|
|
|
|
|
|
|
|
2023-07-24 18:23:58 -03:00
|
|
|
def to_required(self) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Transition to the "required" parameter state.
|
|
|
|
"""
|
2023-07-03 18:16:21 -03:00
|
|
|
if self.parameter_state is not ParamState.REQUIRED:
|
|
|
|
self.parameter_state = ParamState.REQUIRED
|
2023-07-24 18:23:58 -03:00
|
|
|
assert self.function is not None
|
2013-10-19 04:09:25 -03:00
|
|
|
for p in self.function.parameters.values():
|
|
|
|
p.group = -p.group
|
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_parameter(self, line: str) -> None:
|
2023-07-03 19:10:46 -03:00
|
|
|
assert isinstance(self.function, Function)
|
2014-01-16 15:32:01 -04:00
|
|
|
|
2023-07-02 20:42:38 -03:00
|
|
|
if not self.valid_line(line):
|
2013-10-19 04:09:25 -03:00
|
|
|
return
|
|
|
|
|
2023-07-03 19:10:46 -03:00
|
|
|
if self.parameter_continuation:
|
|
|
|
line = self.parameter_continuation + ' ' + line.lstrip()
|
|
|
|
self.parameter_continuation = ''
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
assert self.indent.depth == 2
|
|
|
|
indent = self.indent.infer(line)
|
|
|
|
if indent == -1:
|
|
|
|
# we outdented, must be to definition column
|
|
|
|
return self.next(self.state_function_docstring, line)
|
|
|
|
|
|
|
|
if indent == 1:
|
|
|
|
# we indented, must be to new parameter docstring column
|
|
|
|
return self.next(self.state_parameter_docstring_start, line)
|
|
|
|
|
2014-01-16 15:32:01 -04:00
|
|
|
line = line.rstrip()
|
|
|
|
if line.endswith('\\'):
|
|
|
|
self.parameter_continuation = line[:-1]
|
|
|
|
return
|
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
line = line.lstrip()
|
2023-08-19 04:13:35 -03:00
|
|
|
version: VersionTuple | None = None
|
|
|
|
match = self.from_version_re.fullmatch(line)
|
2023-08-07 08:28:08 -03:00
|
|
|
if match:
|
2023-08-19 04:13:35 -03:00
|
|
|
line = match[1]
|
|
|
|
version = self.parse_version(match[2])
|
2023-08-07 08:28:08 -03:00
|
|
|
|
2023-07-17 19:37:11 -03:00
|
|
|
func = self.function
|
2023-08-07 08:28:08 -03:00
|
|
|
match line:
|
2023-07-17 19:37:11 -03:00
|
|
|
case '*':
|
2023-08-19 04:13:35 -03:00
|
|
|
self.parse_star(func, version)
|
2023-07-17 19:37:11 -03:00
|
|
|
case '[':
|
|
|
|
self.parse_opening_square_bracket(func)
|
|
|
|
case ']':
|
|
|
|
self.parse_closing_square_bracket(func)
|
|
|
|
case '/':
|
2023-08-19 04:13:35 -03:00
|
|
|
self.parse_slash(func, version)
|
2023-07-17 19:37:11 -03:00
|
|
|
case param:
|
|
|
|
self.parse_parameter(param)
|
|
|
|
|
|
|
|
def parse_parameter(self, line: str) -> None:
|
|
|
|
assert self.function is not None
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-03 18:16:21 -03:00
|
|
|
match self.parameter_state:
|
|
|
|
case ParamState.START | ParamState.REQUIRED:
|
2013-10-19 04:09:25 -03:00
|
|
|
self.to_required()
|
2023-07-03 18:16:21 -03:00
|
|
|
case ParamState.LEFT_SQUARE_BEFORE:
|
|
|
|
self.parameter_state = ParamState.GROUP_BEFORE
|
|
|
|
case ParamState.GROUP_BEFORE:
|
|
|
|
if not self.group:
|
|
|
|
self.to_required()
|
|
|
|
case ParamState.GROUP_AFTER | ParamState.OPTIONAL:
|
|
|
|
pass
|
|
|
|
case st:
|
|
|
|
fail(f"Function {self.function.name} has an unsupported group configuration. (Unexpected state {st}.a)")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-02-01 02:03:12 -04:00
|
|
|
# handle "as" for parameters too
|
|
|
|
c_name = None
|
|
|
|
name, have_as_token, trailing = line.partition(' as ')
|
|
|
|
if have_as_token:
|
|
|
|
name = name.strip()
|
|
|
|
if ' ' not in name:
|
|
|
|
fields = trailing.strip().split(' ')
|
|
|
|
if not fields:
|
|
|
|
fail("Invalid 'as' clause!")
|
|
|
|
c_name = fields[0]
|
|
|
|
if c_name.endswith(':'):
|
|
|
|
name += ':'
|
|
|
|
c_name = c_name[:-1]
|
|
|
|
fields[0] = name
|
|
|
|
line = ' '.join(fields)
|
|
|
|
|
2023-07-03 19:10:46 -03:00
|
|
|
default: str | None
|
2014-01-16 15:32:01 -04:00
|
|
|
base, equals, default = line.rpartition('=')
|
|
|
|
if not equals:
|
|
|
|
base = default
|
|
|
|
default = None
|
2014-01-26 00:43:29 -04:00
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
module = None
|
|
|
|
try:
|
2023-05-20 17:16:49 -03:00
|
|
|
ast_input = f"def x({base}): pass"
|
2013-10-19 04:09:25 -03:00
|
|
|
module = ast.parse(ast_input)
|
|
|
|
except SyntaxError:
|
2014-01-16 15:32:01 -04:00
|
|
|
try:
|
2014-01-26 00:43:29 -04:00
|
|
|
# the last = was probably inside a function call, like
|
2015-05-04 10:59:46 -03:00
|
|
|
# c: int(accept={str})
|
2014-01-26 00:43:29 -04:00
|
|
|
# so assume there was no actual default value.
|
2014-01-16 15:32:01 -04:00
|
|
|
default = None
|
2023-05-20 17:16:49 -03:00
|
|
|
ast_input = f"def x({line}): pass"
|
2014-01-16 15:32:01 -04:00
|
|
|
module = ast.parse(ast_input)
|
|
|
|
except SyntaxError:
|
|
|
|
pass
|
2013-10-19 04:09:25 -03:00
|
|
|
if not module:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {self.function.name!r} has an invalid parameter declaration:\n\t",
|
|
|
|
repr(line))
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-03 19:10:46 -03:00
|
|
|
function = module.body[0]
|
|
|
|
assert isinstance(function, ast.FunctionDef)
|
|
|
|
function_args = function.args
|
2015-05-04 10:59:46 -03:00
|
|
|
|
|
|
|
if len(function_args.args) > 1:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {self.function.name!r} has an "
|
|
|
|
f"invalid parameter declaration (comma?): {line!r}")
|
2015-05-04 10:59:46 -03:00
|
|
|
if function_args.defaults or function_args.kw_defaults:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {self.function.name!r} has an "
|
|
|
|
f"invalid parameter declaration (default value?): {line!r}")
|
2021-07-16 12:43:02 -03:00
|
|
|
if function_args.kwarg:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {self.function.name!r} has an "
|
|
|
|
f"invalid parameter declaration (**kwargs?): {line!r}")
|
2015-05-04 10:59:46 -03:00
|
|
|
|
2021-07-16 12:43:02 -03:00
|
|
|
if function_args.vararg:
|
2024-02-15 08:22:21 -04:00
|
|
|
if any(p.is_vararg() for p in self.function.parameters.values()):
|
|
|
|
fail("Too many var args")
|
2021-07-16 12:43:02 -03:00
|
|
|
is_vararg = True
|
|
|
|
parameter = function_args.vararg
|
|
|
|
else:
|
|
|
|
is_vararg = False
|
|
|
|
parameter = function_args.args[0]
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-07 15:53:01 -04:00
|
|
|
parameter_name = parameter.arg
|
|
|
|
name, legacy, kwargs = self.parse_converter(parameter.annotation)
|
|
|
|
|
2023-12-21 19:14:24 -04:00
|
|
|
value: object
|
2014-01-16 15:32:01 -04:00
|
|
|
if not default:
|
2023-07-03 18:16:21 -03:00
|
|
|
if self.parameter_state is ParamState.OPTIONAL:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Can't have a parameter without a default ({parameter_name!r}) "
|
2023-07-03 18:16:21 -03:00
|
|
|
"after a parameter with a default!")
|
2021-07-16 12:43:02 -03:00
|
|
|
if is_vararg:
|
|
|
|
value = NULL
|
|
|
|
kwargs.setdefault('c_default', "NULL")
|
|
|
|
else:
|
|
|
|
value = unspecified
|
2014-01-16 15:32:01 -04:00
|
|
|
if 'py_default' in kwargs:
|
|
|
|
fail("You can't specify py_default without specifying a default value!")
|
|
|
|
else:
|
2021-07-16 12:43:02 -03:00
|
|
|
if is_vararg:
|
|
|
|
fail("Vararg can't take a default value!")
|
|
|
|
|
2023-07-03 18:16:21 -03:00
|
|
|
if self.parameter_state is ParamState.REQUIRED:
|
|
|
|
self.parameter_state = ParamState.OPTIONAL
|
2014-01-16 15:32:01 -04:00
|
|
|
default = default.strip()
|
2014-01-25 00:52:30 -04:00
|
|
|
bad = False
|
2023-05-20 17:16:49 -03:00
|
|
|
ast_input = f"x = {default}"
|
2014-01-16 15:32:01 -04:00
|
|
|
try:
|
|
|
|
module = ast.parse(ast_input)
|
|
|
|
|
2014-01-24 10:17:25 -04:00
|
|
|
if 'c_default' not in kwargs:
|
|
|
|
# we can only represent very simple data values in C.
|
2020-08-11 10:26:59 -03:00
|
|
|
# detect whether default is okay, via a denylist
|
2014-01-24 10:17:25 -04:00
|
|
|
# of disallowed ast nodes.
|
|
|
|
class DetectBadNodes(ast.NodeVisitor):
|
|
|
|
bad = False
|
2023-07-24 18:23:58 -03:00
|
|
|
def bad_node(self, node: ast.AST) -> None:
|
2014-01-24 10:17:25 -04:00
|
|
|
self.bad = True
|
|
|
|
|
|
|
|
# inline function call
|
|
|
|
visit_Call = bad_node
|
|
|
|
# inline if statement ("x = 3 if y else z")
|
|
|
|
visit_IfExp = bad_node
|
|
|
|
|
|
|
|
# comprehensions and generator expressions
|
|
|
|
visit_ListComp = visit_SetComp = bad_node
|
|
|
|
visit_DictComp = visit_GeneratorExp = bad_node
|
|
|
|
|
|
|
|
# literals for advanced types
|
|
|
|
visit_Dict = visit_Set = bad_node
|
|
|
|
visit_List = visit_Tuple = bad_node
|
|
|
|
|
|
|
|
# "starred": "a = [1, 2, 3]; *a"
|
|
|
|
visit_Starred = bad_node
|
|
|
|
|
2020-08-11 10:26:59 -03:00
|
|
|
denylist = DetectBadNodes()
|
|
|
|
denylist.visit(module)
|
|
|
|
bad = denylist.bad
|
2014-01-24 10:17:25 -04:00
|
|
|
else:
|
|
|
|
# if they specify a c_default, we can be more lenient about the default value.
|
2014-01-25 00:52:30 -04:00
|
|
|
# but at least make an attempt at ensuring it's a valid expression.
|
|
|
|
try:
|
|
|
|
value = eval(default)
|
|
|
|
except NameError:
|
|
|
|
pass # probably a named constant
|
|
|
|
except Exception as e:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("Malformed expression given as default value "
|
|
|
|
f"{default!r} caused {e!r}")
|
2023-08-08 09:12:49 -03:00
|
|
|
else:
|
|
|
|
if value is unspecified:
|
|
|
|
fail("'unspecified' is not a legal default value!")
|
2014-01-24 10:17:25 -04:00
|
|
|
if bad:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Unsupported expression as default value: {default!r}")
|
2014-01-16 15:32:01 -04:00
|
|
|
|
2023-07-03 19:10:46 -03:00
|
|
|
assignment = module.body[0]
|
|
|
|
assert isinstance(assignment, ast.Assign)
|
|
|
|
expr = assignment.value
|
2014-01-16 15:32:01 -04:00
|
|
|
# mild hack: explicitly support NULL as a default value
|
2023-07-03 19:10:46 -03:00
|
|
|
c_default: str | None
|
2014-01-16 15:32:01 -04:00
|
|
|
if isinstance(expr, ast.Name) and expr.id == 'NULL':
|
|
|
|
value = NULL
|
2019-09-14 06:24:05 -03:00
|
|
|
py_default = '<unrepresentable>'
|
2014-01-16 15:32:01 -04:00
|
|
|
c_default = "NULL"
|
|
|
|
elif (isinstance(expr, ast.BinOp) or
|
2018-09-27 11:42:37 -03:00
|
|
|
(isinstance(expr, ast.UnaryOp) and
|
2023-05-09 18:16:22 -03:00
|
|
|
not (isinstance(expr.operand, ast.Constant) and
|
|
|
|
type(expr.operand.value) in {int, float, complex})
|
2018-09-27 11:42:37 -03:00
|
|
|
)):
|
2014-01-16 15:32:01 -04:00
|
|
|
c_default = kwargs.get("c_default")
|
|
|
|
if not (isinstance(c_default, str) and c_default):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"When you specify an expression ({default!r}) "
|
|
|
|
f"as your default value, "
|
|
|
|
f"you MUST specify a valid c_default.",
|
|
|
|
ast.dump(expr))
|
2014-01-16 15:32:01 -04:00
|
|
|
py_default = default
|
|
|
|
value = unknown
|
|
|
|
elif isinstance(expr, ast.Attribute):
|
|
|
|
a = []
|
2023-07-03 19:10:46 -03:00
|
|
|
n: ast.expr | ast.Attribute = expr
|
2014-01-16 15:32:01 -04:00
|
|
|
while isinstance(n, ast.Attribute):
|
|
|
|
a.append(n.attr)
|
|
|
|
n = n.value
|
|
|
|
if not isinstance(n, ast.Name):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Unsupported default value {default!r} "
|
|
|
|
"(looked like a Python constant)")
|
2014-01-16 15:32:01 -04:00
|
|
|
a.append(n.id)
|
|
|
|
py_default = ".".join(reversed(a))
|
|
|
|
|
|
|
|
c_default = kwargs.get("c_default")
|
|
|
|
if not (isinstance(c_default, str) and c_default):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"When you specify a named constant ({py_default!r}) "
|
|
|
|
"as your default value, "
|
|
|
|
"you MUST specify a valid c_default.")
|
2014-01-16 15:32:01 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
value = eval(py_default)
|
|
|
|
except NameError:
|
|
|
|
value = unknown
|
|
|
|
else:
|
|
|
|
value = ast.literal_eval(expr)
|
|
|
|
py_default = repr(value)
|
2023-07-03 19:10:46 -03:00
|
|
|
if isinstance(value, (bool, NoneType)):
|
2014-01-16 15:32:01 -04:00
|
|
|
c_default = "Py_" + py_default
|
|
|
|
elif isinstance(value, str):
|
2023-12-22 20:37:39 -04:00
|
|
|
c_default = libclinic.c_repr(value)
|
2014-01-16 15:32:01 -04:00
|
|
|
else:
|
|
|
|
c_default = py_default
|
|
|
|
|
|
|
|
except SyntaxError as e:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Syntax error: {e.text!r}")
|
2014-01-16 15:32:01 -04:00
|
|
|
except (ValueError, AttributeError):
|
|
|
|
value = unknown
|
2014-01-12 15:09:57 -04:00
|
|
|
c_default = kwargs.get("c_default")
|
2014-01-16 15:32:01 -04:00
|
|
|
py_default = default
|
2014-01-12 15:09:57 -04:00
|
|
|
if not (isinstance(c_default, str) and c_default):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("When you specify a named constant "
|
|
|
|
f"({py_default!r}) as your default value, "
|
|
|
|
"you MUST specify a valid c_default.")
|
2014-01-12 15:09:57 -04:00
|
|
|
|
2014-01-16 15:32:01 -04:00
|
|
|
kwargs.setdefault('c_default', c_default)
|
|
|
|
kwargs.setdefault('py_default', py_default)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
dict = legacy_converters if legacy else converters
|
|
|
|
legacy_str = "legacy " if legacy else ""
|
|
|
|
if name not in dict:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f'{name!r} is not a valid {legacy_str}converter')
|
2014-02-01 02:03:12 -04:00
|
|
|
# if you use a c_name for the parameter, we just give that name to the converter
|
|
|
|
# but the parameter object gets the python name
|
|
|
|
converter = dict[name](c_name or parameter_name, parameter_name, self.function, value, **kwargs)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-07-03 19:10:46 -03:00
|
|
|
kind: inspect._ParameterKind
|
2021-07-16 12:43:02 -03:00
|
|
|
if is_vararg:
|
|
|
|
kind = inspect.Parameter.VAR_POSITIONAL
|
|
|
|
elif self.keyword_only:
|
|
|
|
kind = inspect.Parameter.KEYWORD_ONLY
|
|
|
|
else:
|
|
|
|
kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
|
2014-01-24 10:17:25 -04:00
|
|
|
|
2013-11-23 18:54:00 -04:00
|
|
|
if isinstance(converter, self_converter):
|
2014-01-24 10:17:25 -04:00
|
|
|
if len(self.function.parameters) == 1:
|
2023-07-03 18:16:21 -03:00
|
|
|
if self.parameter_state is not ParamState.REQUIRED:
|
2014-01-24 10:17:25 -04:00
|
|
|
fail("A 'self' parameter cannot be marked optional.")
|
|
|
|
if value is not unspecified:
|
|
|
|
fail("A 'self' parameter cannot have a default value.")
|
|
|
|
if self.group:
|
|
|
|
fail("A 'self' parameter cannot be in an optional group.")
|
|
|
|
kind = inspect.Parameter.POSITIONAL_ONLY
|
2023-07-03 18:16:21 -03:00
|
|
|
self.parameter_state = ParamState.START
|
2014-01-24 10:17:25 -04:00
|
|
|
self.function.parameters.clear()
|
|
|
|
else:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("A 'self' parameter, if specified, must be the "
|
|
|
|
"very first thing in the parameter block.")
|
2013-11-23 18:54:00 -04:00
|
|
|
|
2020-05-07 10:39:59 -03:00
|
|
|
if isinstance(converter, defining_class_converter):
|
|
|
|
_lp = len(self.function.parameters)
|
|
|
|
if _lp == 1:
|
2023-07-03 18:16:21 -03:00
|
|
|
if self.parameter_state is not ParamState.REQUIRED:
|
2020-05-07 10:39:59 -03:00
|
|
|
fail("A 'defining_class' parameter cannot be marked optional.")
|
|
|
|
if value is not unspecified:
|
|
|
|
fail("A 'defining_class' parameter cannot have a default value.")
|
|
|
|
if self.group:
|
|
|
|
fail("A 'defining_class' parameter cannot be in an optional group.")
|
|
|
|
else:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail("A 'defining_class' parameter, if specified, must either "
|
|
|
|
"be the first thing in the parameter block, or come just "
|
|
|
|
"after 'self'.")
|
2020-05-07 10:39:59 -03:00
|
|
|
|
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
p = Parameter(parameter_name, kind, function=self.function,
|
|
|
|
converter=converter, default=value, group=self.group,
|
|
|
|
deprecated_positional=self.deprecated_positional)
|
2014-01-17 21:47:17 -04:00
|
|
|
|
2022-07-07 06:29:34 -03:00
|
|
|
names = [k.name for k in self.function.parameters.values()]
|
|
|
|
if parameter_name in names[1:]:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"You can't have two parameters named {parameter_name!r}!")
|
2022-07-07 06:29:34 -03:00
|
|
|
elif names and parameter_name == names[0] and c_name is None:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Parameter {parameter_name!r} requires a custom C name")
|
2022-07-07 06:29:34 -03:00
|
|
|
|
|
|
|
key = f"{parameter_name}_as_{c_name}" if c_name else parameter_name
|
|
|
|
self.function.parameters[key] = p
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-05-21 20:29:43 -03:00
|
|
|
@staticmethod
|
2023-07-03 10:14:59 -03:00
|
|
|
def parse_converter(
|
|
|
|
annotation: ast.expr | None
|
|
|
|
) -> tuple[str, bool, ConverterArgs]:
|
2023-05-21 20:29:43 -03:00
|
|
|
match annotation:
|
|
|
|
case ast.Constant(value=str() as value):
|
|
|
|
return value, True, {}
|
|
|
|
case ast.Name(name):
|
|
|
|
return name, False, {}
|
|
|
|
case ast.Call(func=ast.Name(name)):
|
|
|
|
symbols = globals()
|
2023-07-03 10:14:59 -03:00
|
|
|
kwargs: ConverterArgs = {}
|
|
|
|
for node in annotation.keywords:
|
|
|
|
if not isinstance(node.arg, str):
|
|
|
|
fail("Cannot use a kwarg splat in a function-call annotation")
|
|
|
|
kwargs[node.arg] = eval_ast_expr(node.value, symbols)
|
2023-05-21 20:29:43 -03:00
|
|
|
return name, False, kwargs
|
|
|
|
case _:
|
|
|
|
fail(
|
|
|
|
"Annotations must be either a name, a function call, or a string."
|
|
|
|
)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
def parse_version(self, thenceforth: str) -> VersionTuple:
|
|
|
|
"""Parse Python version in `[from ...]` marker."""
|
2023-08-07 08:28:08 -03:00
|
|
|
assert isinstance(self.function, Function)
|
|
|
|
|
|
|
|
try:
|
|
|
|
major, minor = thenceforth.split(".")
|
2023-08-19 04:13:35 -03:00
|
|
|
return int(major), int(minor)
|
2023-08-07 08:28:08 -03:00
|
|
|
except ValueError:
|
|
|
|
fail(
|
2023-08-19 04:13:35 -03:00
|
|
|
f"Function {self.function.name!r}: expected format '[from major.minor]' "
|
2023-08-07 08:28:08 -03:00
|
|
|
f"where 'major' and 'minor' are integers; got {thenceforth!r}"
|
|
|
|
)
|
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
def parse_star(self, function: Function, version: VersionTuple | None) -> None:
|
|
|
|
"""Parse keyword-only parameter marker '*'.
|
|
|
|
|
|
|
|
The 'version' parameter signifies the future version from which
|
|
|
|
the marker will take effect (None means it is already in effect).
|
|
|
|
"""
|
|
|
|
if version is None:
|
|
|
|
if self.keyword_only:
|
|
|
|
fail(f"Function {function.name!r} uses '*' more than once.")
|
2023-10-16 11:26:11 -03:00
|
|
|
self.check_previous_star()
|
2023-08-19 04:13:35 -03:00
|
|
|
self.check_remaining_star()
|
|
|
|
self.keyword_only = True
|
|
|
|
else:
|
|
|
|
if self.keyword_only:
|
2023-08-21 10:59:58 -03:00
|
|
|
fail(f"Function {function.name!r}: '* [from ...]' must precede '*'")
|
2023-08-19 04:13:35 -03:00
|
|
|
if self.deprecated_positional:
|
2023-08-21 10:59:58 -03:00
|
|
|
if self.deprecated_positional == version:
|
|
|
|
fail(f"Function {function.name!r} uses '* [from "
|
|
|
|
f"{version[0]}.{version[1]}]' more than once.")
|
|
|
|
if self.deprecated_positional < version:
|
|
|
|
fail(f"Function {function.name!r}: '* [from "
|
|
|
|
f"{version[0]}.{version[1]}]' must precede '* [from "
|
|
|
|
f"{self.deprecated_positional[0]}.{self.deprecated_positional[1]}]'")
|
2023-08-19 04:13:35 -03:00
|
|
|
self.deprecated_positional = version
|
2023-07-17 19:37:11 -03:00
|
|
|
|
|
|
|
def parse_opening_square_bracket(self, function: Function) -> None:
|
|
|
|
"""Parse opening parameter group symbol '['."""
|
|
|
|
match self.parameter_state:
|
|
|
|
case ParamState.START | ParamState.LEFT_SQUARE_BEFORE:
|
|
|
|
self.parameter_state = ParamState.LEFT_SQUARE_BEFORE
|
|
|
|
case ParamState.REQUIRED | ParamState.GROUP_AFTER:
|
|
|
|
self.parameter_state = ParamState.GROUP_AFTER
|
|
|
|
case st:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {function.name!r} "
|
|
|
|
f"has an unsupported group configuration. "
|
2023-07-17 19:37:11 -03:00
|
|
|
f"(Unexpected state {st}.b)")
|
|
|
|
self.group += 1
|
|
|
|
function.docstring_only = True
|
|
|
|
|
|
|
|
def parse_closing_square_bracket(self, function: Function) -> None:
|
|
|
|
"""Parse closing parameter group symbol ']'."""
|
|
|
|
if not self.group:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {function.name!r} has a ']' without a matching '['.")
|
2023-07-17 19:37:11 -03:00
|
|
|
if not any(p.group == self.group for p in function.parameters.values()):
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {function.name!r} has an empty group. "
|
2023-07-17 19:37:11 -03:00
|
|
|
"All groups must contain at least one parameter.")
|
|
|
|
self.group -= 1
|
|
|
|
match self.parameter_state:
|
|
|
|
case ParamState.LEFT_SQUARE_BEFORE | ParamState.GROUP_BEFORE:
|
|
|
|
self.parameter_state = ParamState.GROUP_BEFORE
|
|
|
|
case ParamState.GROUP_AFTER | ParamState.RIGHT_SQUARE_AFTER:
|
|
|
|
self.parameter_state = ParamState.RIGHT_SQUARE_AFTER
|
|
|
|
case st:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {function.name!r} "
|
|
|
|
f"has an unsupported group configuration. "
|
2023-07-17 19:37:11 -03:00
|
|
|
f"(Unexpected state {st}.c)")
|
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
def parse_slash(self, function: Function, version: VersionTuple | None) -> None:
|
|
|
|
"""Parse positional-only parameter marker '/'.
|
|
|
|
|
|
|
|
The 'version' parameter signifies the future version from which
|
|
|
|
the marker will take effect (None means it is already in effect).
|
|
|
|
"""
|
|
|
|
if version is None:
|
|
|
|
if self.deprecated_keyword:
|
|
|
|
fail(f"Function {function.name!r}: '/' must precede '/ [from ...]'")
|
|
|
|
if self.deprecated_positional:
|
|
|
|
fail(f"Function {function.name!r}: '/' must precede '* [from ...]'")
|
|
|
|
if self.keyword_only:
|
|
|
|
fail(f"Function {function.name!r}: '/' must precede '*'")
|
|
|
|
if self.positional_only:
|
|
|
|
fail(f"Function {function.name!r} uses '/' more than once.")
|
|
|
|
else:
|
|
|
|
if self.deprecated_keyword:
|
2023-08-21 10:59:58 -03:00
|
|
|
if self.deprecated_keyword == version:
|
|
|
|
fail(f"Function {function.name!r} uses '/ [from "
|
|
|
|
f"{version[0]}.{version[1]}]' more than once.")
|
|
|
|
if self.deprecated_keyword > version:
|
|
|
|
fail(f"Function {function.name!r}: '/ [from "
|
|
|
|
f"{version[0]}.{version[1]}]' must precede '/ [from "
|
|
|
|
f"{self.deprecated_keyword[0]}.{self.deprecated_keyword[1]}]'")
|
2023-08-19 04:13:35 -03:00
|
|
|
if self.deprecated_positional:
|
|
|
|
fail(f"Function {function.name!r}: '/ [from ...]' must precede '* [from ...]'")
|
|
|
|
if self.keyword_only:
|
|
|
|
fail(f"Function {function.name!r}: '/ [from ...]' must precede '*'")
|
2023-07-17 19:37:11 -03:00
|
|
|
self.positional_only = True
|
2023-08-19 04:13:35 -03:00
|
|
|
self.deprecated_keyword = version
|
|
|
|
if version is not None:
|
|
|
|
found = False
|
|
|
|
for p in reversed(function.parameters.values()):
|
|
|
|
found = p.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
|
|
|
|
break
|
|
|
|
if not found:
|
|
|
|
fail(f"Function {function.name!r} specifies '/ [from ...]' "
|
|
|
|
f"without preceding parameters.")
|
2023-07-17 19:37:11 -03:00
|
|
|
# REQUIRED and OPTIONAL are allowed here, that allows positional-only
|
|
|
|
# without option groups to work (and have default values!)
|
|
|
|
allowed = {
|
|
|
|
ParamState.REQUIRED,
|
|
|
|
ParamState.OPTIONAL,
|
|
|
|
ParamState.RIGHT_SQUARE_AFTER,
|
|
|
|
ParamState.GROUP_BEFORE,
|
|
|
|
}
|
|
|
|
if (self.parameter_state not in allowed) or self.group:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {function.name!r} has an unsupported group configuration. "
|
2023-07-17 19:37:11 -03:00
|
|
|
f"(Unexpected state {self.parameter_state}.d)")
|
|
|
|
# fixup preceding parameters
|
|
|
|
for p in function.parameters.values():
|
2023-08-19 04:13:35 -03:00
|
|
|
if p.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD:
|
|
|
|
if version is None:
|
|
|
|
p.kind = inspect.Parameter.POSITIONAL_ONLY
|
2023-08-21 10:59:58 -03:00
|
|
|
elif p.deprecated_keyword is None:
|
2023-08-19 04:13:35 -03:00
|
|
|
p.deprecated_keyword = version
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_parameter_docstring_start(self, line: str) -> None:
|
2023-07-22 19:30:42 -03:00
|
|
|
assert self.indent.margin is not None, "self.margin.infer() has not yet been called to set the margin"
|
2013-10-19 04:09:25 -03:00
|
|
|
self.parameter_docstring_indent = len(self.indent.margin)
|
|
|
|
assert self.indent.depth == 3
|
|
|
|
return self.next(self.state_parameter_docstring, line)
|
|
|
|
|
2023-08-01 20:32:27 -03:00
|
|
|
def docstring_append(self, obj: Function | Parameter, line: str) -> None:
|
|
|
|
"""Add a rstripped line to the current docstring."""
|
2023-08-09 02:55:34 -03:00
|
|
|
# gh-80282: We filter out non-ASCII characters from the docstring,
|
|
|
|
# since historically, some compilers may balk on non-ASCII input.
|
|
|
|
# If you're using Argument Clinic in an external project,
|
|
|
|
# you may not need to support the same array of platforms as CPython,
|
|
|
|
# so you may be able to remove this restriction.
|
2023-08-02 09:40:23 -03:00
|
|
|
matches = re.finditer(r'[^\x00-\x7F]', line)
|
|
|
|
if offending := ", ".join([repr(m[0]) for m in matches]):
|
|
|
|
warn("Non-ascii characters are not allowed in docstrings:",
|
|
|
|
offending)
|
|
|
|
|
2023-08-01 20:32:27 -03:00
|
|
|
docstring = obj.docstring
|
|
|
|
if docstring:
|
|
|
|
docstring += "\n"
|
|
|
|
if stripped := line.rstrip():
|
|
|
|
docstring += self.indent.dedent(stripped)
|
|
|
|
obj.docstring = docstring
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
# every line of the docstring must start with at least F spaces,
|
|
|
|
# where F > P.
|
|
|
|
# these F spaces will be stripped.
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_parameter_docstring(self, line: str) -> None:
|
2023-08-01 20:32:27 -03:00
|
|
|
if not self.valid_line(line):
|
2013-10-19 04:09:25 -03:00
|
|
|
return
|
|
|
|
|
|
|
|
indent = self.indent.measure(line)
|
|
|
|
if indent < self.parameter_docstring_indent:
|
|
|
|
self.indent.infer(line)
|
|
|
|
assert self.indent.depth < 3
|
|
|
|
if self.indent.depth == 2:
|
|
|
|
# back to a parameter
|
|
|
|
return self.next(self.state_parameter, line)
|
|
|
|
assert self.indent.depth == 1
|
|
|
|
return self.next(self.state_function_docstring, line)
|
|
|
|
|
2023-07-24 18:23:58 -03:00
|
|
|
assert self.function and self.function.parameters
|
2023-08-01 20:32:27 -03:00
|
|
|
last_param = next(reversed(self.function.parameters.values()))
|
|
|
|
self.docstring_append(last_param, line)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
# the final stanza of the DSL is the docstring.
|
2023-08-01 17:42:39 -03:00
|
|
|
def state_function_docstring(self, line: str) -> None:
|
2023-07-24 18:23:58 -03:00
|
|
|
assert self.function is not None
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
if self.group:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Function {self.function.name!r} has a ']' without a matching '['.")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 20:32:27 -03:00
|
|
|
if not self.valid_line(line):
|
2013-10-19 04:09:25 -03:00
|
|
|
return
|
|
|
|
|
2023-08-01 20:32:27 -03:00
|
|
|
self.docstring_append(self.function, line)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
def format_docstring_signature(
|
|
|
|
self, f: Function, parameters: list[Parameter]
|
|
|
|
) -> str:
|
2023-12-22 16:28:15 -04:00
|
|
|
lines = []
|
|
|
|
lines.append(f.displayname)
|
2023-08-07 17:34:53 -03:00
|
|
|
if self.forced_text_signature:
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append(self.forced_text_signature)
|
2023-12-20 08:52:12 -04:00
|
|
|
elif f.kind in {GETTER, SETTER}:
|
|
|
|
# @getter and @setter do not need signatures like a method or a function.
|
|
|
|
return ''
|
2023-08-07 17:34:53 -03:00
|
|
|
else:
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append('(')
|
2023-08-07 17:34:53 -03:00
|
|
|
|
|
|
|
# populate "right_bracket_count" field for every parameter
|
|
|
|
assert parameters, "We should always have a self parameter. " + repr(f)
|
|
|
|
assert isinstance(parameters[0].converter, self_converter)
|
|
|
|
# self is always positional-only.
|
|
|
|
assert parameters[0].is_positional_only()
|
|
|
|
assert parameters[0].right_bracket_count == 0
|
|
|
|
positional_only = True
|
|
|
|
for p in parameters[1:]:
|
|
|
|
if not p.is_positional_only():
|
|
|
|
positional_only = False
|
|
|
|
else:
|
|
|
|
assert positional_only
|
|
|
|
if positional_only:
|
|
|
|
p.right_bracket_count = abs(p.group)
|
|
|
|
else:
|
|
|
|
# don't put any right brackets around non-positional-only parameters, ever.
|
|
|
|
p.right_bracket_count = 0
|
|
|
|
|
|
|
|
right_bracket_count = 0
|
|
|
|
|
|
|
|
def fix_right_bracket_count(desired: int) -> str:
|
|
|
|
nonlocal right_bracket_count
|
|
|
|
s = ''
|
|
|
|
while right_bracket_count < desired:
|
|
|
|
s += '['
|
|
|
|
right_bracket_count += 1
|
|
|
|
while right_bracket_count > desired:
|
|
|
|
s += ']'
|
|
|
|
right_bracket_count -= 1
|
|
|
|
return s
|
|
|
|
|
|
|
|
need_slash = False
|
|
|
|
added_slash = False
|
|
|
|
need_a_trailing_slash = False
|
|
|
|
|
|
|
|
# we only need a trailing slash:
|
|
|
|
# * if this is not a "docstring_only" signature
|
|
|
|
# * and if the last *shown* parameter is
|
|
|
|
# positional only
|
|
|
|
if not f.docstring_only:
|
|
|
|
for p in reversed(parameters):
|
|
|
|
if not p.converter.show_in_signature:
|
|
|
|
continue
|
|
|
|
if p.is_positional_only():
|
|
|
|
need_a_trailing_slash = True
|
|
|
|
break
|
2014-02-09 02:15:29 -04:00
|
|
|
|
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
added_star = False
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
first_parameter = True
|
|
|
|
last_p = parameters[-1]
|
2023-12-22 16:28:15 -04:00
|
|
|
line_length = len(''.join(lines))
|
2023-08-07 17:34:53 -03:00
|
|
|
indent = " " * line_length
|
|
|
|
def add_parameter(text: str) -> None:
|
|
|
|
nonlocal line_length
|
|
|
|
nonlocal first_parameter
|
|
|
|
if first_parameter:
|
2014-02-09 02:15:29 -04:00
|
|
|
s = text
|
2023-08-07 17:34:53 -03:00
|
|
|
first_parameter = False
|
|
|
|
else:
|
|
|
|
s = ' ' + text
|
|
|
|
if line_length + len(s) >= 72:
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.extend(["\n", indent])
|
2023-08-07 17:34:53 -03:00
|
|
|
line_length = len(indent)
|
|
|
|
s = text
|
|
|
|
line_length += len(s)
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append(s)
|
2023-08-07 17:34:53 -03:00
|
|
|
|
|
|
|
for p in parameters:
|
|
|
|
if not p.converter.show_in_signature:
|
|
|
|
continue
|
|
|
|
assert p.name
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
is_self = isinstance(p.converter, self_converter)
|
|
|
|
if is_self and f.docstring_only:
|
|
|
|
# this isn't a real machine-parsable signature,
|
|
|
|
# so let's not print the "self" parameter
|
|
|
|
continue
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
if p.is_positional_only():
|
|
|
|
need_slash = not f.docstring_only
|
|
|
|
elif need_slash and not (added_slash or p.is_positional_only()):
|
|
|
|
added_slash = True
|
|
|
|
add_parameter('/,')
|
|
|
|
|
|
|
|
if p.is_keyword_only() and not added_star:
|
|
|
|
added_star = True
|
|
|
|
add_parameter('*,')
|
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines = [fix_right_bracket_count(p.right_bracket_count)]
|
2023-08-07 17:34:53 -03:00
|
|
|
|
|
|
|
if isinstance(p.converter, self_converter):
|
|
|
|
# annotate first parameter as being a "self".
|
|
|
|
#
|
|
|
|
# if inspect.Signature gets this function,
|
|
|
|
# and it's already bound, the self parameter
|
|
|
|
# will be stripped off.
|
|
|
|
#
|
|
|
|
# if it's not bound, it should be marked
|
|
|
|
# as positional-only.
|
|
|
|
#
|
|
|
|
# note: we don't print "self" for __init__,
|
|
|
|
# because this isn't actually the signature
|
|
|
|
# for __init__. (it can't be, __init__ doesn't
|
|
|
|
# have a docstring.) if this is an __init__
|
|
|
|
# (or __new__), then this signature is for
|
|
|
|
# calling the class to construct a new instance.
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append('$')
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
if p.is_vararg():
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append("*")
|
2021-07-16 12:43:02 -03:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
name = p.converter.signature_name or p.name
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append(name)
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
if not p.is_vararg() and p.converter.is_optional():
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append('=')
|
2023-08-07 17:34:53 -03:00
|
|
|
value = p.converter.py_default
|
|
|
|
if not value:
|
|
|
|
value = repr(p.converter.default)
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append(value)
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-08-07 17:34:53 -03:00
|
|
|
if (p != last_p) or need_a_trailing_slash:
|
2023-12-22 16:28:15 -04:00
|
|
|
p_lines.append(',')
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
p_output = "".join(p_lines)
|
|
|
|
add_parameter(p_output)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append(fix_right_bracket_count(0))
|
2023-08-07 17:34:53 -03:00
|
|
|
if need_a_trailing_slash:
|
|
|
|
add_parameter('/')
|
2023-12-22 16:28:15 -04:00
|
|
|
lines.append(')')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-01-16 15:32:01 -04:00
|
|
|
# PEP 8 says:
|
|
|
|
#
|
|
|
|
# The Python standard library will not use function annotations
|
|
|
|
# as that would result in a premature commitment to a particular
|
|
|
|
# annotation style. Instead, the annotations are left for users
|
|
|
|
# to discover and experiment with useful annotation styles.
|
|
|
|
#
|
|
|
|
# therefore this is commented out:
|
|
|
|
#
|
|
|
|
# if f.return_converter.py_default:
|
2023-12-22 16:28:15 -04:00
|
|
|
# lines.append(' -> ')
|
|
|
|
# lines.append(f.return_converter.py_default)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2014-02-09 02:15:29 -04:00
|
|
|
if not f.docstring_only:
|
2023-12-22 20:37:39 -04:00
|
|
|
lines.append("\n" + libclinic.SIG_END_MARKER + "\n")
|
2014-02-09 02:15:29 -04:00
|
|
|
|
2023-12-22 16:28:15 -04:00
|
|
|
signature_line = "".join(lines)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
# now fix up the places where the brackets look wrong
|
2023-08-08 18:12:35 -03:00
|
|
|
return signature_line.replace(', ]', ',] ')
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
@staticmethod
|
|
|
|
def format_docstring_parameters(params: list[Parameter]) -> str:
|
|
|
|
"""Create substitution text for {parameters}"""
|
2023-12-22 16:28:15 -04:00
|
|
|
return "".join(p.render_docstring() + "\n" for p in params if p.docstring)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
def format_docstring(self) -> str:
|
|
|
|
assert self.function is not None
|
|
|
|
f = self.function
|
2023-12-20 08:52:12 -04:00
|
|
|
# For the following special cases, it does not make sense to render a docstring.
|
|
|
|
if f.kind in {METHOD_INIT, METHOD_NEW, GETTER, SETTER} and not f.docstring:
|
2023-08-08 18:12:35 -03:00
|
|
|
return f.docstring
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
# Enforce the summary line!
|
|
|
|
# The first line of a docstring should be a summary of the function.
|
|
|
|
# It should fit on one line (80 columns? 79 maybe?) and be a paragraph
|
|
|
|
# by itself.
|
|
|
|
#
|
|
|
|
# Argument Clinic enforces the following rule:
|
|
|
|
# * either the docstring is empty,
|
|
|
|
# * or it must have a summary line.
|
|
|
|
#
|
|
|
|
# Guido said Clinic should enforce this:
|
|
|
|
# http://mail.python.org/pipermail/python-dev/2013-June/127110.html
|
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
lines = f.docstring.split('\n')
|
2013-10-19 04:09:25 -03:00
|
|
|
if len(lines) >= 2:
|
|
|
|
if lines[1]:
|
2023-08-04 09:13:10 -03:00
|
|
|
fail(f"Docstring for {f.full_name!r} does not have a summary line!\n"
|
|
|
|
"Every non-blank function docstring must start with "
|
|
|
|
"a single line summary followed by an empty line.")
|
2013-10-19 04:09:25 -03:00
|
|
|
elif len(lines) == 1:
|
|
|
|
# the docstring is only one line right now--the summary line.
|
|
|
|
# add an empty line after the summary line so we have space
|
2013-11-23 19:37:55 -04:00
|
|
|
# between it and the {parameters} we're about to add.
|
2013-10-19 04:09:25 -03:00
|
|
|
lines.append('')
|
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
parameters_marker_count = len(f.docstring.split('{parameters}')) - 1
|
2013-11-23 19:37:55 -04:00
|
|
|
if parameters_marker_count > 1:
|
|
|
|
fail('You may not specify {parameters} more than once in a docstring!')
|
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
# insert signature at front and params after the summary line
|
2013-11-23 19:37:55 -04:00
|
|
|
if not parameters_marker_count:
|
|
|
|
lines.insert(2, '{parameters}')
|
2023-08-08 18:12:35 -03:00
|
|
|
lines.insert(0, '{signature}')
|
2013-11-23 19:37:55 -04:00
|
|
|
|
2023-08-08 18:12:35 -03:00
|
|
|
# finalize docstring
|
|
|
|
params = f.render_parameters
|
|
|
|
parameters = self.format_docstring_parameters(params)
|
|
|
|
signature = self.format_docstring_signature(f, params)
|
2013-10-19 04:09:25 -03:00
|
|
|
docstring = "\n".join(lines)
|
2024-02-15 18:52:20 -04:00
|
|
|
return libclinic.linear_format(docstring,
|
|
|
|
signature=signature,
|
|
|
|
parameters=parameters).rstrip()
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
def check_remaining_star(self, lineno: int | None = None) -> None:
|
|
|
|
assert isinstance(self.function, Function)
|
|
|
|
|
|
|
|
if self.keyword_only:
|
|
|
|
symbol = '*'
|
|
|
|
elif self.deprecated_positional:
|
|
|
|
symbol = '* [from ...]'
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
|
|
|
for p in reversed(self.function.parameters.values()):
|
|
|
|
if self.keyword_only:
|
|
|
|
if p.kind == inspect.Parameter.KEYWORD_ONLY:
|
|
|
|
return
|
|
|
|
elif self.deprecated_positional:
|
|
|
|
if p.deprecated_positional == self.deprecated_positional:
|
|
|
|
return
|
|
|
|
break
|
|
|
|
|
|
|
|
fail(f"Function {self.function.name!r} specifies {symbol!r} "
|
|
|
|
f"without following parameters.", line_number=lineno)
|
|
|
|
|
2023-10-16 11:26:11 -03:00
|
|
|
def check_previous_star(self, lineno: int | None = None) -> None:
|
|
|
|
assert isinstance(self.function, Function)
|
|
|
|
|
|
|
|
for p in self.function.parameters.values():
|
|
|
|
if p.kind == inspect.Parameter.VAR_POSITIONAL:
|
|
|
|
fail(f"Function {self.function.name!r} uses '*' more than once.")
|
|
|
|
|
|
|
|
|
2023-08-07 08:28:08 -03:00
|
|
|
def do_post_block_processing_cleanup(self, lineno: int) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
"""
|
|
|
|
Called when processing the block is done.
|
|
|
|
"""
|
|
|
|
if not self.function:
|
|
|
|
return
|
|
|
|
|
2023-08-19 04:13:35 -03:00
|
|
|
self.check_remaining_star(lineno)
|
2024-02-15 08:22:21 -04:00
|
|
|
try:
|
|
|
|
self.function.docstring = self.format_docstring()
|
|
|
|
except ClinicError as exc:
|
|
|
|
exc.lineno = lineno
|
|
|
|
exc.filename = self.clinic.filename
|
|
|
|
raise
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2014-01-24 10:17:25 -04:00
|
|
|
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
# maps strings to callables.
|
|
|
|
# the callable should return an object
|
|
|
|
# that implements the clinic parser
|
|
|
|
# interface (__init__ and parse).
|
|
|
|
#
|
|
|
|
# example parsers:
|
|
|
|
# "clinic", handles the Clinic DSL
|
|
|
|
# "python", handles running Python code
|
|
|
|
#
|
2023-07-16 21:04:10 -03:00
|
|
|
parsers: dict[str, Callable[[Clinic], Parser]] = {
|
|
|
|
'clinic': DSLParser,
|
|
|
|
'python': PythonParser,
|
|
|
|
}
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-08-01 13:24:23 -03:00
|
|
|
def create_cli() -> argparse.ArgumentParser:
|
2019-06-02 13:58:10 -03:00
|
|
|
cmdline = argparse.ArgumentParser(
|
2023-08-01 13:24:23 -03:00
|
|
|
prog="clinic.py",
|
2019-06-02 13:58:10 -03:00
|
|
|
description="""Preprocessor for CPython C files.
|
|
|
|
|
|
|
|
The purpose of the Argument Clinic is automating all the boilerplate involved
|
|
|
|
with writing argument parsing code for builtins and providing introspection
|
|
|
|
signatures ("docstrings") for CPython builtins.
|
|
|
|
|
2023-12-21 05:28:43 -04:00
|
|
|
For more information see https://devguide.python.org/development-tools/clinic/""")
|
2023-07-26 19:08:43 -03:00
|
|
|
cmdline.add_argument("-f", "--force", action='store_true',
|
|
|
|
help="force output regeneration")
|
|
|
|
cmdline.add_argument("-o", "--output", type=str,
|
|
|
|
help="redirect file output to OUTPUT")
|
|
|
|
cmdline.add_argument("-v", "--verbose", action='store_true',
|
|
|
|
help="enable verbose mode")
|
|
|
|
cmdline.add_argument("--converters", action='store_true',
|
|
|
|
help=("print a list of all supported converters "
|
|
|
|
"and return converters"))
|
2017-05-27 20:40:45 -03:00
|
|
|
cmdline.add_argument("--make", action='store_true',
|
2023-07-26 19:08:43 -03:00
|
|
|
help="walk --srcdir to run over all relevant files")
|
2017-05-27 20:40:45 -03:00
|
|
|
cmdline.add_argument("--srcdir", type=str, default=os.curdir,
|
2023-07-26 19:08:43 -03:00
|
|
|
help="the directory tree to walk in --make mode")
|
2023-08-08 17:50:54 -03:00
|
|
|
cmdline.add_argument("--exclude", type=str, action="append",
|
|
|
|
help=("a file to exclude in --make mode; "
|
|
|
|
"can be given multiple times"))
|
2023-08-25 18:22:08 -03:00
|
|
|
cmdline.add_argument("--limited", dest="limited_capi", action='store_true',
|
|
|
|
help="use the Limited C API")
|
2023-07-26 19:08:43 -03:00
|
|
|
cmdline.add_argument("filename", metavar="FILE", type=str, nargs="*",
|
|
|
|
help="the list of files to process")
|
2023-08-01 13:24:23 -03:00
|
|
|
return cmdline
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2023-08-01 13:24:23 -03:00
|
|
|
|
|
|
|
def run_clinic(parser: argparse.ArgumentParser, ns: argparse.Namespace) -> None:
|
2013-10-19 04:09:25 -03:00
|
|
|
if ns.converters:
|
|
|
|
if ns.filename:
|
2023-08-01 13:24:23 -03:00
|
|
|
parser.error(
|
|
|
|
"can't specify --converters and a filename at the same time"
|
|
|
|
)
|
2023-07-24 16:32:38 -03:00
|
|
|
converters: list[tuple[str, str]] = []
|
|
|
|
return_converters: list[tuple[str, str]] = []
|
2013-10-19 04:09:25 -03:00
|
|
|
ignored = set("""
|
|
|
|
add_c_converter
|
|
|
|
add_c_return_converter
|
|
|
|
add_default_legacy_c_converter
|
|
|
|
add_legacy_c_converter
|
|
|
|
""".strip().split())
|
|
|
|
module = globals()
|
|
|
|
for name in module:
|
|
|
|
for suffix, ids in (
|
|
|
|
("_return_converter", return_converters),
|
|
|
|
("_converter", converters),
|
|
|
|
):
|
|
|
|
if name in ignored:
|
|
|
|
continue
|
|
|
|
if name.endswith(suffix):
|
2023-05-20 08:08:28 -03:00
|
|
|
ids.append((name, name.removesuffix(suffix)))
|
2013-10-19 04:09:25 -03:00
|
|
|
break
|
|
|
|
print()
|
|
|
|
|
|
|
|
print("Legacy converters:")
|
|
|
|
legacy = sorted(legacy_converters)
|
|
|
|
print(' ' + ' '.join(c for c in legacy if c[0].isupper()))
|
|
|
|
print(' ' + ' '.join(c for c in legacy if c[0].islower()))
|
|
|
|
print()
|
|
|
|
|
|
|
|
for title, attribute, ids in (
|
|
|
|
("Converters", 'converter_init', converters),
|
|
|
|
("Return converters", 'return_converter_init', return_converters),
|
|
|
|
):
|
|
|
|
print(title + ":")
|
|
|
|
longest = -1
|
|
|
|
for name, short_name in ids:
|
|
|
|
longest = max(longest, len(short_name))
|
|
|
|
for name, short_name in sorted(ids, key=lambda x: x[1].lower()):
|
|
|
|
cls = module[name]
|
|
|
|
callable = getattr(cls, attribute, None)
|
|
|
|
if not callable:
|
|
|
|
continue
|
|
|
|
signature = inspect.signature(callable)
|
|
|
|
parameters = []
|
|
|
|
for parameter_name, parameter in signature.parameters.items():
|
|
|
|
if parameter.kind == inspect.Parameter.KEYWORD_ONLY:
|
|
|
|
if parameter.default != inspect.Parameter.empty:
|
2023-05-20 17:16:49 -03:00
|
|
|
s = f'{parameter_name}={parameter.default!r}'
|
2013-10-19 04:09:25 -03:00
|
|
|
else:
|
|
|
|
s = parameter_name
|
|
|
|
parameters.append(s)
|
|
|
|
print(' {}({})'.format(short_name, ', '.join(parameters)))
|
|
|
|
print()
|
2014-01-16 15:32:01 -04:00
|
|
|
print("All converters also accept (c_default=None, py_default=None, annotation=None).")
|
|
|
|
print("All return converters also accept (py_default=None).")
|
2023-08-01 13:24:23 -03:00
|
|
|
return
|
2013-10-19 04:09:25 -03:00
|
|
|
|
2013-11-23 18:58:45 -04:00
|
|
|
if ns.make:
|
|
|
|
if ns.output or ns.filename:
|
2023-08-01 13:24:23 -03:00
|
|
|
parser.error("can't use -o or filenames with --make")
|
2017-05-27 20:40:45 -03:00
|
|
|
if not ns.srcdir:
|
2023-08-01 13:24:23 -03:00
|
|
|
parser.error("--srcdir must not be empty with --make")
|
2023-08-08 17:50:54 -03:00
|
|
|
if ns.exclude:
|
|
|
|
excludes = [os.path.join(ns.srcdir, f) for f in ns.exclude]
|
|
|
|
excludes = [os.path.normpath(f) for f in excludes]
|
|
|
|
else:
|
|
|
|
excludes = []
|
2017-05-27 20:40:45 -03:00
|
|
|
for root, dirs, files in os.walk(ns.srcdir):
|
2015-04-13 20:33:41 -03:00
|
|
|
for rcs_dir in ('.svn', '.git', '.hg', 'build', 'externals'):
|
2013-11-23 18:58:45 -04:00
|
|
|
if rcs_dir in dirs:
|
|
|
|
dirs.remove(rcs_dir)
|
|
|
|
for filename in files:
|
2023-06-01 20:31:58 -03:00
|
|
|
# handle .c, .cpp and .h files
|
|
|
|
if not filename.endswith(('.c', '.cpp', '.h')):
|
2013-11-23 18:58:45 -04:00
|
|
|
continue
|
|
|
|
path = os.path.join(root, filename)
|
2023-08-08 17:50:54 -03:00
|
|
|
path = os.path.normpath(path)
|
|
|
|
if path in excludes:
|
|
|
|
continue
|
2014-01-24 10:17:25 -04:00
|
|
|
if ns.verbose:
|
|
|
|
print(path)
|
2023-08-28 15:25:16 -03:00
|
|
|
parse_file(path,
|
|
|
|
verify=not ns.force, limited_capi=ns.limited_capi)
|
2013-11-23 18:58:45 -04:00
|
|
|
return
|
|
|
|
|
2013-10-19 04:09:25 -03:00
|
|
|
if not ns.filename:
|
2023-08-01 13:24:23 -03:00
|
|
|
parser.error("no input files")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
if ns.output and len(ns.filename) > 1:
|
2023-08-01 13:24:23 -03:00
|
|
|
parser.error("can't use -o with multiple filenames")
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
for filename in ns.filename:
|
2014-01-24 10:17:25 -04:00
|
|
|
if ns.verbose:
|
|
|
|
print(filename)
|
2023-08-28 15:25:16 -03:00
|
|
|
parse_file(filename, output=ns.output,
|
|
|
|
verify=not ns.force, limited_capi=ns.limited_capi)
|
2013-10-19 04:09:25 -03:00
|
|
|
|
|
|
|
|
2023-08-01 13:24:23 -03:00
|
|
|
def main(argv: list[str] | None = None) -> NoReturn:
|
|
|
|
parser = create_cli()
|
|
|
|
args = parser.parse_args(argv)
|
2023-08-02 21:00:06 -03:00
|
|
|
try:
|
|
|
|
run_clinic(parser, args)
|
|
|
|
except ClinicError as exc:
|
|
|
|
sys.stderr.write(exc.report())
|
|
|
|
sys.exit(1)
|
|
|
|
else:
|
|
|
|
sys.exit(0)
|
2023-08-01 13:24:23 -03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|