diff --git a/third_party/CityFlow/docs/source/introduction.rst b/third_party/CityFlow/docs/source/introduction.rst index 60f3e39d80a286086e5036cd079d7ae8fd09339a..e88250585a5f4367c4aa13a2d94a10b4bd4a8abc 100644 --- a/third_party/CityFlow/docs/source/introduction.rst +++ b/third_party/CityFlow/docs/source/introduction.rst @@ -1,21 +1,21 @@ -Introduction -============ - -CityFlow is a multi-agent reinforcement learning environment for large scale city traffic scenario. - -Checkout these features! - -- a microscopic traffic simulator which simulates the behavior of each vehicle, providing highest level detail of traffic evolution. -- support flexible definitions for road network and traffic flow -- provides friendly python interface for reinforcement learning -- **Fast!** Elaborately designed data structure and simulation algorithm with multithreading. Capable of simulating city-wide traffic. See the performance comparison with SUMO [#sumo]_. - -.. figure:: https://github.com/cityflow-project/data/raw/master/docs/images/performance.png - :align: center - - Performance comparison between CityFlow with different number of threads (1, 2, 4, 8) and SUMO. From small 1x1 grid roadnet to city-level 30x30 roadnet. Even faster when you need to interact with the simulator through python API. - -See :ref:`start` to get started. - -.. [#paper] `WWW 2019 Demo Paper `_ +Introduction +============ + +CityFlow is a multi-agent reinforcement learning environment for large scale city traffic scenario. + +Checkout these features! + +- a microscopic traffic simulator which simulates the behavior of each vehicle, providing highest level detail of traffic evolution. +- support flexible definitions for road network and traffic flow +- provides friendly python interface for reinforcement learning +- **Fast!** Elaborately designed data structure and simulation algorithm with multithreading. Capable of simulating city-wide traffic. See the performance comparison with SUMO [#sumo]_. + +.. figure:: https://github.com/cityflow-project/data/raw/master/docs/images/performance.png + :align: center + + Performance comparison between CityFlow with different number of threads (1, 2, 4, 8) and SUMO. From small 1x1 grid roadnet to city-level 30x30 roadnet. Even faster when you need to interact with the simulator through python API. + +See :ref:`start` to get started. + +.. [#paper] `WWW 2019 Demo Paper `_ .. [#sumo] `SUMO home page `_ \ No newline at end of file diff --git a/third_party/CityFlow/docs/source/replay.rst b/third_party/CityFlow/docs/source/replay.rst index e6635ea9559a8a5ab6af667f93f2bcf627b3b873..5269a8343e69f283df54725829542c3f36030c29 100644 --- a/third_party/CityFlow/docs/source/replay.rst +++ b/third_party/CityFlow/docs/source/replay.rst @@ -1,69 +1,69 @@ -.. _replay: - -Replay -====== - -Start ------- - -1. enter the ``frontend`` folder and open ``index.html`` in your browser. - -2. choose the roadnet log file (as defined by ``roadnetLogFile`` field in the config file, **not 'roadnetFile'**) and wait for it to be loaded. When it has finished loading, there will be a message shown in the info box. - -3. choose the replay file (as defined by ``replayLogFile`` field in the config file) . - -4. choose the chart data file (optional, see section *Chart* below). - -5. press ``Start`` button to start the replay. - -Control -------- - -- Use the mouse to navigate. Dragging and mouse wheel zooming are supported. - -- Move the slider in Control Box to adjust the replay speed. You can also press ``1`` on keyboard to slow down or ``2`` to speed up. - -- Press ``Pause`` button in Control Box to pause/resume. You can also double-click on the map to pause and resume. - -- Press ``[`` or ``]`` on keyboard to take a step backward or forward. - -- To restart the replay, just press ``Start`` button again. - -- The ``debug`` option enables displaying the ID of vehicles, roads and intersections during a mouse hover. **This will cause a slower replaying**, so we suggest using it only for debugging purposes. - -Chart ------- - -The player supports showing the change of different metrics in a chart simultaneously with the replay process. - -To provide required data, a log file in a format as shown below is needed: - -.. code-block:: - - title - 0.3 0.4 0.1 ...(step1) - 0.5 0.2 0.2 ...(step2) - ...(metric1) ...(metric2) ...(metric3) - -The first line is the title of the chart. - -Each row stands for a time step and each column stands for a specific metric. -For example, to track vehicle numbers of three crossroads respectively, we need three columns and each column stands for the vehicle number of a certain crossroads. - -In one row, numbers are separated by one or more spaces or tabs. - -The numbers in one column will be shown as points connected by one line in the chart. - -.. note:: - Make sure that each row is corresponding with the right time step. - -Notes ------- - -- To get the example replay files, run ``download_replay.py`` under ``frontend`` folder. - -- If you create a new Engine object with same ``replayLogFile``, it will clear the old replay file first - -- Using ``eng.reset()`` won't clear old replays, it will append newly generated replay to the end of ``replayLogFile`` - -- You can change ``replayLogFile`` during runtime using ``set_replay_file``, see :ref:`set-replay-file` +.. _replay: + +Replay +====== + +Start +------ + +1. enter the ``frontend`` folder and open ``index.html`` in your browser. + +2. choose the roadnet log file (as defined by ``roadnetLogFile`` field in the config file, **not 'roadnetFile'**) and wait for it to be loaded. When it has finished loading, there will be a message shown in the info box. + +3. choose the replay file (as defined by ``replayLogFile`` field in the config file) . + +4. choose the chart data file (optional, see section *Chart* below). + +5. press ``Start`` button to start the replay. + +Control +------- + +- Use the mouse to navigate. Dragging and mouse wheel zooming are supported. + +- Move the slider in Control Box to adjust the replay speed. You can also press ``1`` on keyboard to slow down or ``2`` to speed up. + +- Press ``Pause`` button in Control Box to pause/resume. You can also double-click on the map to pause and resume. + +- Press ``[`` or ``]`` on keyboard to take a step backward or forward. + +- To restart the replay, just press ``Start`` button again. + +- The ``debug`` option enables displaying the ID of vehicles, roads and intersections during a mouse hover. **This will cause a slower replaying**, so we suggest using it only for debugging purposes. + +Chart +------ + +The player supports showing the change of different metrics in a chart simultaneously with the replay process. + +To provide required data, a log file in a format as shown below is needed: + +.. code-block:: + + title + 0.3 0.4 0.1 ...(step1) + 0.5 0.2 0.2 ...(step2) + ...(metric1) ...(metric2) ...(metric3) + +The first line is the title of the chart. + +Each row stands for a time step and each column stands for a specific metric. +For example, to track vehicle numbers of three crossroads respectively, we need three columns and each column stands for the vehicle number of a certain crossroads. + +In one row, numbers are separated by one or more spaces or tabs. + +The numbers in one column will be shown as points connected by one line in the chart. + +.. note:: + Make sure that each row is corresponding with the right time step. + +Notes +------ + +- To get the example replay files, run ``download_replay.py`` under ``frontend`` folder. + +- If you create a new Engine object with same ``replayLogFile``, it will clear the old replay file first + +- Using ``eng.reset()`` won't clear old replays, it will append newly generated replay to the end of ``replayLogFile`` + +- You can change ``replayLogFile`` during runtime using ``set_replay_file``, see :ref:`set-replay-file` diff --git a/third_party/CityFlow/docs/source/roadnet.rst b/third_party/CityFlow/docs/source/roadnet.rst index caa88d301c0f645b4214dc6785a0d8c1b4e87128..375b4512a1083c2820383dcf597e2e6c6a78b38c 100644 --- a/third_party/CityFlow/docs/source/roadnet.rst +++ b/third_party/CityFlow/docs/source/roadnet.rst @@ -1,129 +1,129 @@ -.. _roadnet: - -Roadnet File Format -=================== - -Roadnet file defines the roadnet structure. CityFlow's roadnet mainly consists of intersections and roads (see them as nodes and edges of a graph). - -- *Road* represents a directional road from one *intersection* to another *intersection* with road-specific properties. A *road* may contain multiple *lanes*. -- *Intersection* is where roads intersects. An *intersection* contains several *roadlinks*. Each *roadlink* connects two roads of the intersection and can be controlled by traffic signals. -- A *roadlink* may contain several *lanelinks*. Each lanelink represents a specific path from one lane of incoming road to one lane of outgoing road. - -Now let's see a sample roadnet file and we'll explain the meaning of each components. Relax, the definition of field is quite straight forward, if you are familiar with modern road networks. For the following json file, ``[]`` means this field is an array, but we will only show one object for demonstration. - -.. note:: - Runnable sample roadnet files can be found in ``examples`` folder. - -Sample ``roadnet.json`` with explanation. - -.. code-block:: js - - { - "intersections": [ - { - // id of the intersection - "id": "intersection_1_0", - // coordinate of center of intersection - "point": { - "x": 0, - "y": 0 - }, - // width of the intersection - "width": 10, - // roads connected to the intersection - "roads": [ - "road_1", - "road_2" - ], - // roadLinks of the intersection - "roadLinks": [ - { - // 'turn_left', 'turn_right', 'go_straight' - "type": "go_straight", - // id of starting road - "startRoad": "road_1", - // id of ending road - "endRoad": "road_2", - // lanelinks of roadlink - "laneLinks": [ - { - // from startRoad's startLaneIndex lane to endRoad's endLaneIndex lane - "startLaneIndex": 0, - "endLaneIndex": 1, - // points along the laneLink which describe the shape of laneLink - "points": [ - { - "x": -10, - "y": 2 - }, - { - "x": 10, - "y": -2 - } - ] - } - ] - } - ], - // traffic light plan of the intersection - "trafficLight": { - "lightphases": [ - { - // default duration of the phase - "time": 30, - // available roadLinks of current phase, index is the no. of roadlinks defined above. - "availableRoadLinks": [ - 0, - 2 - ] - } - ] - }, - // true if it's a peripheral intersection (if it only connects to one road) - "virtual": false - } - ], - "roads": [ - { - // id of road - "id": "road_1", - // id of start intersection - "startIntersection": "intersection_1", - // id of end intersection - "endIntersection": "intersection_2", - // points along the road which describe the shape of the road - "points": [ - { - "x": -200, - "y": 0 - }, - { - "x": 0, - "y": 0 - } - ], - // property of each lane - "lanes": [ - { - "width": 4, - "maxSpeed": 16.67 - } - ] - } - ] - } - - -.. figure:: https://github.com/cityflow-project/data/raw/master/docs/images/roadnet.jpg - :align: center - - Illustration of a 1x2 grid roadnet. - - -You can convert SUMO roadnet files into CityFlow format using tools/Converter/converter.py - -For example, the following code converts a sumo roadnet file, atlanta.net.xml, to CityFlow format. - -.. code-block:: shell - - python converter.py --sumonet atlanta_sumo.net.xml --cityflownet atlanta_cityflow.json +.. _roadnet: + +Roadnet File Format +=================== + +Roadnet file defines the roadnet structure. CityFlow's roadnet mainly consists of intersections and roads (see them as nodes and edges of a graph). + +- *Road* represents a directional road from one *intersection* to another *intersection* with road-specific properties. A *road* may contain multiple *lanes*. +- *Intersection* is where roads intersects. An *intersection* contains several *roadlinks*. Each *roadlink* connects two roads of the intersection and can be controlled by traffic signals. +- A *roadlink* may contain several *lanelinks*. Each lanelink represents a specific path from one lane of incoming road to one lane of outgoing road. + +Now let's see a sample roadnet file and we'll explain the meaning of each components. Relax, the definition of field is quite straight forward, if you are familiar with modern road networks. For the following json file, ``[]`` means this field is an array, but we will only show one object for demonstration. + +.. note:: + Runnable sample roadnet files can be found in ``examples`` folder. + +Sample ``roadnet.json`` with explanation. + +.. code-block:: js + + { + "intersections": [ + { + // id of the intersection + "id": "intersection_1_0", + // coordinate of center of intersection + "point": { + "x": 0, + "y": 0 + }, + // width of the intersection + "width": 10, + // roads connected to the intersection + "roads": [ + "road_1", + "road_2" + ], + // roadLinks of the intersection + "roadLinks": [ + { + // 'turn_left', 'turn_right', 'go_straight' + "type": "go_straight", + // id of starting road + "startRoad": "road_1", + // id of ending road + "endRoad": "road_2", + // lanelinks of roadlink + "laneLinks": [ + { + // from startRoad's startLaneIndex lane to endRoad's endLaneIndex lane + "startLaneIndex": 0, + "endLaneIndex": 1, + // points along the laneLink which describe the shape of laneLink + "points": [ + { + "x": -10, + "y": 2 + }, + { + "x": 10, + "y": -2 + } + ] + } + ] + } + ], + // traffic light plan of the intersection + "trafficLight": { + "lightphases": [ + { + // default duration of the phase + "time": 30, + // available roadLinks of current phase, index is the no. of roadlinks defined above. + "availableRoadLinks": [ + 0, + 2 + ] + } + ] + }, + // true if it's a peripheral intersection (if it only connects to one road) + "virtual": false + } + ], + "roads": [ + { + // id of road + "id": "road_1", + // id of start intersection + "startIntersection": "intersection_1", + // id of end intersection + "endIntersection": "intersection_2", + // points along the road which describe the shape of the road + "points": [ + { + "x": -200, + "y": 0 + }, + { + "x": 0, + "y": 0 + } + ], + // property of each lane + "lanes": [ + { + "width": 4, + "maxSpeed": 16.67 + } + ] + } + ] + } + + +.. figure:: https://github.com/cityflow-project/data/raw/master/docs/images/roadnet.jpg + :align: center + + Illustration of a 1x2 grid roadnet. + + +You can convert SUMO roadnet files into CityFlow format using tools/Converter/converter.py + +For example, the following code converts a sumo roadnet file, atlanta.net.xml, to CityFlow format. + +.. code-block:: shell + + python converter.py --sumonet atlanta_sumo.net.xml --cityflownet atlanta_cityflow.json diff --git a/third_party/CityFlow/docs/source/start.rst b/third_party/CityFlow/docs/source/start.rst index 0feba4161025ffd646216e8307847bfb16ecc217..306d5a0e314ca1ae7148cf51f4aaeaac02673690 100644 --- a/third_party/CityFlow/docs/source/start.rst +++ b/third_party/CityFlow/docs/source/start.rst @@ -1,229 +1,229 @@ -.. _start: - -Quick Start -=========== - -Installation ------------- - -If you have not installed CityFlow yet, :ref:`install` is a simple guide for installation. - - -Create Engine -------------- - -.. code-block:: python - - import cityflow - eng = cityflow.Engine(config_path, thread_num=1) - - -- ``config_path``: path for config file. -- ``thread_num``: number of threads. - -Arguments In Config File -^^^^^^^^^^^^^^^^^^^^^^^^ -- ``interval``: time of each simulation step (in seconds). An ``interval`` of 0.5 means for each simulation step, the system will move 0.5 seconds forward. For example, if a car is at location 0 with speed 10m/s, after one simulation step, it will move to location 10*0.5=5. -- ``seed``: random seed. -- ``dir``: root directory, all file path will be relative to this directory. -- ``roadnetFile``: path for roadnet file. -- ``flowFile``: path for flow file. -- ``rlTrafficLight``: whether to enable traffic light control through python API. If set to ``false``, default traffic light plan defined in ``roadnetFile`` will be used. -- ``saveReplay``: whether to save simulation for replay. If set to ``true``, ``roadnetLogFile`` and ``replayLogFile`` are required. -- ``roadnetLogFile``: path for roadnet replay file. This is a special roadnet file for replay, not the same as ``roadnetFile``. -- ``replayLogFile``: path for replay. This file contains vehicle positions and traffic light situation of each simulation step. -- ``laneChange``: whether to enable lane changing. The default value is 'false'. - -For format of ``roadnetFile`` and ``flowFile``, please see :ref:`roadnet`, :ref:`flow` - -.. note:: - Runnable sample roadnet and flow files can be found in ``examples`` folder. - -You can generate grid roadnet and flow files using `tools/generate_grid_scenario.py` - -For example, you can generate a 2x3 roadnet with predefined traffic light plan and a corresponding flow file with - -.. code-block:: shell - - python generate_grid_scenario.py 2 3 --roadnetFile roadnet.json --flowFile flow.json --dir . --tlPlan - -Sample Config File -^^^^^^^^^^^^^^^^^^^ - -.. note:: - Runnable sample config files can be found in ``examples`` folder. - -.. code-block:: json - - { - "interval": 1.0, - "seed": 0, - "dir": "data/", - "roadnetFile": "roadnet/testcase_roadnet_3x3.json", - "flowFile": "flow/testcase_flow_3x3.json", - "rlTrafficLight": false, - "saveReplay": true, - "roadnetLogFile": "frontend/web/testcase_roadnet_3x3.json", - "replayLogFile": "frontend/web/testcase_replay_3x3.txt" - } - -Simulation ----------- - -To simulate one step, simply call ``eng.next_step()`` - -.. code-block:: python - - eng.next_step() - -Data Access API ---------------- - -``get_vehicle_count()``: - -- Get number of total running vehicles. -- Return an ``int`` - -``get_vehicles(include_waiting=False)``: - -- Get all vehicle ids -- Include vehicles in lane's waiting buffer if ``include_waiting=True`` -- Return an ``list`` of vehicle ids - -``get_lane_vehicle_count()``: - -- Get number of running vehicles on each lane. -- Return a ``dict`` with lane id as key and corresponding number as value. - -``get_lane_waiting_vehicle_count()``: - -- Get number of waiting vehicles on each lane. Currently, vehicles with speed less than 0.1m/s is considered as waiting. -- Return a ``dict`` with lane id as key and corresponding number as value. - -``get_lane_vehicles()``: - -- Get vehicle ids on each lane. -- Return a ``dict`` with lane id as key and list of vehicle id as value. - -``get_vehicle_info(vehicle_id)``: - -- Return a ``dict`` which contains information of the given vehicle. -- The items include: - - + ``running``: whether the vehicle is running. - + If the vehicle is running: - - * ``speed``: The speed of the vehicle. - * ``distance``: The distance the vehicle has travelled on the current lane or lanelink. - * ``drivable``: The id of the current drivable(lane or lanelink) - * ``road``: The id of the current road if the vehicle is running on a lane. - * ``intersection``: The next intersection if the vehicle is running on a lane. - * ``route``: A string contains ids of following roads in the vehicle's route which are separated by ``' '``. - -- Note that all items are stored as ``str``. - -``get_vehicle_speed()``: - -- Get speed of each vehicle -- Return a ``dict`` with vehicle id as key and corresponding speed as value. - -``get_vehicle_distance()``: - -- Get distance travelled on current lane of each vehicle. -- Return a ``dict`` with vehicle id as key and corresponding distance as value. - -``get_leader(vehicle_id)`` - -- Return the id of the vehicle in front of ``vehicle_id``. -- Return an empty string ``""`` when ``vehicle_id`` does not have a leader - -``get_current_time()``: - -- Get simulation time (in seconds) -- Return a ``double`` - -``get_average_travel_time()``: - -- Get average travel time (in seconds) -- Return a ``double`` - -Control API ------------ - -``set_tl_phase(intersection_id, phase_id)``: - -- Set the phase of traffic light of ``intersection_id`` to ``phase_id``. Only works when ``rlTrafficLight`` is set to ``true``. -- The ``intersection_id`` should be defined in ``roadnetFile`` -- ``phase_id`` is the index of phase in array ``"lightphases"``, defined in ``roadnetFile``. - -``set_vehicle_speed(vehicle_id, speed)``: - -- Set the speed of ``vehicle_id`` to ``speed``. -- The vehicles have to obey fundamental rules to avoid collisions so the real speed might be different from ``speed``. - -``reset(seed=False)``: - -- Reset the simulation (clear all vehicles and set simulation time back to zero) -- Reset random seed if ``seed`` is set to ``True`` -- This does not clear old replays, instead, it appends new replays to ``replayLogFile``. - -``snapshot()``: - -- Take a snapshot of current simulation state -- This will generate an ``Archive`` object which can be loaded later -- You can save an ``Archive`` object to a file using its ``dump`` method. - -``load(archive)``: - -- Load an ``Archive`` object and restore simulation state - -``load_from_file(path)`` - -- Load a snapshot file created by ``dump`` method and restore simulation state. -- The whole process of saving and loading file is like: - - .. code-block:: python - - archive = eng.snapshot() # create an archive object - archive.dump("save.json") # if you want to save the snapshot to a file - - # do something - - eng.load(archive) - # load 'archive' and the simulation will start from the status when 'archive'is created - - # or if you want to load from 'save.json' - eng.load_from_file("save.json") - - -``set_random_seed(seed)``: - -- Set seed of random generator to ``seed`` - -.. _set-replay-file: - - -``set_vehicle_route(vehicle_id, route)``: - -- To change the route of a vehicle during its travelling. -- `route` is a list of road ids (doesn't include the current road) -- Return true if the route is available and can be connected. - - - -Other API ---------- - -``set_replay_file(replay_file)``: - -- ``replay_file`` should be a path related to ``dir`` in config file -- Set ``replayLogFile`` to ``replay_file``, newly generated replays will be output into ``replay_file`` -- This is useful when you want to look at a specific episode for debugging purposes -- This API works only when ``saveReplay`` is ``true`` in config json - -``set_save_replay(open)``: - -- Open or close replay saving -- Set ``open`` to False to stop replay saving -- Set ``open`` to True to start replay saving +.. _start: + +Quick Start +=========== + +Installation +------------ + +If you have not installed CityFlow yet, :ref:`install` is a simple guide for installation. + + +Create Engine +------------- + +.. code-block:: python + + import cityflow + eng = cityflow.Engine(config_path, thread_num=1) + + +- ``config_path``: path for config file. +- ``thread_num``: number of threads. + +Arguments In Config File +^^^^^^^^^^^^^^^^^^^^^^^^ +- ``interval``: time of each simulation step (in seconds). An ``interval`` of 0.5 means for each simulation step, the system will move 0.5 seconds forward. For example, if a car is at location 0 with speed 10m/s, after one simulation step, it will move to location 10*0.5=5. +- ``seed``: random seed. +- ``dir``: root directory, all file path will be relative to this directory. +- ``roadnetFile``: path for roadnet file. +- ``flowFile``: path for flow file. +- ``rlTrafficLight``: whether to enable traffic light control through python API. If set to ``false``, default traffic light plan defined in ``roadnetFile`` will be used. +- ``saveReplay``: whether to save simulation for replay. If set to ``true``, ``roadnetLogFile`` and ``replayLogFile`` are required. +- ``roadnetLogFile``: path for roadnet replay file. This is a special roadnet file for replay, not the same as ``roadnetFile``. +- ``replayLogFile``: path for replay. This file contains vehicle positions and traffic light situation of each simulation step. +- ``laneChange``: whether to enable lane changing. The default value is 'false'. + +For format of ``roadnetFile`` and ``flowFile``, please see :ref:`roadnet`, :ref:`flow` + +.. note:: + Runnable sample roadnet and flow files can be found in ``examples`` folder. + +You can generate grid roadnet and flow files using `tools/generate_grid_scenario.py` + +For example, you can generate a 2x3 roadnet with predefined traffic light plan and a corresponding flow file with + +.. code-block:: shell + + python generate_grid_scenario.py 2 3 --roadnetFile roadnet.json --flowFile flow.json --dir . --tlPlan + +Sample Config File +^^^^^^^^^^^^^^^^^^^ + +.. note:: + Runnable sample config files can be found in ``examples`` folder. + +.. code-block:: json + + { + "interval": 1.0, + "seed": 0, + "dir": "data/", + "roadnetFile": "roadnet/testcase_roadnet_3x3.json", + "flowFile": "flow/testcase_flow_3x3.json", + "rlTrafficLight": false, + "saveReplay": true, + "roadnetLogFile": "frontend/web/testcase_roadnet_3x3.json", + "replayLogFile": "frontend/web/testcase_replay_3x3.txt" + } + +Simulation +---------- + +To simulate one step, simply call ``eng.next_step()`` + +.. code-block:: python + + eng.next_step() + +Data Access API +--------------- + +``get_vehicle_count()``: + +- Get number of total running vehicles. +- Return an ``int`` + +``get_vehicles(include_waiting=False)``: + +- Get all vehicle ids +- Include vehicles in lane's waiting buffer if ``include_waiting=True`` +- Return an ``list`` of vehicle ids + +``get_lane_vehicle_count()``: + +- Get number of running vehicles on each lane. +- Return a ``dict`` with lane id as key and corresponding number as value. + +``get_lane_waiting_vehicle_count()``: + +- Get number of waiting vehicles on each lane. Currently, vehicles with speed less than 0.1m/s is considered as waiting. +- Return a ``dict`` with lane id as key and corresponding number as value. + +``get_lane_vehicles()``: + +- Get vehicle ids on each lane. +- Return a ``dict`` with lane id as key and list of vehicle id as value. + +``get_vehicle_info(vehicle_id)``: + +- Return a ``dict`` which contains information of the given vehicle. +- The items include: + + + ``running``: whether the vehicle is running. + + If the vehicle is running: + + * ``speed``: The speed of the vehicle. + * ``distance``: The distance the vehicle has travelled on the current lane or lanelink. + * ``drivable``: The id of the current drivable(lane or lanelink) + * ``road``: The id of the current road if the vehicle is running on a lane. + * ``intersection``: The next intersection if the vehicle is running on a lane. + * ``route``: A string contains ids of following roads in the vehicle's route which are separated by ``' '``. + +- Note that all items are stored as ``str``. + +``get_vehicle_speed()``: + +- Get speed of each vehicle +- Return a ``dict`` with vehicle id as key and corresponding speed as value. + +``get_vehicle_distance()``: + +- Get distance travelled on current lane of each vehicle. +- Return a ``dict`` with vehicle id as key and corresponding distance as value. + +``get_leader(vehicle_id)`` + +- Return the id of the vehicle in front of ``vehicle_id``. +- Return an empty string ``""`` when ``vehicle_id`` does not have a leader + +``get_current_time()``: + +- Get simulation time (in seconds) +- Return a ``double`` + +``get_average_travel_time()``: + +- Get average travel time (in seconds) +- Return a ``double`` + +Control API +----------- + +``set_tl_phase(intersection_id, phase_id)``: + +- Set the phase of traffic light of ``intersection_id`` to ``phase_id``. Only works when ``rlTrafficLight`` is set to ``true``. +- The ``intersection_id`` should be defined in ``roadnetFile`` +- ``phase_id`` is the index of phase in array ``"lightphases"``, defined in ``roadnetFile``. + +``set_vehicle_speed(vehicle_id, speed)``: + +- Set the speed of ``vehicle_id`` to ``speed``. +- The vehicles have to obey fundamental rules to avoid collisions so the real speed might be different from ``speed``. + +``reset(seed=False)``: + +- Reset the simulation (clear all vehicles and set simulation time back to zero) +- Reset random seed if ``seed`` is set to ``True`` +- This does not clear old replays, instead, it appends new replays to ``replayLogFile``. + +``snapshot()``: + +- Take a snapshot of current simulation state +- This will generate an ``Archive`` object which can be loaded later +- You can save an ``Archive`` object to a file using its ``dump`` method. + +``load(archive)``: + +- Load an ``Archive`` object and restore simulation state + +``load_from_file(path)`` + +- Load a snapshot file created by ``dump`` method and restore simulation state. +- The whole process of saving and loading file is like: + + .. code-block:: python + + archive = eng.snapshot() # create an archive object + archive.dump("save.json") # if you want to save the snapshot to a file + + # do something + + eng.load(archive) + # load 'archive' and the simulation will start from the status when 'archive'is created + + # or if you want to load from 'save.json' + eng.load_from_file("save.json") + + +``set_random_seed(seed)``: + +- Set seed of random generator to ``seed`` + +.. _set-replay-file: + + +``set_vehicle_route(vehicle_id, route)``: + +- To change the route of a vehicle during its travelling. +- `route` is a list of road ids (doesn't include the current road) +- Return true if the route is available and can be connected. + + + +Other API +--------- + +``set_replay_file(replay_file)``: + +- ``replay_file`` should be a path related to ``dir`` in config file +- Set ``replayLogFile`` to ``replay_file``, newly generated replays will be output into ``replay_file`` +- This is useful when you want to look at a specific episode for debugging purposes +- This API works only when ``saveReplay`` is ``true`` in config json + +``set_save_replay(open)``: + +- Open or close replay saving +- Set ``open`` to False to stop replay saving +- Set ``open`` to True to start replay saving - This API works only when ``saveReplay`` is ``true`` in config json \ No newline at end of file diff --git a/third_party/CityFlow/extern/milo/dtoa_milo.h b/third_party/CityFlow/extern/milo/dtoa_milo.h index 46cb0e176cd0ddac6f6bfa2e53fd766657af72a5..4d2f864ecb4a1ea36dbcf1853f8ab402ad966d5e 100644 --- a/third_party/CityFlow/extern/milo/dtoa_milo.h +++ b/third_party/CityFlow/extern/milo/dtoa_milo.h @@ -1,396 +1,396 @@ -#pragma once -#include -#include -#include -#include - -#define UINT64_C2(h, l) ((static_cast(h) << 32) | static_cast(l)) - -struct DiyFp { - DiyFp() {} - - DiyFp(uint64_t f, int e) : f(f), e(e) {} - - DiyFp(double d) { - union { - double d; - uint64_t u64; - } u = { d }; - - int biased_e = (u.u64 & kDpExponentMask) >> kDpSignificandSize; - uint64_t significand = (u.u64 & kDpSignificandMask); - if (biased_e != 0) { - f = significand + kDpHiddenBit; - e = biased_e - kDpExponentBias; - } - else { - f = significand; - e = kDpMinExponent + 1; - } - } - - DiyFp operator-(const DiyFp& rhs) const { - assert(e == rhs.e); - assert(f >= rhs.f); - return DiyFp(f - rhs.f, e); - } - - DiyFp operator*(const DiyFp& rhs) const { -#if defined(_MSC_VER) && defined(_M_AMD64) - uint64_t h; - uint64_t l = _umul128(f, rhs.f, &h); - if (l & (uint64_t(1) << 63)) // rounding - h++; - return DiyFp(h, e + rhs.e + 64); -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) - unsigned __int128 p = static_cast(f) * static_cast(rhs.f); - uint64_t h = p >> 64; - uint64_t l = static_cast(p); - if (l & (uint64_t(1) << 63)) // rounding - h++; - return DiyFp(h, e + rhs.e + 64); -#else - const uint64_t M32 = 0xFFFFFFFF; - const uint64_t a = f >> 32; - const uint64_t b = f & M32; - const uint64_t c = rhs.f >> 32; - const uint64_t d = rhs.f & M32; - const uint64_t ac = a * c; - const uint64_t bc = b * c; - const uint64_t ad = a * d; - const uint64_t bd = b * d; - uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); - tmp += 1U << 31; /// mult_round - return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); -#endif - } - - DiyFp Normalize() const { -#if defined(_MSC_VER) && defined(_M_AMD64) - unsigned long index; - _BitScanReverse64(&index, f); - return DiyFp(f << (63 - index), e - (63 - index)); -#elif defined(__GNUC__) - int s = __builtin_clzll(f); - return DiyFp(f << s, e - s); -#else - DiyFp res = *this; - while (!(res.f & kDpHiddenBit)) { - res.f <<= 1; - res.e--; - } - res.f <<= (kDiySignificandSize - kDpSignificandSize - 1); - res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 1); - return res; -#endif - } - - DiyFp NormalizeBoundary() const { -#if defined(_MSC_VER) && defined(_M_AMD64) - unsigned long index; - _BitScanReverse64(&index, f); - return DiyFp (f << (63 - index), e - (63 - index)); -#else - DiyFp res = *this; - while (!(res.f & (kDpHiddenBit << 1))) { - res.f <<= 1; - res.e--; - } - res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); - res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); - return res; -#endif - } - - void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { - DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); - DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); - mi.f <<= mi.e - pl.e; - mi.e = pl.e; - *plus = pl; - *minus = mi; - } - - static const int kDiySignificandSize = 64; - static const int kDpSignificandSize = 52; - static const int kDpExponentBias = 0x3FF + kDpSignificandSize; - static const int kDpMinExponent = -kDpExponentBias; - static const uint64_t kDpExponentMask = UINT64_C2(0x7FF00000, 0x00000000); - static const uint64_t kDpSignificandMask = UINT64_C2(0x000FFFFF, 0xFFFFFFFF); - static const uint64_t kDpHiddenBit = UINT64_C2(0x00100000, 0x00000000); - - uint64_t f; - int e; -}; - -inline DiyFp GetCachedPower(int e, int* K) { - // 10^-348, 10^-340, ..., 10^340 - static const uint64_t kCachedPowers_F[] = { - UINT64_C2(0xfa8fd5a0, 0x081c0288), UINT64_C2(0xbaaee17f, 0xa23ebf76), - UINT64_C2(0x8b16fb20, 0x3055ac76), UINT64_C2(0xcf42894a, 0x5dce35ea), - UINT64_C2(0x9a6bb0aa, 0x55653b2d), UINT64_C2(0xe61acf03, 0x3d1a45df), - UINT64_C2(0xab70fe17, 0xc79ac6ca), UINT64_C2(0xff77b1fc, 0xbebcdc4f), - UINT64_C2(0xbe5691ef, 0x416bd60c), UINT64_C2(0x8dd01fad, 0x907ffc3c), - UINT64_C2(0xd3515c28, 0x31559a83), UINT64_C2(0x9d71ac8f, 0xada6c9b5), - UINT64_C2(0xea9c2277, 0x23ee8bcb), UINT64_C2(0xaecc4991, 0x4078536d), - UINT64_C2(0x823c1279, 0x5db6ce57), UINT64_C2(0xc2109436, 0x4dfb5637), - UINT64_C2(0x9096ea6f, 0x3848984f), UINT64_C2(0xd77485cb, 0x25823ac7), - UINT64_C2(0xa086cfcd, 0x97bf97f4), UINT64_C2(0xef340a98, 0x172aace5), - UINT64_C2(0xb23867fb, 0x2a35b28e), UINT64_C2(0x84c8d4df, 0xd2c63f3b), - UINT64_C2(0xc5dd4427, 0x1ad3cdba), UINT64_C2(0x936b9fce, 0xbb25c996), - UINT64_C2(0xdbac6c24, 0x7d62a584), UINT64_C2(0xa3ab6658, 0x0d5fdaf6), - UINT64_C2(0xf3e2f893, 0xdec3f126), UINT64_C2(0xb5b5ada8, 0xaaff80b8), - UINT64_C2(0x87625f05, 0x6c7c4a8b), UINT64_C2(0xc9bcff60, 0x34c13053), - UINT64_C2(0x964e858c, 0x91ba2655), UINT64_C2(0xdff97724, 0x70297ebd), - UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), UINT64_C2(0xf8a95fcf, 0x88747d94), - UINT64_C2(0xb9447093, 0x8fa89bcf), UINT64_C2(0x8a08f0f8, 0xbf0f156b), - UINT64_C2(0xcdb02555, 0x653131b6), UINT64_C2(0x993fe2c6, 0xd07b7fac), - UINT64_C2(0xe45c10c4, 0x2a2b3b06), UINT64_C2(0xaa242499, 0x697392d3), - UINT64_C2(0xfd87b5f2, 0x8300ca0e), UINT64_C2(0xbce50864, 0x92111aeb), - UINT64_C2(0x8cbccc09, 0x6f5088cc), UINT64_C2(0xd1b71758, 0xe219652c), - UINT64_C2(0x9c400000, 0x00000000), UINT64_C2(0xe8d4a510, 0x00000000), - UINT64_C2(0xad78ebc5, 0xac620000), UINT64_C2(0x813f3978, 0xf8940984), - UINT64_C2(0xc097ce7b, 0xc90715b3), UINT64_C2(0x8f7e32ce, 0x7bea5c70), - UINT64_C2(0xd5d238a4, 0xabe98068), UINT64_C2(0x9f4f2726, 0x179a2245), - UINT64_C2(0xed63a231, 0xd4c4fb27), UINT64_C2(0xb0de6538, 0x8cc8ada8), - UINT64_C2(0x83c7088e, 0x1aab65db), UINT64_C2(0xc45d1df9, 0x42711d9a), - UINT64_C2(0x924d692c, 0xa61be758), UINT64_C2(0xda01ee64, 0x1a708dea), - UINT64_C2(0xa26da399, 0x9aef774a), UINT64_C2(0xf209787b, 0xb47d6b85), - UINT64_C2(0xb454e4a1, 0x79dd1877), UINT64_C2(0x865b8692, 0x5b9bc5c2), - UINT64_C2(0xc83553c5, 0xc8965d3d), UINT64_C2(0x952ab45c, 0xfa97a0b3), - UINT64_C2(0xde469fbd, 0x99a05fe3), UINT64_C2(0xa59bc234, 0xdb398c25), - UINT64_C2(0xf6c69a72, 0xa3989f5c), UINT64_C2(0xb7dcbf53, 0x54e9bece), - UINT64_C2(0x88fcf317, 0xf22241e2), UINT64_C2(0xcc20ce9b, 0xd35c78a5), - UINT64_C2(0x98165af3, 0x7b2153df), UINT64_C2(0xe2a0b5dc, 0x971f303a), - UINT64_C2(0xa8d9d153, 0x5ce3b396), UINT64_C2(0xfb9b7cd9, 0xa4a7443c), - UINT64_C2(0xbb764c4c, 0xa7a44410), UINT64_C2(0x8bab8eef, 0xb6409c1a), - UINT64_C2(0xd01fef10, 0xa657842c), UINT64_C2(0x9b10a4e5, 0xe9913129), - UINT64_C2(0xe7109bfb, 0xa19c0c9d), UINT64_C2(0xac2820d9, 0x623bf429), - UINT64_C2(0x80444b5e, 0x7aa7cf85), UINT64_C2(0xbf21e440, 0x03acdd2d), - UINT64_C2(0x8e679c2f, 0x5e44ff8f), UINT64_C2(0xd433179d, 0x9c8cb841), - UINT64_C2(0x9e19db92, 0xb4e31ba9), UINT64_C2(0xeb96bf6e, 0xbadf77d9), - UINT64_C2(0xaf87023b, 0x9bf0ee6b) - }; - static const int16_t kCachedPowers_E[] = { - -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, - -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, - -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, - -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, - -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, - 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, - 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, - 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, - 907, 933, 960, 986, 1013, 1039, 1066 - }; - - //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; - double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive - int k = static_cast(dk); - if (k != dk) - k++; - - unsigned index = static_cast((k >> 3) + 1); - *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table - - assert(index < sizeof(kCachedPowers_F) / sizeof(kCachedPowers_F[0])); - return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); -} - -inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { - while (rest < wp_w && delta - rest >= ten_kappa && - (rest + ten_kappa < wp_w || /// closer - wp_w - rest > rest + ten_kappa - wp_w)) { - buffer[len - 1]--; - rest += ten_kappa; - } -} - -inline unsigned CountDecimalDigit32(uint32_t n) { - // Simple pure C++ implementation was faster than __builtin_clz version in this situation. - if (n < 10) return 1; - if (n < 100) return 2; - if (n < 1000) return 3; - if (n < 10000) return 4; - if (n < 100000) return 5; - if (n < 1000000) return 6; - if (n < 10000000) return 7; - if (n < 100000000) return 8; - if (n < 1000000000) return 9; - return 10; -} - -inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { - static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; - const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); - const DiyFp wp_w = Mp - W; - uint32_t p1 = static_cast(Mp.f >> -one.e); - uint64_t p2 = Mp.f & (one.f - 1); - int kappa = static_cast(CountDecimalDigit32(p1)); - *len = 0; - - while (kappa > 0) { - uint32_t d; - switch (kappa) { - case 10: d = p1 / 1000000000; p1 %= 1000000000; break; - case 9: d = p1 / 100000000; p1 %= 100000000; break; - case 8: d = p1 / 10000000; p1 %= 10000000; break; - case 7: d = p1 / 1000000; p1 %= 1000000; break; - case 6: d = p1 / 100000; p1 %= 100000; break; - case 5: d = p1 / 10000; p1 %= 10000; break; - case 4: d = p1 / 1000; p1 %= 1000; break; - case 3: d = p1 / 100; p1 %= 100; break; - case 2: d = p1 / 10; p1 %= 10; break; - case 1: d = p1; p1 = 0; break; - default: -#if defined(_MSC_VER) - __assume(0); -#elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) - __builtin_unreachable(); -#else - d = 0; -#endif - } - if (d || *len) - buffer[(*len)++] = '0' + static_cast(d); - kappa--; - uint64_t tmp = (static_cast(p1) << -one.e) + p2; - if (tmp <= delta) { - *K += kappa; - GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); - return; - } - } - - // kappa = 0 - for (;;) { - p2 *= 10; - delta *= 10; - char d = static_cast(p2 >> -one.e); - if (d || *len) - buffer[(*len)++] = '0' + d; - p2 &= one.f - 1; - kappa--; - if (p2 < delta) { - *K += kappa; - GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * kPow10[-kappa]); - return; - } - } -} - -inline void Grisu2(double value, char* buffer, int* length, int* K) { - const DiyFp v(value); - DiyFp w_m, w_p; - v.NormalizedBoundaries(&w_m, &w_p); - - const DiyFp c_mk = GetCachedPower(w_p.e, K); - const DiyFp W = v.Normalize() * c_mk; - DiyFp Wp = w_p * c_mk; - DiyFp Wm = w_m * c_mk; - Wm.f++; - Wp.f--; - DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); -} - -inline const char* GetDigitsLut() { - static const char cDigitsLut[200] = { - '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', - '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', - '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', - '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', - '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', - '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', - '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', - '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', - '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', - '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9' - }; - return cDigitsLut; -} - -inline void WriteExponent(int K, char* buffer) { - if (K < 0) { - *buffer++ = '-'; - K = -K; - } - - if (K >= 100) { - *buffer++ = '0' + static_cast(K / 100); - K %= 100; - const char* d = GetDigitsLut() + K * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - else if (K >= 10) { - const char* d = GetDigitsLut() + K * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - else - *buffer++ = '0' + static_cast(K); - - *buffer = '\0'; -} - -inline void Prettify(char* buffer, int length, int k) { - const int kk = length + k; // 10^(kk-1) <= v < 10^kk - - if (length <= kk && kk <= 21) { - // 1234e7 -> 12340000000 - for (int i = length; i < kk; i++) - buffer[i] = '0'; - buffer[kk] = '.'; - buffer[kk + 1] = '0'; - buffer[kk + 2] = '\0'; - } - else if (0 < kk && kk <= 21) { - // 1234e-2 -> 12.34 - memmove(&buffer[kk + 1], &buffer[kk], length - kk); - buffer[kk] = '.'; - buffer[length + 1] = '\0'; - } - else if (-6 < kk && kk <= 0) { - // 1234e-6 -> 0.001234 - const int offset = 2 - kk; - memmove(&buffer[offset], &buffer[0], length); - buffer[0] = '0'; - buffer[1] = '.'; - for (int i = 2; i < offset; i++) - buffer[i] = '0'; - buffer[length + offset] = '\0'; - } - else if (length == 1) { - // 1e30 - buffer[1] = 'e'; - WriteExponent(kk - 1, &buffer[2]); - } - else { - // 1234e30 -> 1.234e33 - memmove(&buffer[2], &buffer[1], length - 1); - buffer[1] = '.'; - buffer[length + 1] = 'e'; - WriteExponent(kk - 1, &buffer[0 + length + 2]); - } -} - -inline void dtoa_milo(double value, char* buffer) { - // Not handling NaN and inf - assert(!std::isnan(value)); - assert(!std::isinf(value)); - - if (value == 0) { - buffer[0] = '0'; - buffer[1] = '.'; - buffer[2] = '0'; - buffer[3] = '\0'; - } - else { - if (value < 0) { - *buffer++ = '-'; - value = -value; - } - int length, K; - Grisu2(value, buffer, &length, &K); - Prettify(buffer, length, K); - } +#pragma once +#include +#include +#include +#include + +#define UINT64_C2(h, l) ((static_cast(h) << 32) | static_cast(l)) + +struct DiyFp { + DiyFp() {} + + DiyFp(uint64_t f, int e) : f(f), e(e) {} + + DiyFp(double d) { + union { + double d; + uint64_t u64; + } u = { d }; + + int biased_e = (u.u64 & kDpExponentMask) >> kDpSignificandSize; + uint64_t significand = (u.u64 & kDpSignificandMask); + if (biased_e != 0) { + f = significand + kDpHiddenBit; + e = biased_e - kDpExponentBias; + } + else { + f = significand; + e = kDpMinExponent + 1; + } + } + + DiyFp operator-(const DiyFp& rhs) const { + assert(e == rhs.e); + assert(f >= rhs.f); + return DiyFp(f - rhs.f, e); + } + + DiyFp operator*(const DiyFp& rhs) const { +#if defined(_MSC_VER) && defined(_M_AMD64) + uint64_t h; + uint64_t l = _umul128(f, rhs.f, &h); + if (l & (uint64_t(1) << 63)) // rounding + h++; + return DiyFp(h, e + rhs.e + 64); +#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) + unsigned __int128 p = static_cast(f) * static_cast(rhs.f); + uint64_t h = p >> 64; + uint64_t l = static_cast(p); + if (l & (uint64_t(1) << 63)) // rounding + h++; + return DiyFp(h, e + rhs.e + 64); +#else + const uint64_t M32 = 0xFFFFFFFF; + const uint64_t a = f >> 32; + const uint64_t b = f & M32; + const uint64_t c = rhs.f >> 32; + const uint64_t d = rhs.f & M32; + const uint64_t ac = a * c; + const uint64_t bc = b * c; + const uint64_t ad = a * d; + const uint64_t bd = b * d; + uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); + tmp += 1U << 31; /// mult_round + return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); +#endif + } + + DiyFp Normalize() const { +#if defined(_MSC_VER) && defined(_M_AMD64) + unsigned long index; + _BitScanReverse64(&index, f); + return DiyFp(f << (63 - index), e - (63 - index)); +#elif defined(__GNUC__) + int s = __builtin_clzll(f); + return DiyFp(f << s, e - s); +#else + DiyFp res = *this; + while (!(res.f & kDpHiddenBit)) { + res.f <<= 1; + res.e--; + } + res.f <<= (kDiySignificandSize - kDpSignificandSize - 1); + res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 1); + return res; +#endif + } + + DiyFp NormalizeBoundary() const { +#if defined(_MSC_VER) && defined(_M_AMD64) + unsigned long index; + _BitScanReverse64(&index, f); + return DiyFp (f << (63 - index), e - (63 - index)); +#else + DiyFp res = *this; + while (!(res.f & (kDpHiddenBit << 1))) { + res.f <<= 1; + res.e--; + } + res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); + res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); + return res; +#endif + } + + void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { + DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); + DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); + mi.f <<= mi.e - pl.e; + mi.e = pl.e; + *plus = pl; + *minus = mi; + } + + static const int kDiySignificandSize = 64; + static const int kDpSignificandSize = 52; + static const int kDpExponentBias = 0x3FF + kDpSignificandSize; + static const int kDpMinExponent = -kDpExponentBias; + static const uint64_t kDpExponentMask = UINT64_C2(0x7FF00000, 0x00000000); + static const uint64_t kDpSignificandMask = UINT64_C2(0x000FFFFF, 0xFFFFFFFF); + static const uint64_t kDpHiddenBit = UINT64_C2(0x00100000, 0x00000000); + + uint64_t f; + int e; +}; + +inline DiyFp GetCachedPower(int e, int* K) { + // 10^-348, 10^-340, ..., 10^340 + static const uint64_t kCachedPowers_F[] = { + UINT64_C2(0xfa8fd5a0, 0x081c0288), UINT64_C2(0xbaaee17f, 0xa23ebf76), + UINT64_C2(0x8b16fb20, 0x3055ac76), UINT64_C2(0xcf42894a, 0x5dce35ea), + UINT64_C2(0x9a6bb0aa, 0x55653b2d), UINT64_C2(0xe61acf03, 0x3d1a45df), + UINT64_C2(0xab70fe17, 0xc79ac6ca), UINT64_C2(0xff77b1fc, 0xbebcdc4f), + UINT64_C2(0xbe5691ef, 0x416bd60c), UINT64_C2(0x8dd01fad, 0x907ffc3c), + UINT64_C2(0xd3515c28, 0x31559a83), UINT64_C2(0x9d71ac8f, 0xada6c9b5), + UINT64_C2(0xea9c2277, 0x23ee8bcb), UINT64_C2(0xaecc4991, 0x4078536d), + UINT64_C2(0x823c1279, 0x5db6ce57), UINT64_C2(0xc2109436, 0x4dfb5637), + UINT64_C2(0x9096ea6f, 0x3848984f), UINT64_C2(0xd77485cb, 0x25823ac7), + UINT64_C2(0xa086cfcd, 0x97bf97f4), UINT64_C2(0xef340a98, 0x172aace5), + UINT64_C2(0xb23867fb, 0x2a35b28e), UINT64_C2(0x84c8d4df, 0xd2c63f3b), + UINT64_C2(0xc5dd4427, 0x1ad3cdba), UINT64_C2(0x936b9fce, 0xbb25c996), + UINT64_C2(0xdbac6c24, 0x7d62a584), UINT64_C2(0xa3ab6658, 0x0d5fdaf6), + UINT64_C2(0xf3e2f893, 0xdec3f126), UINT64_C2(0xb5b5ada8, 0xaaff80b8), + UINT64_C2(0x87625f05, 0x6c7c4a8b), UINT64_C2(0xc9bcff60, 0x34c13053), + UINT64_C2(0x964e858c, 0x91ba2655), UINT64_C2(0xdff97724, 0x70297ebd), + UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), UINT64_C2(0xf8a95fcf, 0x88747d94), + UINT64_C2(0xb9447093, 0x8fa89bcf), UINT64_C2(0x8a08f0f8, 0xbf0f156b), + UINT64_C2(0xcdb02555, 0x653131b6), UINT64_C2(0x993fe2c6, 0xd07b7fac), + UINT64_C2(0xe45c10c4, 0x2a2b3b06), UINT64_C2(0xaa242499, 0x697392d3), + UINT64_C2(0xfd87b5f2, 0x8300ca0e), UINT64_C2(0xbce50864, 0x92111aeb), + UINT64_C2(0x8cbccc09, 0x6f5088cc), UINT64_C2(0xd1b71758, 0xe219652c), + UINT64_C2(0x9c400000, 0x00000000), UINT64_C2(0xe8d4a510, 0x00000000), + UINT64_C2(0xad78ebc5, 0xac620000), UINT64_C2(0x813f3978, 0xf8940984), + UINT64_C2(0xc097ce7b, 0xc90715b3), UINT64_C2(0x8f7e32ce, 0x7bea5c70), + UINT64_C2(0xd5d238a4, 0xabe98068), UINT64_C2(0x9f4f2726, 0x179a2245), + UINT64_C2(0xed63a231, 0xd4c4fb27), UINT64_C2(0xb0de6538, 0x8cc8ada8), + UINT64_C2(0x83c7088e, 0x1aab65db), UINT64_C2(0xc45d1df9, 0x42711d9a), + UINT64_C2(0x924d692c, 0xa61be758), UINT64_C2(0xda01ee64, 0x1a708dea), + UINT64_C2(0xa26da399, 0x9aef774a), UINT64_C2(0xf209787b, 0xb47d6b85), + UINT64_C2(0xb454e4a1, 0x79dd1877), UINT64_C2(0x865b8692, 0x5b9bc5c2), + UINT64_C2(0xc83553c5, 0xc8965d3d), UINT64_C2(0x952ab45c, 0xfa97a0b3), + UINT64_C2(0xde469fbd, 0x99a05fe3), UINT64_C2(0xa59bc234, 0xdb398c25), + UINT64_C2(0xf6c69a72, 0xa3989f5c), UINT64_C2(0xb7dcbf53, 0x54e9bece), + UINT64_C2(0x88fcf317, 0xf22241e2), UINT64_C2(0xcc20ce9b, 0xd35c78a5), + UINT64_C2(0x98165af3, 0x7b2153df), UINT64_C2(0xe2a0b5dc, 0x971f303a), + UINT64_C2(0xa8d9d153, 0x5ce3b396), UINT64_C2(0xfb9b7cd9, 0xa4a7443c), + UINT64_C2(0xbb764c4c, 0xa7a44410), UINT64_C2(0x8bab8eef, 0xb6409c1a), + UINT64_C2(0xd01fef10, 0xa657842c), UINT64_C2(0x9b10a4e5, 0xe9913129), + UINT64_C2(0xe7109bfb, 0xa19c0c9d), UINT64_C2(0xac2820d9, 0x623bf429), + UINT64_C2(0x80444b5e, 0x7aa7cf85), UINT64_C2(0xbf21e440, 0x03acdd2d), + UINT64_C2(0x8e679c2f, 0x5e44ff8f), UINT64_C2(0xd433179d, 0x9c8cb841), + UINT64_C2(0x9e19db92, 0xb4e31ba9), UINT64_C2(0xeb96bf6e, 0xbadf77d9), + UINT64_C2(0xaf87023b, 0x9bf0ee6b) + }; + static const int16_t kCachedPowers_E[] = { + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, + -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, + -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, + -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, + -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, + 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, + 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, + 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, + 907, 933, 960, 986, 1013, 1039, 1066 + }; + + //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; + double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive + int k = static_cast(dk); + if (k != dk) + k++; + + unsigned index = static_cast((k >> 3) + 1); + *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table + + assert(index < sizeof(kCachedPowers_F) / sizeof(kCachedPowers_F[0])); + return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); +} + +inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { + while (rest < wp_w && delta - rest >= ten_kappa && + (rest + ten_kappa < wp_w || /// closer + wp_w - rest > rest + ten_kappa - wp_w)) { + buffer[len - 1]--; + rest += ten_kappa; + } +} + +inline unsigned CountDecimalDigit32(uint32_t n) { + // Simple pure C++ implementation was faster than __builtin_clz version in this situation. + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; + if (n < 1000000000) return 9; + return 10; +} + +inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { + static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); + const DiyFp wp_w = Mp - W; + uint32_t p1 = static_cast(Mp.f >> -one.e); + uint64_t p2 = Mp.f & (one.f - 1); + int kappa = static_cast(CountDecimalDigit32(p1)); + *len = 0; + + while (kappa > 0) { + uint32_t d; + switch (kappa) { + case 10: d = p1 / 1000000000; p1 %= 1000000000; break; + case 9: d = p1 / 100000000; p1 %= 100000000; break; + case 8: d = p1 / 10000000; p1 %= 10000000; break; + case 7: d = p1 / 1000000; p1 %= 1000000; break; + case 6: d = p1 / 100000; p1 %= 100000; break; + case 5: d = p1 / 10000; p1 %= 10000; break; + case 4: d = p1 / 1000; p1 %= 1000; break; + case 3: d = p1 / 100; p1 %= 100; break; + case 2: d = p1 / 10; p1 %= 10; break; + case 1: d = p1; p1 = 0; break; + default: +#if defined(_MSC_VER) + __assume(0); +#elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) + __builtin_unreachable(); +#else + d = 0; +#endif + } + if (d || *len) + buffer[(*len)++] = '0' + static_cast(d); + kappa--; + uint64_t tmp = (static_cast(p1) << -one.e) + p2; + if (tmp <= delta) { + *K += kappa; + GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); + return; + } + } + + // kappa = 0 + for (;;) { + p2 *= 10; + delta *= 10; + char d = static_cast(p2 >> -one.e); + if (d || *len) + buffer[(*len)++] = '0' + d; + p2 &= one.f - 1; + kappa--; + if (p2 < delta) { + *K += kappa; + GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * kPow10[-kappa]); + return; + } + } +} + +inline void Grisu2(double value, char* buffer, int* length, int* K) { + const DiyFp v(value); + DiyFp w_m, w_p; + v.NormalizedBoundaries(&w_m, &w_p); + + const DiyFp c_mk = GetCachedPower(w_p.e, K); + const DiyFp W = v.Normalize() * c_mk; + DiyFp Wp = w_p * c_mk; + DiyFp Wm = w_m * c_mk; + Wm.f++; + Wp.f--; + DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); +} + +inline const char* GetDigitsLut() { + static const char cDigitsLut[200] = { + '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', + '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', + '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', + '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', + '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', + '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', + '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', + '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', + '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', + '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9' + }; + return cDigitsLut; +} + +inline void WriteExponent(int K, char* buffer) { + if (K < 0) { + *buffer++ = '-'; + K = -K; + } + + if (K >= 100) { + *buffer++ = '0' + static_cast(K / 100); + K %= 100; + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else if (K >= 10) { + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else + *buffer++ = '0' + static_cast(K); + + *buffer = '\0'; +} + +inline void Prettify(char* buffer, int length, int k) { + const int kk = length + k; // 10^(kk-1) <= v < 10^kk + + if (length <= kk && kk <= 21) { + // 1234e7 -> 12340000000 + for (int i = length; i < kk; i++) + buffer[i] = '0'; + buffer[kk] = '.'; + buffer[kk + 1] = '0'; + buffer[kk + 2] = '\0'; + } + else if (0 < kk && kk <= 21) { + // 1234e-2 -> 12.34 + memmove(&buffer[kk + 1], &buffer[kk], length - kk); + buffer[kk] = '.'; + buffer[length + 1] = '\0'; + } + else if (-6 < kk && kk <= 0) { + // 1234e-6 -> 0.001234 + const int offset = 2 - kk; + memmove(&buffer[offset], &buffer[0], length); + buffer[0] = '0'; + buffer[1] = '.'; + for (int i = 2; i < offset; i++) + buffer[i] = '0'; + buffer[length + offset] = '\0'; + } + else if (length == 1) { + // 1e30 + buffer[1] = 'e'; + WriteExponent(kk - 1, &buffer[2]); + } + else { + // 1234e30 -> 1.234e33 + memmove(&buffer[2], &buffer[1], length - 1); + buffer[1] = '.'; + buffer[length + 1] = 'e'; + WriteExponent(kk - 1, &buffer[0 + length + 2]); + } +} + +inline void dtoa_milo(double value, char* buffer) { + // Not handling NaN and inf + assert(!std::isnan(value)); + assert(!std::isinf(value)); + + if (value == 0) { + buffer[0] = '0'; + buffer[1] = '.'; + buffer[2] = '0'; + buffer[3] = '\0'; + } + else { + if (value < 0) { + *buffer++ = '-'; + value = -value; + } + int length, K; + Grisu2(value, buffer, &length, &K); + Prettify(buffer, length, K); + } } \ No newline at end of file diff --git a/third_party/CityFlow/extern/pybind11/.appveyor.yml b/third_party/CityFlow/extern/pybind11/.appveyor.yml index 360760ac8db71a68cd2f874723e1e2bbb80545fb..3a1c14298c35795d3c0e6df88019dd12b7f3a19c 100644 --- a/third_party/CityFlow/extern/pybind11/.appveyor.yml +++ b/third_party/CityFlow/extern/pybind11/.appveyor.yml @@ -1,35 +1,35 @@ -version: 1.0.{build} -image: -- Visual Studio 2017 -test: off -skip_branch_with_pr: true -build: - parallel: true -platform: -- x86 -environment: - matrix: - - PYTHON: 36 - CONFIG: Debug -install: -- ps: | - $env:CMAKE_GENERATOR = "Visual Studio 15 2017" - if ($env:PLATFORM -eq "x64") { $env:PYTHON = "$env:PYTHON-x64" } - $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts\;$env:PATH" - python -W ignore -m pip install --upgrade pip wheel - python -W ignore -m pip install pytest numpy --no-warn-script-location pytest-timeout -- ps: | - Start-FileDownload 'https://gitlab.com/libeigen/eigen/-/archive/3.3.7/eigen-3.3.7.zip' - 7z x eigen-3.3.7.zip -y > $null - $env:CMAKE_INCLUDE_PATH = "eigen-3.3.7;$env:CMAKE_INCLUDE_PATH" -build_script: -- cmake -G "%CMAKE_GENERATOR%" -A "%CMAKE_ARCH%" - -DCMAKE_CXX_STANDARD=14 - -DPYBIND11_WERROR=ON - -DDOWNLOAD_CATCH=ON - -DCMAKE_SUPPRESS_REGENERATION=1 - . -- set MSBuildLogger="C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" -- cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger% -- cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger% -on_failure: if exist "tests\test_cmake_build" type tests\test_cmake_build\*.log* +version: 1.0.{build} +image: +- Visual Studio 2017 +test: off +skip_branch_with_pr: true +build: + parallel: true +platform: +- x86 +environment: + matrix: + - PYTHON: 36 + CONFIG: Debug +install: +- ps: | + $env:CMAKE_GENERATOR = "Visual Studio 15 2017" + if ($env:PLATFORM -eq "x64") { $env:PYTHON = "$env:PYTHON-x64" } + $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts\;$env:PATH" + python -W ignore -m pip install --upgrade pip wheel + python -W ignore -m pip install pytest numpy --no-warn-script-location pytest-timeout +- ps: | + Start-FileDownload 'https://gitlab.com/libeigen/eigen/-/archive/3.3.7/eigen-3.3.7.zip' + 7z x eigen-3.3.7.zip -y > $null + $env:CMAKE_INCLUDE_PATH = "eigen-3.3.7;$env:CMAKE_INCLUDE_PATH" +build_script: +- cmake -G "%CMAKE_GENERATOR%" -A "%CMAKE_ARCH%" + -DCMAKE_CXX_STANDARD=14 + -DPYBIND11_WERROR=ON + -DDOWNLOAD_CATCH=ON + -DCMAKE_SUPPRESS_REGENERATION=1 + . +- set MSBuildLogger="C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" +- cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger% +- cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger% +on_failure: if exist "tests\test_cmake_build" type tests\test_cmake_build\*.log* diff --git a/third_party/CityFlow/extern/pybind11/.clang-format b/third_party/CityFlow/extern/pybind11/.clang-format index b477a16037bc70dabe91e0bf7f8dae057124c653..7ec1c91bf1a83f14af90f67d99ca2dfb12df638d 100644 --- a/third_party/CityFlow/extern/pybind11/.clang-format +++ b/third_party/CityFlow/extern/pybind11/.clang-format @@ -1,38 +1,38 @@ ---- -# See all possible options and defaults with: -# clang-format --style=llvm --dump-config -BasedOnStyle: LLVM -AccessModifierOffset: -4 -AllowShortLambdasOnASingleLine: true -AlwaysBreakTemplateDeclarations: Yes -BinPackArguments: false -BinPackParameters: false -BreakBeforeBinaryOperators: All -BreakConstructorInitializers: BeforeColon -ColumnLimit: 99 -CommentPragmas: 'NOLINT:.*|^ IWYU pragma:' -IncludeBlocks: Regroup -IndentCaseLabels: true -IndentPPDirectives: AfterHash -IndentWidth: 4 -Language: Cpp -SpaceAfterCStyleCast: true -Standard: Cpp11 -StatementMacros: ['PyObject_HEAD'] -TabWidth: 4 -IncludeCategories: - - Regex: '' - Priority: 4 - - Regex: '.*' - Priority: 5 -... +--- +# See all possible options and defaults with: +# clang-format --style=llvm --dump-config +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AllowShortLambdasOnASingleLine: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false +BreakBeforeBinaryOperators: All +BreakConstructorInitializers: BeforeColon +ColumnLimit: 99 +CommentPragmas: 'NOLINT:.*|^ IWYU pragma:' +IncludeBlocks: Regroup +IndentCaseLabels: true +IndentPPDirectives: AfterHash +IndentWidth: 4 +Language: Cpp +SpaceAfterCStyleCast: true +Standard: Cpp11 +StatementMacros: ['PyObject_HEAD'] +TabWidth: 4 +IncludeCategories: + - Regex: '' + Priority: 4 + - Regex: '.*' + Priority: 5 +... diff --git a/third_party/CityFlow/extern/pybind11/.clang-tidy b/third_party/CityFlow/extern/pybind11/.clang-tidy index 23018386c1079cbc82d62e44aac840bd825396eb..6debc15f6d91317cdcb2b056969bd80c67fef40c 100644 --- a/third_party/CityFlow/extern/pybind11/.clang-tidy +++ b/third_party/CityFlow/extern/pybind11/.clang-tidy @@ -1,77 +1,77 @@ -FormatStyle: file - -Checks: | - *bugprone*, - *performance*, - clang-analyzer-optin.cplusplus.VirtualCall, - clang-analyzer-optin.performance.Padding, - cppcoreguidelines-init-variables, - cppcoreguidelines-prefer-member-initializer, - cppcoreguidelines-pro-type-static-cast-downcast, - cppcoreguidelines-slicing, - google-explicit-constructor, - llvm-namespace-comment, - misc-definitions-in-headers, - misc-misplaced-const, - misc-non-copyable-objects, - misc-static-assert, - misc-throw-by-value-catch-by-reference, - misc-uniqueptr-reset-release, - misc-unused-parameters, - modernize-avoid-bind, - modernize-loop-convert, - modernize-make-shared, - modernize-redundant-void-arg, - modernize-replace-auto-ptr, - modernize-replace-disallow-copy-and-assign-macro, - modernize-replace-random-shuffle, - modernize-shrink-to-fit, - modernize-use-auto, - modernize-use-bool-literals, - modernize-use-default-member-init, - modernize-use-emplace, - modernize-use-equals-default, - modernize-use-equals-delete, - modernize-use-noexcept, - modernize-use-nullptr, - modernize-use-override, - modernize-use-using, - readability-avoid-const-params-in-decls, - readability-braces-around-statements, - readability-const-return-type, - readability-container-size-empty, - readability-delete-null-pointer, - readability-else-after-return, - readability-implicit-bool-conversion, - readability-inconsistent-declaration-parameter-name, - readability-make-member-function-const, - readability-misplaced-array-index, - readability-non-const-parameter, - readability-qualified-auto, - readability-redundant-function-ptr-dereference, - readability-redundant-smartptr-get, - readability-redundant-string-cstr, - readability-simplify-subscript-expr, - readability-static-accessed-through-instance, - readability-static-definition-in-anonymous-namespace, - readability-string-compare, - readability-suspicious-call-argument, - readability-uniqueptr-delete-release, - -bugprone-easily-swappable-parameters, - -bugprone-exception-escape, - -bugprone-reserved-identifier, - -bugprone-unused-raii, - -CheckOptions: -- key: modernize-use-equals-default.IgnoreMacros - value: false -- key: performance-for-range-copy.WarnOnAllAutoCopies - value: true -- key: performance-inefficient-string-concatenation.StrictMode - value: true -- key: performance-unnecessary-value-param.AllowedTypes - value: 'exception_ptr$;' -- key: readability-implicit-bool-conversion.AllowPointerConditions - value: true - -HeaderFilterRegex: 'pybind11/.*h' +FormatStyle: file + +Checks: | + *bugprone*, + *performance*, + clang-analyzer-optin.cplusplus.VirtualCall, + clang-analyzer-optin.performance.Padding, + cppcoreguidelines-init-variables, + cppcoreguidelines-prefer-member-initializer, + cppcoreguidelines-pro-type-static-cast-downcast, + cppcoreguidelines-slicing, + google-explicit-constructor, + llvm-namespace-comment, + misc-definitions-in-headers, + misc-misplaced-const, + misc-non-copyable-objects, + misc-static-assert, + misc-throw-by-value-catch-by-reference, + misc-uniqueptr-reset-release, + misc-unused-parameters, + modernize-avoid-bind, + modernize-loop-convert, + modernize-make-shared, + modernize-redundant-void-arg, + modernize-replace-auto-ptr, + modernize-replace-disallow-copy-and-assign-macro, + modernize-replace-random-shuffle, + modernize-shrink-to-fit, + modernize-use-auto, + modernize-use-bool-literals, + modernize-use-default-member-init, + modernize-use-emplace, + modernize-use-equals-default, + modernize-use-equals-delete, + modernize-use-noexcept, + modernize-use-nullptr, + modernize-use-override, + modernize-use-using, + readability-avoid-const-params-in-decls, + readability-braces-around-statements, + readability-const-return-type, + readability-container-size-empty, + readability-delete-null-pointer, + readability-else-after-return, + readability-implicit-bool-conversion, + readability-inconsistent-declaration-parameter-name, + readability-make-member-function-const, + readability-misplaced-array-index, + readability-non-const-parameter, + readability-qualified-auto, + readability-redundant-function-ptr-dereference, + readability-redundant-smartptr-get, + readability-redundant-string-cstr, + readability-simplify-subscript-expr, + readability-static-accessed-through-instance, + readability-static-definition-in-anonymous-namespace, + readability-string-compare, + readability-suspicious-call-argument, + readability-uniqueptr-delete-release, + -bugprone-easily-swappable-parameters, + -bugprone-exception-escape, + -bugprone-reserved-identifier, + -bugprone-unused-raii, + +CheckOptions: +- key: modernize-use-equals-default.IgnoreMacros + value: false +- key: performance-for-range-copy.WarnOnAllAutoCopies + value: true +- key: performance-inefficient-string-concatenation.StrictMode + value: true +- key: performance-unnecessary-value-param.AllowedTypes + value: 'exception_ptr$;' +- key: readability-implicit-bool-conversion.AllowPointerConditions + value: true + +HeaderFilterRegex: 'pybind11/.*h' diff --git a/third_party/CityFlow/extern/pybind11/.cmake-format.yaml b/third_party/CityFlow/extern/pybind11/.cmake-format.yaml index a2a69f3f897da990a4255b593dc3fcdf4b89a764..2371b63a853bf9b83965a1c1c15e3619942e7f21 100644 --- a/third_party/CityFlow/extern/pybind11/.cmake-format.yaml +++ b/third_party/CityFlow/extern/pybind11/.cmake-format.yaml @@ -1,73 +1,73 @@ -parse: - additional_commands: - pybind11_add_module: - flags: - - THIN_LTO - - MODULE - - SHARED - - NO_EXTRAS - - EXCLUDE_FROM_ALL - - SYSTEM - -format: - line_width: 99 - tab_size: 2 - - # If an argument group contains more than this many sub-groups - # (parg or kwarg groups) then force it to a vertical layout. - max_subgroups_hwrap: 2 - - # If a positional argument group contains more than this many - # arguments, then force it to a vertical layout. - max_pargs_hwrap: 6 - - # If a cmdline positional group consumes more than this many - # lines without nesting, then invalidate the layout (and nest) - max_rows_cmdline: 2 - separate_ctrl_name_with_space: false - separate_fn_name_with_space: false - dangle_parens: false - - # If the trailing parenthesis must be 'dangled' on its on - # 'line, then align it to this reference: `prefix`: the start' - # 'of the statement, `prefix-indent`: the start of the' - # 'statement, plus one indentation level, `child`: align to' - # the column of the arguments - dangle_align: prefix - # If the statement spelling length (including space and - # parenthesis) is smaller than this amount, then force reject - # nested layouts. - min_prefix_chars: 4 - - # If the statement spelling length (including space and - # parenthesis) is larger than the tab width by more than this - # amount, then force reject un-nested layouts. - max_prefix_chars: 10 - - # If a candidate layout is wrapped horizontally but it exceeds - # this many lines, then reject the layout. - max_lines_hwrap: 2 - - line_ending: unix - - # Format command names consistently as 'lower' or 'upper' case - command_case: canonical - - # Format keywords consistently as 'lower' or 'upper' case - # unchanged is valid too - keyword_case: 'upper' - - # A list of command names which should always be wrapped - always_wrap: [] - - # If true, the argument lists which are known to be sortable - # will be sorted lexicographically - enable_sort: true - - # If true, the parsers may infer whether or not an argument - # list is sortable (without annotation). - autosort: false - -# Causes a few issues - can be solved later, possibly. -markup: - enable_markup: false +parse: + additional_commands: + pybind11_add_module: + flags: + - THIN_LTO + - MODULE + - SHARED + - NO_EXTRAS + - EXCLUDE_FROM_ALL + - SYSTEM + +format: + line_width: 99 + tab_size: 2 + + # If an argument group contains more than this many sub-groups + # (parg or kwarg groups) then force it to a vertical layout. + max_subgroups_hwrap: 2 + + # If a positional argument group contains more than this many + # arguments, then force it to a vertical layout. + max_pargs_hwrap: 6 + + # If a cmdline positional group consumes more than this many + # lines without nesting, then invalidate the layout (and nest) + max_rows_cmdline: 2 + separate_ctrl_name_with_space: false + separate_fn_name_with_space: false + dangle_parens: false + + # If the trailing parenthesis must be 'dangled' on its on + # 'line, then align it to this reference: `prefix`: the start' + # 'of the statement, `prefix-indent`: the start of the' + # 'statement, plus one indentation level, `child`: align to' + # the column of the arguments + dangle_align: prefix + # If the statement spelling length (including space and + # parenthesis) is smaller than this amount, then force reject + # nested layouts. + min_prefix_chars: 4 + + # If the statement spelling length (including space and + # parenthesis) is larger than the tab width by more than this + # amount, then force reject un-nested layouts. + max_prefix_chars: 10 + + # If a candidate layout is wrapped horizontally but it exceeds + # this many lines, then reject the layout. + max_lines_hwrap: 2 + + line_ending: unix + + # Format command names consistently as 'lower' or 'upper' case + command_case: canonical + + # Format keywords consistently as 'lower' or 'upper' case + # unchanged is valid too + keyword_case: 'upper' + + # A list of command names which should always be wrapped + always_wrap: [] + + # If true, the argument lists which are known to be sortable + # will be sorted lexicographically + enable_sort: true + + # If true, the parsers may infer whether or not an argument + # list is sortable (without annotation). + autosort: false + +# Causes a few issues - can be solved later, possibly. +markup: + enable_markup: false diff --git a/third_party/CityFlow/extern/pybind11/.codespell-ignore-lines b/third_party/CityFlow/extern/pybind11/.codespell-ignore-lines index 2a01d63ebb35287ef7e95ddf5c856ca272872b6b..5c7cd2821a3ea6a8c0dcaa94ed9abe9eb1c4d20e 100644 --- a/third_party/CityFlow/extern/pybind11/.codespell-ignore-lines +++ b/third_party/CityFlow/extern/pybind11/.codespell-ignore-lines @@ -1,24 +1,24 @@ -template - template - auto &this_ = static_cast(*this); - if (load_impl(temp, false)) { - ssize_t nd = 0; - auto trivial = broadcast(buffers, nd, shape); - auto ndim = (size_t) nd; - int nd; - ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; } - using op = op_impl; -template - template - class_ &def(const detail::op_ &op, const Extra &...extra) { - class_ &def_cast(const detail::op_ &op, const Extra &...extra) { -@pytest.mark.parametrize("access", ["ro", "rw", "static_ro", "static_rw"]) -struct IntStruct { - explicit IntStruct(int v) : value(v){}; - ~IntStruct() { value = -value; } - IntStruct(const IntStruct &) = default; - IntStruct &operator=(const IntStruct &) = default; - py::class_(m, "IntStruct").def(py::init([](const int i) { return IntStruct(i); })); - py::implicitly_convertible(); - m.def("test", [](int expected, const IntStruct &in) { - [](int expected, const IntStruct &in) { +template + template + auto &this_ = static_cast(*this); + if (load_impl(temp, false)) { + ssize_t nd = 0; + auto trivial = broadcast(buffers, nd, shape); + auto ndim = (size_t) nd; + int nd; + ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; } + using op = op_impl; +template + template + class_ &def(const detail::op_ &op, const Extra &...extra) { + class_ &def_cast(const detail::op_ &op, const Extra &...extra) { +@pytest.mark.parametrize("access", ["ro", "rw", "static_ro", "static_rw"]) +struct IntStruct { + explicit IntStruct(int v) : value(v){}; + ~IntStruct() { value = -value; } + IntStruct(const IntStruct &) = default; + IntStruct &operator=(const IntStruct &) = default; + py::class_(m, "IntStruct").def(py::init([](const int i) { return IntStruct(i); })); + py::implicitly_convertible(); + m.def("test", [](int expected, const IntStruct &in) { + [](int expected, const IntStruct &in) { diff --git a/third_party/CityFlow/extern/pybind11/.git.bak/FETCH_HEAD b/third_party/CityFlow/extern/pybind11/.git.bak/FETCH_HEAD index ef06204eb799d121d6a90c8b5901470094a4faf2..7aa0b9dac6cae0275828418ea5763b5c89fa6fec 100644 --- a/third_party/CityFlow/extern/pybind11/.git.bak/FETCH_HEAD +++ b/third_party/CityFlow/extern/pybind11/.git.bak/FETCH_HEAD @@ -1,32 +1,32 @@ -68a11bb65b774df161c898204d08e85ac2cbac5f not-for-merge branch 'archive/smart_holder' of https://github.com/pybind/pybind11 -619fb2305697c1eb4a6e248af03eab2c8c57237d not-for-merge branch 'array-sequence-fix' of https://github.com/pybind/pybind11 -1423623205a5d656ec2f068b948dcf5f02146f2f not-for-merge branch 'cpp17-aligned-new' of https://github.com/pybind/pybind11 -fd3a93c520a661b78e177280128a9c855d7f5be5 not-for-merge branch 'fold-expression-caster' of https://github.com/pybind/pybind11 -9fa6acdf5bf53b6f26d6bf2f1bdab65da782ec08 not-for-merge branch 'henryiii-patch-1' of https://github.com/pybind/pybind11 -d8c30a8f2df87007ca2a5679119af50aff5c0695 not-for-merge branch 'henryiii-patch-2' of https://github.com/pybind/pybind11 -d7cc5b052d737de8478b536fee4a2075cedec866 not-for-merge branch 'henryiii-patch-3' of https://github.com/pybind/pybind11 -19ddbe5bc3eb3064201a914626ac642e1884e654 not-for-merge branch 'henryiii/revert/pycapsule' of https://github.com/pybind/pybind11 -78e074b8bbda1073e60273620e084aac28b0740c not-for-merge branch 'internals_ptr' of https://github.com/pybind/pybind11 -8986743b6daebfcb07428e921192ff77308db055 not-for-merge branch 'issue1561_fix' of https://github.com/pybind/pybind11 -cd538ed1184d41cf685dd4da81c1eca80d24f353 not-for-merge branch 'master' of https://github.com/pybind/pybind11 -45c45eefe9bb7ba37a7e71dcabff5e7b5ff4596c not-for-merge branch 'pre-commit-ci-update-config' of https://github.com/pybind/pybind11 -dba00d7369677617d00974f5a00ebcd5e6288cdc not-for-merge branch 'revert-4220-fix-nvcc-11.4-11.8' of https://github.com/pybind/pybind11 -04cfb45b7998fe960a70743770b94bdb3a712f73 not-for-merge branch 'stable' of https://github.com/pybind/pybind11 -e076c4513dc2c89c1e9b7cb716fb8e4588e8e067 not-for-merge branch 'undefined-macos' of https://github.com/pybind/pybind11 -121360c6ae0fff0c97c64470508c11a0cc27bf94 not-for-merge branch 'v1.8' of https://github.com/pybind/pybind11 -07de0d8627101be53986e841cd4e21ee38c2498a not-for-merge branch 'v2.0' of https://github.com/pybind/pybind11 -1df91d36cfa997c8987889234304ea5e37cc3e68 not-for-merge branch 'v2.1' of https://github.com/pybind/pybind11 -5b0a6fc2017fcc176545afe3e09c9f9885283242 not-for-merge branch 'v2.10' of https://github.com/pybind/pybind11 -95d943ae0ebdf609bbd650d119fda539509929b6 not-for-merge branch 'v2.11' of https://github.com/pybind/pybind11 -2e0815278cb899b20870a67ca8205996ef47e70f not-for-merge branch 'v2.12' of https://github.com/pybind/pybind11 -a2e59f0e7065404b44dfe92a28aca47ba1378dc4 not-for-merge branch 'v2.13' of https://github.com/pybind/pybind11 -a23996fce38ff6ccfbcdc09f1e63f2c4be5ea2ef not-for-merge branch 'v2.2' of https://github.com/pybind/pybind11 -a1b71df137e015d44f7e31f7b6d4807253fb7871 not-for-merge branch 'v2.3' of https://github.com/pybind/pybind11 -80d452484c5409444b0ec19383faa84bb7a4d351 not-for-merge branch 'v2.4' of https://github.com/pybind/pybind11 -3b1dbebabc801c9cf6f0953a4c20b904d444f879 not-for-merge branch 'v2.5' of https://github.com/pybind/pybind11 -8de7772cc72daca8e947b79b83fea46214931604 not-for-merge branch 'v2.6' of https://github.com/pybind/pybind11 -5b4432439ed72417253f9eec99f2a014636c0362 not-for-merge branch 'v2.7' of https://github.com/pybind/pybind11 -f7b499615e14d70ab098a20deb0cdb3889998a1a not-for-merge branch 'v2.8' of https://github.com/pybind/pybind11 -914c06fb252b6cc3727d0eedab6736e88a3fcb01 not-for-merge branch 'v2.9' of https://github.com/pybind/pybind11 -45fab4087eaaff234227a10cf7845e8b07f28a98 not-for-merge branch 'v3.0' of https://github.com/pybind/pybind11 -0991e90375606254087f7bffe0dd15dd910ec62b not-for-merge branch 'void-caster-fix' of https://github.com/pybind/pybind11 +68a11bb65b774df161c898204d08e85ac2cbac5f not-for-merge branch 'archive/smart_holder' of https://github.com/pybind/pybind11 +619fb2305697c1eb4a6e248af03eab2c8c57237d not-for-merge branch 'array-sequence-fix' of https://github.com/pybind/pybind11 +1423623205a5d656ec2f068b948dcf5f02146f2f not-for-merge branch 'cpp17-aligned-new' of https://github.com/pybind/pybind11 +fd3a93c520a661b78e177280128a9c855d7f5be5 not-for-merge branch 'fold-expression-caster' of https://github.com/pybind/pybind11 +9fa6acdf5bf53b6f26d6bf2f1bdab65da782ec08 not-for-merge branch 'henryiii-patch-1' of https://github.com/pybind/pybind11 +d8c30a8f2df87007ca2a5679119af50aff5c0695 not-for-merge branch 'henryiii-patch-2' of https://github.com/pybind/pybind11 +d7cc5b052d737de8478b536fee4a2075cedec866 not-for-merge branch 'henryiii-patch-3' of https://github.com/pybind/pybind11 +19ddbe5bc3eb3064201a914626ac642e1884e654 not-for-merge branch 'henryiii/revert/pycapsule' of https://github.com/pybind/pybind11 +78e074b8bbda1073e60273620e084aac28b0740c not-for-merge branch 'internals_ptr' of https://github.com/pybind/pybind11 +8986743b6daebfcb07428e921192ff77308db055 not-for-merge branch 'issue1561_fix' of https://github.com/pybind/pybind11 +cd538ed1184d41cf685dd4da81c1eca80d24f353 not-for-merge branch 'master' of https://github.com/pybind/pybind11 +45c45eefe9bb7ba37a7e71dcabff5e7b5ff4596c not-for-merge branch 'pre-commit-ci-update-config' of https://github.com/pybind/pybind11 +dba00d7369677617d00974f5a00ebcd5e6288cdc not-for-merge branch 'revert-4220-fix-nvcc-11.4-11.8' of https://github.com/pybind/pybind11 +04cfb45b7998fe960a70743770b94bdb3a712f73 not-for-merge branch 'stable' of https://github.com/pybind/pybind11 +e076c4513dc2c89c1e9b7cb716fb8e4588e8e067 not-for-merge branch 'undefined-macos' of https://github.com/pybind/pybind11 +121360c6ae0fff0c97c64470508c11a0cc27bf94 not-for-merge branch 'v1.8' of https://github.com/pybind/pybind11 +07de0d8627101be53986e841cd4e21ee38c2498a not-for-merge branch 'v2.0' of https://github.com/pybind/pybind11 +1df91d36cfa997c8987889234304ea5e37cc3e68 not-for-merge branch 'v2.1' of https://github.com/pybind/pybind11 +5b0a6fc2017fcc176545afe3e09c9f9885283242 not-for-merge branch 'v2.10' of https://github.com/pybind/pybind11 +95d943ae0ebdf609bbd650d119fda539509929b6 not-for-merge branch 'v2.11' of https://github.com/pybind/pybind11 +2e0815278cb899b20870a67ca8205996ef47e70f not-for-merge branch 'v2.12' of https://github.com/pybind/pybind11 +a2e59f0e7065404b44dfe92a28aca47ba1378dc4 not-for-merge branch 'v2.13' of https://github.com/pybind/pybind11 +a23996fce38ff6ccfbcdc09f1e63f2c4be5ea2ef not-for-merge branch 'v2.2' of https://github.com/pybind/pybind11 +a1b71df137e015d44f7e31f7b6d4807253fb7871 not-for-merge branch 'v2.3' of https://github.com/pybind/pybind11 +80d452484c5409444b0ec19383faa84bb7a4d351 not-for-merge branch 'v2.4' of https://github.com/pybind/pybind11 +3b1dbebabc801c9cf6f0953a4c20b904d444f879 not-for-merge branch 'v2.5' of https://github.com/pybind/pybind11 +8de7772cc72daca8e947b79b83fea46214931604 not-for-merge branch 'v2.6' of https://github.com/pybind/pybind11 +5b4432439ed72417253f9eec99f2a014636c0362 not-for-merge branch 'v2.7' of https://github.com/pybind/pybind11 +f7b499615e14d70ab098a20deb0cdb3889998a1a not-for-merge branch 'v2.8' of https://github.com/pybind/pybind11 +914c06fb252b6cc3727d0eedab6736e88a3fcb01 not-for-merge branch 'v2.9' of https://github.com/pybind/pybind11 +45fab4087eaaff234227a10cf7845e8b07f28a98 not-for-merge branch 'v3.0' of https://github.com/pybind/pybind11 +0991e90375606254087f7bffe0dd15dd910ec62b not-for-merge branch 'void-caster-fix' of https://github.com/pybind/pybind11 diff --git a/third_party/CityFlow/extern/pybind11/.git.bak/HEAD b/third_party/CityFlow/extern/pybind11/.git.bak/HEAD index a65636e1da5633cb681a3a0abcecd6d2b72c5904..0dbaa48057eb8e4b96c78589ffd9f30d505df67e 100644 --- a/third_party/CityFlow/extern/pybind11/.git.bak/HEAD +++ b/third_party/CityFlow/extern/pybind11/.git.bak/HEAD @@ -1 +1 @@ -3e9dfa2866941655c56877882565e7577de6fc7b +3e9dfa2866941655c56877882565e7577de6fc7b diff --git a/third_party/CityFlow/extern/pybind11/.git.bak/config b/third_party/CityFlow/extern/pybind11/.git.bak/config index aa0aa90930a61bad0f04470655e698cd6f85de6e..d5e2d2b94de4492b736568851fb851c58783b6d6 100644 --- a/third_party/CityFlow/extern/pybind11/.git.bak/config +++ b/third_party/CityFlow/extern/pybind11/.git.bak/config @@ -1,13 +1,13 @@ -[core] - repositoryformatversion = 0 - filemode = true - bare = false - logallrefupdates = true - ignorecase = true - precomposeunicode = true -[remote "origin"] - url = https://github.com/pybind/pybind11.git - fetch = +refs/heads/*:refs/remotes/origin/* -[branch "master"] - remote = origin - merge = refs/heads/master +[core] + repositoryformatversion = 0 + filemode = true + bare = false + logallrefupdates = true + ignorecase = true + precomposeunicode = true +[remote "origin"] + url = https://github.com/pybind/pybind11.git + fetch = +refs/heads/*:refs/remotes/origin/* +[branch "master"] + remote = origin + merge = refs/heads/master diff --git a/third_party/CityFlow/extern/pybind11/.git.bak/description b/third_party/CityFlow/extern/pybind11/.git.bak/description index 498b267a8c7812490d6479839c5577eaaec79d62..893e5cad249f51c4660252d98ce696a69db917ee 100644 --- a/third_party/CityFlow/extern/pybind11/.git.bak/description +++ b/third_party/CityFlow/extern/pybind11/.git.bak/description @@ -1 +1 @@ -Unnamed repository; edit this file 'description' to name the repository. +Unnamed repository; edit this file 'description' to name the repository. diff --git a/third_party/CityFlow/extern/pybind11/.git.bak/packed-refs b/third_party/CityFlow/extern/pybind11/.git.bak/packed-refs index 75ccb1fe27f8270809dc66e8581e8ce3fada40d4..290632b74b180ca5d391073bed6b265268d556ff 100644 --- a/third_party/CityFlow/extern/pybind11/.git.bak/packed-refs +++ b/third_party/CityFlow/extern/pybind11/.git.bak/packed-refs @@ -1,143 +1,143 @@ -# pack-refs with: peeled fully-peeled sorted -68a11bb65b774df161c898204d08e85ac2cbac5f refs/remotes/origin/archive/smart_holder -619fb2305697c1eb4a6e248af03eab2c8c57237d refs/remotes/origin/array-sequence-fix -1423623205a5d656ec2f068b948dcf5f02146f2f refs/remotes/origin/cpp17-aligned-new -fd3a93c520a661b78e177280128a9c855d7f5be5 refs/remotes/origin/fold-expression-caster -9fa6acdf5bf53b6f26d6bf2f1bdab65da782ec08 refs/remotes/origin/henryiii-patch-1 -d8c30a8f2df87007ca2a5679119af50aff5c0695 refs/remotes/origin/henryiii-patch-2 -d7cc5b052d737de8478b536fee4a2075cedec866 refs/remotes/origin/henryiii-patch-3 -19ddbe5bc3eb3064201a914626ac642e1884e654 refs/remotes/origin/henryiii/revert/pycapsule -78e074b8bbda1073e60273620e084aac28b0740c refs/remotes/origin/internals_ptr -8986743b6daebfcb07428e921192ff77308db055 refs/remotes/origin/issue1561_fix -cd538ed1184d41cf685dd4da81c1eca80d24f353 refs/remotes/origin/master -45c45eefe9bb7ba37a7e71dcabff5e7b5ff4596c refs/remotes/origin/pre-commit-ci-update-config -dba00d7369677617d00974f5a00ebcd5e6288cdc refs/remotes/origin/revert-4220-fix-nvcc-11.4-11.8 -04cfb45b7998fe960a70743770b94bdb3a712f73 refs/remotes/origin/stable -e076c4513dc2c89c1e9b7cb716fb8e4588e8e067 refs/remotes/origin/undefined-macos -121360c6ae0fff0c97c64470508c11a0cc27bf94 refs/remotes/origin/v1.8 -07de0d8627101be53986e841cd4e21ee38c2498a refs/remotes/origin/v2.0 -1df91d36cfa997c8987889234304ea5e37cc3e68 refs/remotes/origin/v2.1 -5b0a6fc2017fcc176545afe3e09c9f9885283242 refs/remotes/origin/v2.10 -95d943ae0ebdf609bbd650d119fda539509929b6 refs/remotes/origin/v2.11 -2e0815278cb899b20870a67ca8205996ef47e70f refs/remotes/origin/v2.12 -a2e59f0e7065404b44dfe92a28aca47ba1378dc4 refs/remotes/origin/v2.13 -a23996fce38ff6ccfbcdc09f1e63f2c4be5ea2ef refs/remotes/origin/v2.2 -a1b71df137e015d44f7e31f7b6d4807253fb7871 refs/remotes/origin/v2.3 -80d452484c5409444b0ec19383faa84bb7a4d351 refs/remotes/origin/v2.4 -3b1dbebabc801c9cf6f0953a4c20b904d444f879 refs/remotes/origin/v2.5 -8de7772cc72daca8e947b79b83fea46214931604 refs/remotes/origin/v2.6 -5b4432439ed72417253f9eec99f2a014636c0362 refs/remotes/origin/v2.7 -f7b499615e14d70ab098a20deb0cdb3889998a1a refs/remotes/origin/v2.8 -914c06fb252b6cc3727d0eedab6736e88a3fcb01 refs/remotes/origin/v2.9 -45fab4087eaaff234227a10cf7845e8b07f28a98 refs/remotes/origin/v3.0 -0991e90375606254087f7bffe0dd15dd910ec62b refs/remotes/origin/void-caster-fix -8ae716ab79e0141537eff420cb7e79b06d14c402 refs/tags/v1.0 -^929fd7e6946255ed84c803d2993f48912de96e15 -1a25b3f8f7455246adf2930e4c857c128c71a240 refs/tags/v1.1 -^bda3b67dc5f9481857aa7a14478bab3293bb376f -ef4345f46c672a74e161f5a8955784658fb10ae8 refs/tags/v1.2 -^8ed2808239f3a6052e7789feeeab34eed39b5c62 -1c32fcbfba8849abedf2a50e675e5f847c20a42d refs/tags/v1.3 -^d2385e8fc6a3008cab96532c99db4c3d57541fc5 -0b8a0c621a2872312b477bed4f8b72a1a3a34d61 refs/tags/v1.4 -^0e6ca5916e2585ca9b778f8304c166b6a36b7e5a -dce23aeae9dcae322670073e6b5a7a22fb740c14 refs/tags/v1.5 -^bb79d7bdc0f48f1a9284af85bf36d392afc28307 -549781cb1c71a91b8bab23e452c5bfed413dee40 refs/tags/v1.6 -^e85e9d82824e88352c9389694ff2130e4a6c5d02 -f21d226f83c5c3db2f3f5c554c35fb8942fd6dcb refs/tags/v1.7 -^e70b2abb6dee27a2889b01f245a2a28e6fcd4b01 -8e8bd7090ba1197117560c7e7f46cd2e9d026424 refs/tags/v1.8 -^c0759976177b92f386856a5d9f2e8d63ef89293a -4da184714d7a3ee298edcabb51497c629108205b refs/tags/v1.8.1 -^121360c6ae0fff0c97c64470508c11a0cc27bf94 -40585804f4e9dbf45b277dd55c19a8026b356eef refs/tags/v2.0.0 -^e33ef9c20d36fe760792c61ccc95ecf1b42cf81d -12006926087bdd34dcbd4db40611be7d5b6ed830 refs/tags/v2.0.0-rc1 -^3c7967111280b0a796986ac2025d0ca201623656 -f74dd5d5a4033e68d9000d3c288d0b57a3fc0105 refs/tags/v2.0.1 -^07de0d8627101be53986e841cd4e21ee38c2498a -a2207c044fdffac6023975df015e73f161082b57 refs/tags/v2.1.0 -^ad9d574c85f1836c57f2f0727ffe997bb8cbfdd7 -cbf3c94e781074f2f094e9a39d7ea86304d69a1d refs/tags/v2.1.1 -^1df91d36cfa997c8987889234304ea5e37cc3e68 -8d298f32f3bf5c1854adeadf7f1ec1c236dd5221 refs/tags/v2.10.0 -^aa304c9c7d725ffb9d10af08a3b34cb372307020 -bcee506ac0b09ea13000484c08ab3e5a41ee0fb2 refs/tags/v2.10.1 -^80dc998efced8ceb2be59756668a7e90e8bef917 -76b3533f96774e555a6e10d6deb9bbafe4970011 refs/tags/v2.10.2 -^0694ec6a15863bff2e0ea5efe07c78de39b9a33c -70a09bf92bff267b3eceee51bee00741bc91367f refs/tags/v2.10.3 -^0bd8896a4010f2d91b2340570c24fa08606ec406 -95ddd6b61bbecd06d00eef8a0e72fa9ffd46631e refs/tags/v2.10.4 -^5b0a6fc2017fcc176545afe3e09c9f9885283242 -8d8aecf4a5579c0e51d07fb93411aa120ae0360c refs/tags/v2.11.0 -^1a917f1852eb7819b671fc3fa862840f4c491a07 -0630807c3070287c716f6be3eacb00b8816b4215 refs/tags/v2.11.1 -^8a099e44b3d5f85b20f05828d919d2332a8de841 -95d943ae0ebdf609bbd650d119fda539509929b6 refs/tags/v2.11.2 -3e9dfa2866941655c56877882565e7577de6fc7b refs/tags/v2.12.0 -2e0815278cb899b20870a67ca8205996ef47e70f refs/tags/v2.12.1 -0c69e1eb2177fa8f8580632c7b1f97fdb606ce8f refs/tags/v2.13.0 -941f45bcb51457884fa1afd6e24a67377d70f75c refs/tags/v2.13.1 -07f30430d4186c2712761f1ffaea50ede63f2b2b refs/tags/v2.13.2 -bd67643652d3800837f1f41549a2a5adbaa3fafe refs/tags/v2.13.3 -c6239a8a1b6871cc0fb5f7af885a02ffd1349f9d refs/tags/v2.13.4 -7c33cdc2d39c7b99a122579f53bc94c8eb3332ff refs/tags/v2.13.5 -a2e59f0e7065404b44dfe92a28aca47ba1378dc4 refs/tags/v2.13.6 -c36cf6254170aa8aef35b65854f518016551d5b8 refs/tags/v2.2.0 -^2a5a5ec0a47c245fbf1bb1a8a90b4c3278e01693 -9a9239eaa52e0e2a16c76894a7f30f19997f0167 refs/tags/v2.2.1 -^86e2ad4f77442c3350f9a2476650da6bee253c52 -8bd683141ccf900aafc3dc76e5efd86f1e8ac541 refs/tags/v2.2.2 -^f117a48ea2fd446d2865826a58d08027d4579cb3 -197ae8a04cec7bf9327d36c780d4fca2a6b51339 refs/tags/v2.2.3 -^8edc147d67ca85a93ed1f53628004528dc36a04d -e4637eb508aa3e41233875f6ce3891d96fbc5d33 refs/tags/v2.2.4 -^9a19306fbf30642ca331d0ec88e7da54a96860f9 -7107ada7cbbd01e76a2a9f3e2ec27b683dcec99b refs/tags/v2.3.0 -^e43e1cc01ae6d4e4e5ba10557a057d7f3d5ece0d -ca8264815ffcf8beda3b206405a92927c722027f refs/tags/v2.4.0 -^00a0aa992953d6482114a0f539a21bb535a16383 -8b7a01d0b8dddf9ff650a6511377cd32a4f1501a refs/tags/v2.4.1 -^e44fcc3c15b41f0720c72832c0b9cd07de819781 -6c383e01bbd4155a29ad280ad7ba7941e05675dd refs/tags/v2.4.2 -^7ec2ddfc95f65d1e986d359466a6c254aa514ef3 -aa56a0e4a40af9ff27dd5b4d283d29bc64c19088 refs/tags/v2.4.3 -^80d452484c5409444b0ec19383faa84bb7a4d351 -014cd12ec1a3258f3bfc6597f371ed46c8e89ccd refs/tags/v2.5.0 -^3b1dbebabc801c9cf6f0953a4c20b904d444f879 -78b2d1991b9e81bbc1a6670ab4af189094e952eb refs/tags/v2.6.0 -^59a2ac2745d8a57ac94c6accced73620d59fb844 -319b99648b94c37e16cec64e0aec6d80557de64f refs/tags/v2.6.0b1 -d46f3322a45cb907777f568bb1377ab1b9457ad8 refs/tags/v2.6.0rc1 -c4a8b5bb9140cdc8c214044d41e2593986f875d0 refs/tags/v2.6.0rc2 -c16da993094988141101ac4d96a9b2c92f9ac714 refs/tags/v2.6.0rc3 -f4bc37b3de4857b9d80c1d85ff9f9e5dceef3dd4 refs/tags/v2.6.1 -^f1abf5d9159b805674197f6bc443592e631c9130 -c7faa0f557df4ee266e6e6dca311cd1474ad2123 refs/tags/v2.6.2 -^8de7772cc72daca8e947b79b83fea46214931604 -40d14c37b4cb8488a241f837ea2e3eb60404f7b7 refs/tags/v2.7.0 -^65e95ea8675ea34bdd566d6461330f25c651e5a8 -c0e8a831c6023be719144e7d10c8ea7c9fb81a58 refs/tags/v2.7.1 -^787d2c88cafa4d07fb38c9519c485a86323cfcf4 -dc756043d5ed7654e48c41d97a64403a847214a7 refs/tags/v2.8.0 -^97976c16fb7652f7faf02d76756666ef87adbe7d -79dfe03e432e2af41bba00add596e6df92099b49 refs/tags/v2.8.1 -^f7b499615e14d70ab098a20deb0cdb3889998a1a -1dad2a58efb1eef1eb9f2e5532dedd3711924810 refs/tags/v2.9.0 -^45f792efdd92da094548e2095d6efdbfa7e536ee -35b51445ba2bf5e67137c04bc26ceaab33e4285f refs/tags/v2.9.1 -^ffa346860b306c9bbfb341aed9c14c067751feb8 -dd9ef9f901f3d49426f87a67666393970a6c9431 refs/tags/v2.9.2 -^914c06fb252b6cc3727d0eedab6736e88a3fcb01 -f0ecf21301c0c24bc78b8b310347c7507d9f41d0 refs/tags/v3.0.0 -^ed5057ded698e305210269dafa57574ecf964483 -fc888f758fde1c37d80f85666060d3f179f6c001 refs/tags/v3.0.0rc1 -df595b16579d847cd019072aa0daec1e566c7ba2 refs/tags/v3.0.0rc2 -5d32ed76c0ea53d689f9cec3d4c152d1b0738e8e refs/tags/v3.0.0rc3 -ea3e33e40dd1cbfa9f885e991386337a0e5b4b66 refs/tags/v3.0.0rc4 -e86205cb2ba070755d582856430c0f83c0af6694 refs/tags/v3.0.1 -^f5fbe867d2d26e4a0a9177a51f6e568868ad3dc8 -e6c503bb0b0c13f76ca0546eca7f8d986039517f refs/tags/v3.0.2 -^45fab4087eaaff234227a10cf7845e8b07f28a98 +# pack-refs with: peeled fully-peeled sorted +68a11bb65b774df161c898204d08e85ac2cbac5f refs/remotes/origin/archive/smart_holder +619fb2305697c1eb4a6e248af03eab2c8c57237d refs/remotes/origin/array-sequence-fix +1423623205a5d656ec2f068b948dcf5f02146f2f refs/remotes/origin/cpp17-aligned-new +fd3a93c520a661b78e177280128a9c855d7f5be5 refs/remotes/origin/fold-expression-caster +9fa6acdf5bf53b6f26d6bf2f1bdab65da782ec08 refs/remotes/origin/henryiii-patch-1 +d8c30a8f2df87007ca2a5679119af50aff5c0695 refs/remotes/origin/henryiii-patch-2 +d7cc5b052d737de8478b536fee4a2075cedec866 refs/remotes/origin/henryiii-patch-3 +19ddbe5bc3eb3064201a914626ac642e1884e654 refs/remotes/origin/henryiii/revert/pycapsule +78e074b8bbda1073e60273620e084aac28b0740c refs/remotes/origin/internals_ptr +8986743b6daebfcb07428e921192ff77308db055 refs/remotes/origin/issue1561_fix +cd538ed1184d41cf685dd4da81c1eca80d24f353 refs/remotes/origin/master +45c45eefe9bb7ba37a7e71dcabff5e7b5ff4596c refs/remotes/origin/pre-commit-ci-update-config +dba00d7369677617d00974f5a00ebcd5e6288cdc refs/remotes/origin/revert-4220-fix-nvcc-11.4-11.8 +04cfb45b7998fe960a70743770b94bdb3a712f73 refs/remotes/origin/stable +e076c4513dc2c89c1e9b7cb716fb8e4588e8e067 refs/remotes/origin/undefined-macos +121360c6ae0fff0c97c64470508c11a0cc27bf94 refs/remotes/origin/v1.8 +07de0d8627101be53986e841cd4e21ee38c2498a refs/remotes/origin/v2.0 +1df91d36cfa997c8987889234304ea5e37cc3e68 refs/remotes/origin/v2.1 +5b0a6fc2017fcc176545afe3e09c9f9885283242 refs/remotes/origin/v2.10 +95d943ae0ebdf609bbd650d119fda539509929b6 refs/remotes/origin/v2.11 +2e0815278cb899b20870a67ca8205996ef47e70f refs/remotes/origin/v2.12 +a2e59f0e7065404b44dfe92a28aca47ba1378dc4 refs/remotes/origin/v2.13 +a23996fce38ff6ccfbcdc09f1e63f2c4be5ea2ef refs/remotes/origin/v2.2 +a1b71df137e015d44f7e31f7b6d4807253fb7871 refs/remotes/origin/v2.3 +80d452484c5409444b0ec19383faa84bb7a4d351 refs/remotes/origin/v2.4 +3b1dbebabc801c9cf6f0953a4c20b904d444f879 refs/remotes/origin/v2.5 +8de7772cc72daca8e947b79b83fea46214931604 refs/remotes/origin/v2.6 +5b4432439ed72417253f9eec99f2a014636c0362 refs/remotes/origin/v2.7 +f7b499615e14d70ab098a20deb0cdb3889998a1a refs/remotes/origin/v2.8 +914c06fb252b6cc3727d0eedab6736e88a3fcb01 refs/remotes/origin/v2.9 +45fab4087eaaff234227a10cf7845e8b07f28a98 refs/remotes/origin/v3.0 +0991e90375606254087f7bffe0dd15dd910ec62b refs/remotes/origin/void-caster-fix +8ae716ab79e0141537eff420cb7e79b06d14c402 refs/tags/v1.0 +^929fd7e6946255ed84c803d2993f48912de96e15 +1a25b3f8f7455246adf2930e4c857c128c71a240 refs/tags/v1.1 +^bda3b67dc5f9481857aa7a14478bab3293bb376f +ef4345f46c672a74e161f5a8955784658fb10ae8 refs/tags/v1.2 +^8ed2808239f3a6052e7789feeeab34eed39b5c62 +1c32fcbfba8849abedf2a50e675e5f847c20a42d refs/tags/v1.3 +^d2385e8fc6a3008cab96532c99db4c3d57541fc5 +0b8a0c621a2872312b477bed4f8b72a1a3a34d61 refs/tags/v1.4 +^0e6ca5916e2585ca9b778f8304c166b6a36b7e5a +dce23aeae9dcae322670073e6b5a7a22fb740c14 refs/tags/v1.5 +^bb79d7bdc0f48f1a9284af85bf36d392afc28307 +549781cb1c71a91b8bab23e452c5bfed413dee40 refs/tags/v1.6 +^e85e9d82824e88352c9389694ff2130e4a6c5d02 +f21d226f83c5c3db2f3f5c554c35fb8942fd6dcb refs/tags/v1.7 +^e70b2abb6dee27a2889b01f245a2a28e6fcd4b01 +8e8bd7090ba1197117560c7e7f46cd2e9d026424 refs/tags/v1.8 +^c0759976177b92f386856a5d9f2e8d63ef89293a +4da184714d7a3ee298edcabb51497c629108205b refs/tags/v1.8.1 +^121360c6ae0fff0c97c64470508c11a0cc27bf94 +40585804f4e9dbf45b277dd55c19a8026b356eef refs/tags/v2.0.0 +^e33ef9c20d36fe760792c61ccc95ecf1b42cf81d +12006926087bdd34dcbd4db40611be7d5b6ed830 refs/tags/v2.0.0-rc1 +^3c7967111280b0a796986ac2025d0ca201623656 +f74dd5d5a4033e68d9000d3c288d0b57a3fc0105 refs/tags/v2.0.1 +^07de0d8627101be53986e841cd4e21ee38c2498a +a2207c044fdffac6023975df015e73f161082b57 refs/tags/v2.1.0 +^ad9d574c85f1836c57f2f0727ffe997bb8cbfdd7 +cbf3c94e781074f2f094e9a39d7ea86304d69a1d refs/tags/v2.1.1 +^1df91d36cfa997c8987889234304ea5e37cc3e68 +8d298f32f3bf5c1854adeadf7f1ec1c236dd5221 refs/tags/v2.10.0 +^aa304c9c7d725ffb9d10af08a3b34cb372307020 +bcee506ac0b09ea13000484c08ab3e5a41ee0fb2 refs/tags/v2.10.1 +^80dc998efced8ceb2be59756668a7e90e8bef917 +76b3533f96774e555a6e10d6deb9bbafe4970011 refs/tags/v2.10.2 +^0694ec6a15863bff2e0ea5efe07c78de39b9a33c +70a09bf92bff267b3eceee51bee00741bc91367f refs/tags/v2.10.3 +^0bd8896a4010f2d91b2340570c24fa08606ec406 +95ddd6b61bbecd06d00eef8a0e72fa9ffd46631e refs/tags/v2.10.4 +^5b0a6fc2017fcc176545afe3e09c9f9885283242 +8d8aecf4a5579c0e51d07fb93411aa120ae0360c refs/tags/v2.11.0 +^1a917f1852eb7819b671fc3fa862840f4c491a07 +0630807c3070287c716f6be3eacb00b8816b4215 refs/tags/v2.11.1 +^8a099e44b3d5f85b20f05828d919d2332a8de841 +95d943ae0ebdf609bbd650d119fda539509929b6 refs/tags/v2.11.2 +3e9dfa2866941655c56877882565e7577de6fc7b refs/tags/v2.12.0 +2e0815278cb899b20870a67ca8205996ef47e70f refs/tags/v2.12.1 +0c69e1eb2177fa8f8580632c7b1f97fdb606ce8f refs/tags/v2.13.0 +941f45bcb51457884fa1afd6e24a67377d70f75c refs/tags/v2.13.1 +07f30430d4186c2712761f1ffaea50ede63f2b2b refs/tags/v2.13.2 +bd67643652d3800837f1f41549a2a5adbaa3fafe refs/tags/v2.13.3 +c6239a8a1b6871cc0fb5f7af885a02ffd1349f9d refs/tags/v2.13.4 +7c33cdc2d39c7b99a122579f53bc94c8eb3332ff refs/tags/v2.13.5 +a2e59f0e7065404b44dfe92a28aca47ba1378dc4 refs/tags/v2.13.6 +c36cf6254170aa8aef35b65854f518016551d5b8 refs/tags/v2.2.0 +^2a5a5ec0a47c245fbf1bb1a8a90b4c3278e01693 +9a9239eaa52e0e2a16c76894a7f30f19997f0167 refs/tags/v2.2.1 +^86e2ad4f77442c3350f9a2476650da6bee253c52 +8bd683141ccf900aafc3dc76e5efd86f1e8ac541 refs/tags/v2.2.2 +^f117a48ea2fd446d2865826a58d08027d4579cb3 +197ae8a04cec7bf9327d36c780d4fca2a6b51339 refs/tags/v2.2.3 +^8edc147d67ca85a93ed1f53628004528dc36a04d +e4637eb508aa3e41233875f6ce3891d96fbc5d33 refs/tags/v2.2.4 +^9a19306fbf30642ca331d0ec88e7da54a96860f9 +7107ada7cbbd01e76a2a9f3e2ec27b683dcec99b refs/tags/v2.3.0 +^e43e1cc01ae6d4e4e5ba10557a057d7f3d5ece0d +ca8264815ffcf8beda3b206405a92927c722027f refs/tags/v2.4.0 +^00a0aa992953d6482114a0f539a21bb535a16383 +8b7a01d0b8dddf9ff650a6511377cd32a4f1501a refs/tags/v2.4.1 +^e44fcc3c15b41f0720c72832c0b9cd07de819781 +6c383e01bbd4155a29ad280ad7ba7941e05675dd refs/tags/v2.4.2 +^7ec2ddfc95f65d1e986d359466a6c254aa514ef3 +aa56a0e4a40af9ff27dd5b4d283d29bc64c19088 refs/tags/v2.4.3 +^80d452484c5409444b0ec19383faa84bb7a4d351 +014cd12ec1a3258f3bfc6597f371ed46c8e89ccd refs/tags/v2.5.0 +^3b1dbebabc801c9cf6f0953a4c20b904d444f879 +78b2d1991b9e81bbc1a6670ab4af189094e952eb refs/tags/v2.6.0 +^59a2ac2745d8a57ac94c6accced73620d59fb844 +319b99648b94c37e16cec64e0aec6d80557de64f refs/tags/v2.6.0b1 +d46f3322a45cb907777f568bb1377ab1b9457ad8 refs/tags/v2.6.0rc1 +c4a8b5bb9140cdc8c214044d41e2593986f875d0 refs/tags/v2.6.0rc2 +c16da993094988141101ac4d96a9b2c92f9ac714 refs/tags/v2.6.0rc3 +f4bc37b3de4857b9d80c1d85ff9f9e5dceef3dd4 refs/tags/v2.6.1 +^f1abf5d9159b805674197f6bc443592e631c9130 +c7faa0f557df4ee266e6e6dca311cd1474ad2123 refs/tags/v2.6.2 +^8de7772cc72daca8e947b79b83fea46214931604 +40d14c37b4cb8488a241f837ea2e3eb60404f7b7 refs/tags/v2.7.0 +^65e95ea8675ea34bdd566d6461330f25c651e5a8 +c0e8a831c6023be719144e7d10c8ea7c9fb81a58 refs/tags/v2.7.1 +^787d2c88cafa4d07fb38c9519c485a86323cfcf4 +dc756043d5ed7654e48c41d97a64403a847214a7 refs/tags/v2.8.0 +^97976c16fb7652f7faf02d76756666ef87adbe7d +79dfe03e432e2af41bba00add596e6df92099b49 refs/tags/v2.8.1 +^f7b499615e14d70ab098a20deb0cdb3889998a1a +1dad2a58efb1eef1eb9f2e5532dedd3711924810 refs/tags/v2.9.0 +^45f792efdd92da094548e2095d6efdbfa7e536ee +35b51445ba2bf5e67137c04bc26ceaab33e4285f refs/tags/v2.9.1 +^ffa346860b306c9bbfb341aed9c14c067751feb8 +dd9ef9f901f3d49426f87a67666393970a6c9431 refs/tags/v2.9.2 +^914c06fb252b6cc3727d0eedab6736e88a3fcb01 +f0ecf21301c0c24bc78b8b310347c7507d9f41d0 refs/tags/v3.0.0 +^ed5057ded698e305210269dafa57574ecf964483 +fc888f758fde1c37d80f85666060d3f179f6c001 refs/tags/v3.0.0rc1 +df595b16579d847cd019072aa0daec1e566c7ba2 refs/tags/v3.0.0rc2 +5d32ed76c0ea53d689f9cec3d4c152d1b0738e8e refs/tags/v3.0.0rc3 +ea3e33e40dd1cbfa9f885e991386337a0e5b4b66 refs/tags/v3.0.0rc4 +e86205cb2ba070755d582856430c0f83c0af6694 refs/tags/v3.0.1 +^f5fbe867d2d26e4a0a9177a51f6e568868ad3dc8 +e6c503bb0b0c13f76ca0546eca7f8d986039517f refs/tags/v3.0.2 +^45fab4087eaaff234227a10cf7845e8b07f28a98 diff --git a/third_party/CityFlow/extern/pybind11/.gitattributes b/third_party/CityFlow/extern/pybind11/.gitattributes index d611e1496de00063120fad2ef1e7891eca20f7b3..2ab04c210c5a35e64dacbd5a0a509e17b32ae217 100644 --- a/third_party/CityFlow/extern/pybind11/.gitattributes +++ b/third_party/CityFlow/extern/pybind11/.gitattributes @@ -1 +1 @@ -docs/*.svg binary +docs/*.svg binary diff --git a/third_party/CityFlow/extern/pybind11/.github/CODEOWNERS b/third_party/CityFlow/extern/pybind11/.github/CODEOWNERS index 4e2c66902e5946dfd0eb8fc49d4d4190a620eee6..7d0eb645ec02971207e087f623c34aa070b4a644 100644 --- a/third_party/CityFlow/extern/pybind11/.github/CODEOWNERS +++ b/third_party/CityFlow/extern/pybind11/.github/CODEOWNERS @@ -1,9 +1,9 @@ -*.cmake @henryiii -CMakeLists.txt @henryiii -*.yml @henryiii -*.yaml @henryiii -/tools/ @henryiii -/pybind11/ @henryiii -noxfile.py @henryiii -.clang-format @henryiii -.clang-tidy @henryiii +*.cmake @henryiii +CMakeLists.txt @henryiii +*.yml @henryiii +*.yaml @henryiii +/tools/ @henryiii +/pybind11/ @henryiii +noxfile.py @henryiii +.clang-format @henryiii +.clang-tidy @henryiii diff --git a/third_party/CityFlow/extern/pybind11/.github/CONTRIBUTING.md b/third_party/CityFlow/extern/pybind11/.github/CONTRIBUTING.md index f5a08e2d787153809198a86d2a32687bbb7b69e1..476ed8b2eee8a89de542fa6fbde2b740a2cb7528 100644 --- a/third_party/CityFlow/extern/pybind11/.github/CONTRIBUTING.md +++ b/third_party/CityFlow/extern/pybind11/.github/CONTRIBUTING.md @@ -1,388 +1,388 @@ -Thank you for your interest in this project! Please refer to the following -sections on how to contribute code and bug reports. - -### Reporting bugs - -Before submitting a question or bug report, please take a moment of your time -and ensure that your issue isn't already discussed in the project documentation -provided at [pybind11.readthedocs.org][] or in the [issue tracker][]. You can -also check [gitter][] to see if it came up before. - -Assuming that you have identified a previously unknown problem or an important -question, it's essential that you submit a self-contained and minimal piece of -code that reproduces the problem. In other words: no external dependencies, -isolate the function(s) that cause breakage, submit matched and complete C++ -and Python snippets that can be easily compiled and run in isolation; or -ideally make a small PR with a failing test case that can be used as a starting -point. - -## Pull requests - -Contributions are submitted, reviewed, and accepted using GitHub pull requests. -Please refer to [this article][using pull requests] for details and adhere to -the following rules to make the process as smooth as possible: - -* Make a new branch for every feature you're working on. -* Make small and clean pull requests that are easy to review but make sure they - do add value by themselves. -* Add tests for any new functionality and run the test suite (`cmake --build - build --target pytest`) to ensure that no existing features break. -* Please run [`pre-commit`][pre-commit] to check your code matches the - project style. (Note that `gawk` is required.) Use `pre-commit run - --all-files` before committing (or use installed-mode, check pre-commit docs) - to verify your code passes before pushing to save time. -* This project has a strong focus on providing general solutions using a - minimal amount of code, thus small pull requests are greatly preferred. - -### Licensing of contributions - -pybind11 is provided under a BSD-style license that can be found in the -``LICENSE`` file. By using, distributing, or contributing to this project, you -agree to the terms and conditions of this license. - -You are under no obligation whatsoever to provide any bug fixes, patches, or -upgrades to the features, functionality or performance of the source code -("Enhancements") to anyone; however, if you choose to make your Enhancements -available either publicly, or directly to the author of this software, without -imposing a separate written license agreement for such Enhancements, then you -hereby grant the following license: a non-exclusive, royalty-free perpetual -license to install, use, modify, prepare derivative works, incorporate into -other computer software, distribute, and sublicense such enhancements or -derivative works thereof, in binary and source code form. - - -## Development of pybind11 - -### Quick setup - -To setup a quick development environment, use [`nox`](https://nox.thea.codes). -This will allow you to do some common tasks with minimal setup effort, but will -take more time to run and be less flexible than a full development environment. -If you use [`pipx run nox`](https://pipx.pypa.io), you don't even need to -install `nox`. Examples: - -```bash -# List all available sessions -nox -l - -# Run linters -nox -s lint - -# Run tests on Python 3.9 -nox -s tests-3.9 - -# Build and preview docs -nox -s docs -- serve - -# Build SDists and wheels -nox -s build -``` - -### Full setup - -To setup an ideal development environment, run the following commands on a -system with CMake 3.14+: - -```bash -python3 -m venv venv -source venv/bin/activate -pip install -r tests/requirements.txt -cmake -S . -B build -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON -cmake --build build -j4 -``` - -Tips: - -* You can use `virtualenv` (faster, from PyPI) instead of `venv`. -* You can select any name for your environment folder; if it contains "env" it - will be ignored by git. -* If you don't have CMake 3.14+, just add "cmake" to the pip install command. -* You can use `-DPYBIND11_FINDPYTHON=ON` to use FindPython on CMake 3.12+ -* In classic mode, you may need to set `-DPYTHON_EXECUTABLE=/path/to/python`. - FindPython uses `-DPython_ROOT_DIR=/path/to` or - `-DPython_EXECUTABLE=/path/to/python`. - -### Configuration options - -In CMake, configuration options are given with "-D". Options are stored in the -build directory, in the `CMakeCache.txt` file, so they are remembered for each -build directory. Two selections are special - the generator, given with `-G`, -and the compiler, which is selected based on environment variables `CXX` and -similar, or `-DCMAKE_CXX_COMPILER=`. Unlike the others, these cannot be changed -after the initial run. - -The valid options are: - -* `-DCMAKE_BUILD_TYPE`: Release, Debug, MinSizeRel, RelWithDebInfo -* `-DPYBIND11_FINDPYTHON=ON`: Use CMake 3.12+'s FindPython instead of the - classic, deprecated, custom FindPythonLibs -* `-DPYBIND11_NOPYTHON=ON`: Disable all Python searching (disables tests) -* `-DBUILD_TESTING=ON`: Enable the tests -* `-DDOWNLOAD_CATCH=ON`: Download catch to build the C++ tests -* `-DDOWNLOAD_EIGEN=ON`: Download Eigen for the NumPy tests -* `-DPYBIND11_INSTALL=ON/OFF`: Enable the install target (on by default for the - master project) -* `-DUSE_PYTHON_INSTALL_DIR=ON`: Try to install into the python dir - - -
A few standard CMake tricks: (click to expand)

- -* Use `cmake --build build -v` to see the commands used to build the files. -* Use `cmake build -LH` to list the CMake options with help. -* Use `ccmake` if available to see a curses (terminal) gui, or `cmake-gui` for - a completely graphical interface (not present in the PyPI package). -* Use `cmake --build build -j12` to build with 12 cores (for example). -* Use `-G` and the name of a generator to use something different. `cmake - --help` lists the generators available. - - On Unix, setting `CMAKE_GENERATER=Ninja` in your environment will give - you automatic multithreading on all your CMake projects! -* Open the `CMakeLists.txt` with QtCreator to generate for that IDE. -* You can use `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to generate the `.json` file - that some tools expect. - -

- - -To run the tests, you can "build" the check target: - -```bash -cmake --build build --target check -``` - -`--target` can be spelled `-t` in CMake 3.15+. You can also run individual -tests with these targets: - -* `pytest`: Python tests only, using the -[pytest](https://docs.pytest.org/en/stable/) framework -* `cpptest`: C++ tests only -* `test_cmake_build`: Install / subdirectory tests - -If you want to build just a subset of tests, use -`-DPYBIND11_TEST_OVERRIDE="test_callbacks;test_pickling"`. If this is -empty, all tests will be built. Tests are specified without an extension if they need both a .py and -.cpp file. - -You may also pass flags to the `pytest` target by editing `tests/pytest.ini` or -by using the `PYTEST_ADDOPTS` environment variable -(see [`pytest` docs](https://docs.pytest.org/en/2.7.3/customize.html#adding-default-options)). As an example: - -```bash -env PYTEST_ADDOPTS="--capture=no --exitfirst" \ - cmake --build build --target pytest -# Or using abbreviated flags -env PYTEST_ADDOPTS="-s -x" cmake --build build --target pytest -``` - -### Formatting - -All formatting is handled by pre-commit. - -Install with brew (macOS) or pip (any OS): - -```bash -# Any OS -python3 -m pip install pre-commit - -# OR macOS with homebrew: -brew install pre-commit -``` - -Then, you can run it on the items you've added to your staging area, or all -files: - -```bash -pre-commit run -# OR -pre-commit run --all-files -``` - -And, if you want to always use it, you can install it as a git hook (hence the -name, pre-commit): - -```bash -pre-commit install -``` - -### Clang-Format - -As of v2.6.2, pybind11 ships with a [`clang-format`][clang-format] -configuration file at the top level of the repo (the filename is -`.clang-format`). Currently, formatting is NOT applied automatically, but -manually using `clang-format` for newly developed files is highly encouraged. -To check if a file needs formatting: - -```bash -clang-format -style=file --dry-run some.cpp -``` - -The output will show things to be fixed, if any. To actually format the file: - -```bash -clang-format -style=file -i some.cpp -``` - -Note that the `-style-file` option searches the parent directories for the -`.clang-format` file, i.e. the commands above can be run in any subdirectory -of the pybind11 repo. - -### Clang-Tidy - -[`clang-tidy`][clang-tidy] performs deeper static code analyses and is -more complex to run, compared to `clang-format`, but support for `clang-tidy` -is built into the pybind11 CMake configuration. To run `clang-tidy`, the -following recipe should work. Run the `docker` command from the top-level -directory inside your pybind11 git clone. Files will be modified in place, -so you can use git to monitor the changes. - -```bash -docker run --rm -v $PWD:/mounted_pybind11 -it silkeh/clang:15-bullseye -apt-get update && apt-get install -y git python3-dev python3-pytest -cmake -S /mounted_pybind11/ -B build -DCMAKE_CXX_CLANG_TIDY="$(which clang-tidy);--use-color" -DDOWNLOAD_EIGEN=ON -DDOWNLOAD_CATCH=ON -DCMAKE_CXX_STANDARD=17 -cmake --build build -j 2 -``` - -You can add `--fix` to the options list if you want. - -### Include what you use - -To run include what you use, install (`brew install include-what-you-use` on -macOS), then run: - -```bash -cmake -S . -B build-iwyu -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=$(which include-what-you-use) -cmake --build build -``` - -The report is sent to stderr; you can pipe it into a file if you wish. - -### Build recipes - -This builds with the Intel compiler (assuming it is in your path, along with a -recent CMake and Python): - -```bash -python3 -m venv venv -. venv/bin/activate -pip install pytest -cmake -S . -B build-intel -DCMAKE_CXX_COMPILER=$(which icpc) -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON -DPYBIND11_WERROR=ON -``` - -This will test the PGI compilers: - -```bash -docker run --rm -it -v $PWD:/pybind11 nvcr.io/hpc/pgi-compilers:ce -apt-get update && apt-get install -y python3-dev python3-pip python3-pytest -wget -qO- "https://cmake.org/files/v3.18/cmake-3.18.2-Linux-x86_64.tar.gz" | tar --strip-components=1 -xz -C /usr/local -cmake -S pybind11/ -B build -cmake --build build -``` - -### Explanation of the SDist/wheel building design - -> These details below are _only_ for packaging the Python sources from git. The -> SDists and wheels created do not have any extra requirements at all and are -> completely normal. - -The main objective of the packaging system is to create SDists (Python's source -distribution packages) and wheels (Python's binary distribution packages) that -include everything that is needed to work with pybind11, and which can be -installed without any additional dependencies. This is more complex than it -appears: in order to support CMake as a first class language even when using -the PyPI package, they must include the _generated_ CMake files (so as not to -require CMake when installing the `pybind11` package itself). They should also -provide the option to install to the "standard" location -(`/include/pybind11` and `/share/cmake/pybind11`) so they are -easy to find with CMake, but this can cause problems if you are not an -environment or using ``pyproject.toml`` requirements. This was solved by having -two packages; the "nice" pybind11 package that stores the includes and CMake -files inside the package, that you get access to via functions in the package, -and a `pybind11-global` package that can be included via `pybind11[global]` if -you want the more invasive but discoverable file locations. - -If you want to install or package the GitHub source, it is best to have Pip 10 -or newer on Windows, macOS, or Linux (manylinux1 compatible, includes most -distributions). You can then build the SDists, or run any procedure that makes -SDists internally, like making wheels or installing. - - -```bash -# Editable development install example -python3 -m pip install -e . -``` - -Since Pip itself does not have an `sdist` command (it does have `wheel` and -`install`), you may want to use the upcoming `build` package: - -```bash -python3 -m pip install build - -# Normal package -python3 -m build -s . - -# Global extra -PYBIND11_GLOBAL_SDIST=1 python3 -m build -s . -``` - -If you want to use the classic "direct" usage of `python setup.py`, you will -need CMake 3.15+ and either `make` or `ninja` preinstalled (possibly via `pip -install cmake ninja`), since directly running Python on `setup.py` cannot pick -up and install `pyproject.toml` requirements. As long as you have those two -things, though, everything works the way you would expect: - -```bash -# Normal package -python3 setup.py sdist - -# Global extra -PYBIND11_GLOBAL_SDIST=1 python3 setup.py sdist -``` - -A detailed explanation of the build procedure design for developers wanting to -work on or maintain the packaging system is as follows: - -#### 1. Building from the source directory - -When you invoke any `setup.py` command from the source directory, including -`pip wheel .` and `pip install .`, you will activate a full source build. This -is made of the following steps: - -1. If the tool is PEP 518 compliant, like Pip 10+, it will create a temporary - virtual environment and install the build requirements (mostly CMake) into - it. (if you are not on Windows, macOS, or a manylinux compliant system, you - can disable this with `--no-build-isolation` as long as you have CMake 3.15+ - installed) -2. The environment variable `PYBIND11_GLOBAL_SDIST` is checked - if it is set - and truthy, this will be make the accessory `pybind11-global` package, - instead of the normal `pybind11` package. This package is used for - installing the files directly to your environment root directory, using - `pybind11[global]`. -2. `setup.py` reads the version from `pybind11/_version.py` and verifies it - matches `includes/pybind11/detail/common.h`. -3. CMake is run with `-DCMAKE_INSTALL_PREIFX=pybind11`. Since the CMake install - procedure uses only relative paths and is identical on all platforms, these - files are valid as long as they stay in the correct relative position to the - includes. `pybind11/share/cmake/pybind11` has the CMake files, and - `pybind11/include` has the includes. The build directory is discarded. -4. Simpler files are placed in the SDist: `tools/setup_*.py.in`, - `tools/pyproject.toml` (`main` or `global`) -5. The package is created by running the setup function in the - `tools/setup_*.py`. `setup_main.py` fills in Python packages, and - `setup_global.py` fills in only the data/header slots. -6. A context manager cleans up the temporary CMake install directory (even if - an error is thrown). - -### 2. Building from SDist - -Since the SDist has the rendered template files in `tools` along with the -includes and CMake files in the correct locations, the builds are completely -trivial and simple. No extra requirements are required. You can even use Pip 9 -if you really want to. - - -[pre-commit]: https://pre-commit.com -[clang-format]: https://clang.llvm.org/docs/ClangFormat.html -[clang-tidy]: https://clang.llvm.org/extra/clang-tidy/ -[pybind11.readthedocs.org]: http://pybind11.readthedocs.org/en/latest -[issue tracker]: https://github.com/pybind/pybind11/issues -[gitter]: https://gitter.im/pybind/Lobby -[using pull requests]: https://help.github.com/articles/using-pull-requests +Thank you for your interest in this project! Please refer to the following +sections on how to contribute code and bug reports. + +### Reporting bugs + +Before submitting a question or bug report, please take a moment of your time +and ensure that your issue isn't already discussed in the project documentation +provided at [pybind11.readthedocs.org][] or in the [issue tracker][]. You can +also check [gitter][] to see if it came up before. + +Assuming that you have identified a previously unknown problem or an important +question, it's essential that you submit a self-contained and minimal piece of +code that reproduces the problem. In other words: no external dependencies, +isolate the function(s) that cause breakage, submit matched and complete C++ +and Python snippets that can be easily compiled and run in isolation; or +ideally make a small PR with a failing test case that can be used as a starting +point. + +## Pull requests + +Contributions are submitted, reviewed, and accepted using GitHub pull requests. +Please refer to [this article][using pull requests] for details and adhere to +the following rules to make the process as smooth as possible: + +* Make a new branch for every feature you're working on. +* Make small and clean pull requests that are easy to review but make sure they + do add value by themselves. +* Add tests for any new functionality and run the test suite (`cmake --build + build --target pytest`) to ensure that no existing features break. +* Please run [`pre-commit`][pre-commit] to check your code matches the + project style. (Note that `gawk` is required.) Use `pre-commit run + --all-files` before committing (or use installed-mode, check pre-commit docs) + to verify your code passes before pushing to save time. +* This project has a strong focus on providing general solutions using a + minimal amount of code, thus small pull requests are greatly preferred. + +### Licensing of contributions + +pybind11 is provided under a BSD-style license that can be found in the +``LICENSE`` file. By using, distributing, or contributing to this project, you +agree to the terms and conditions of this license. + +You are under no obligation whatsoever to provide any bug fixes, patches, or +upgrades to the features, functionality or performance of the source code +("Enhancements") to anyone; however, if you choose to make your Enhancements +available either publicly, or directly to the author of this software, without +imposing a separate written license agreement for such Enhancements, then you +hereby grant the following license: a non-exclusive, royalty-free perpetual +license to install, use, modify, prepare derivative works, incorporate into +other computer software, distribute, and sublicense such enhancements or +derivative works thereof, in binary and source code form. + + +## Development of pybind11 + +### Quick setup + +To setup a quick development environment, use [`nox`](https://nox.thea.codes). +This will allow you to do some common tasks with minimal setup effort, but will +take more time to run and be less flexible than a full development environment. +If you use [`pipx run nox`](https://pipx.pypa.io), you don't even need to +install `nox`. Examples: + +```bash +# List all available sessions +nox -l + +# Run linters +nox -s lint + +# Run tests on Python 3.9 +nox -s tests-3.9 + +# Build and preview docs +nox -s docs -- serve + +# Build SDists and wheels +nox -s build +``` + +### Full setup + +To setup an ideal development environment, run the following commands on a +system with CMake 3.14+: + +```bash +python3 -m venv venv +source venv/bin/activate +pip install -r tests/requirements.txt +cmake -S . -B build -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON +cmake --build build -j4 +``` + +Tips: + +* You can use `virtualenv` (faster, from PyPI) instead of `venv`. +* You can select any name for your environment folder; if it contains "env" it + will be ignored by git. +* If you don't have CMake 3.14+, just add "cmake" to the pip install command. +* You can use `-DPYBIND11_FINDPYTHON=ON` to use FindPython on CMake 3.12+ +* In classic mode, you may need to set `-DPYTHON_EXECUTABLE=/path/to/python`. + FindPython uses `-DPython_ROOT_DIR=/path/to` or + `-DPython_EXECUTABLE=/path/to/python`. + +### Configuration options + +In CMake, configuration options are given with "-D". Options are stored in the +build directory, in the `CMakeCache.txt` file, so they are remembered for each +build directory. Two selections are special - the generator, given with `-G`, +and the compiler, which is selected based on environment variables `CXX` and +similar, or `-DCMAKE_CXX_COMPILER=`. Unlike the others, these cannot be changed +after the initial run. + +The valid options are: + +* `-DCMAKE_BUILD_TYPE`: Release, Debug, MinSizeRel, RelWithDebInfo +* `-DPYBIND11_FINDPYTHON=ON`: Use CMake 3.12+'s FindPython instead of the + classic, deprecated, custom FindPythonLibs +* `-DPYBIND11_NOPYTHON=ON`: Disable all Python searching (disables tests) +* `-DBUILD_TESTING=ON`: Enable the tests +* `-DDOWNLOAD_CATCH=ON`: Download catch to build the C++ tests +* `-DDOWNLOAD_EIGEN=ON`: Download Eigen for the NumPy tests +* `-DPYBIND11_INSTALL=ON/OFF`: Enable the install target (on by default for the + master project) +* `-DUSE_PYTHON_INSTALL_DIR=ON`: Try to install into the python dir + + +
A few standard CMake tricks: (click to expand)

+ +* Use `cmake --build build -v` to see the commands used to build the files. +* Use `cmake build -LH` to list the CMake options with help. +* Use `ccmake` if available to see a curses (terminal) gui, or `cmake-gui` for + a completely graphical interface (not present in the PyPI package). +* Use `cmake --build build -j12` to build with 12 cores (for example). +* Use `-G` and the name of a generator to use something different. `cmake + --help` lists the generators available. + - On Unix, setting `CMAKE_GENERATER=Ninja` in your environment will give + you automatic multithreading on all your CMake projects! +* Open the `CMakeLists.txt` with QtCreator to generate for that IDE. +* You can use `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to generate the `.json` file + that some tools expect. + +

+ + +To run the tests, you can "build" the check target: + +```bash +cmake --build build --target check +``` + +`--target` can be spelled `-t` in CMake 3.15+. You can also run individual +tests with these targets: + +* `pytest`: Python tests only, using the +[pytest](https://docs.pytest.org/en/stable/) framework +* `cpptest`: C++ tests only +* `test_cmake_build`: Install / subdirectory tests + +If you want to build just a subset of tests, use +`-DPYBIND11_TEST_OVERRIDE="test_callbacks;test_pickling"`. If this is +empty, all tests will be built. Tests are specified without an extension if they need both a .py and +.cpp file. + +You may also pass flags to the `pytest` target by editing `tests/pytest.ini` or +by using the `PYTEST_ADDOPTS` environment variable +(see [`pytest` docs](https://docs.pytest.org/en/2.7.3/customize.html#adding-default-options)). As an example: + +```bash +env PYTEST_ADDOPTS="--capture=no --exitfirst" \ + cmake --build build --target pytest +# Or using abbreviated flags +env PYTEST_ADDOPTS="-s -x" cmake --build build --target pytest +``` + +### Formatting + +All formatting is handled by pre-commit. + +Install with brew (macOS) or pip (any OS): + +```bash +# Any OS +python3 -m pip install pre-commit + +# OR macOS with homebrew: +brew install pre-commit +``` + +Then, you can run it on the items you've added to your staging area, or all +files: + +```bash +pre-commit run +# OR +pre-commit run --all-files +``` + +And, if you want to always use it, you can install it as a git hook (hence the +name, pre-commit): + +```bash +pre-commit install +``` + +### Clang-Format + +As of v2.6.2, pybind11 ships with a [`clang-format`][clang-format] +configuration file at the top level of the repo (the filename is +`.clang-format`). Currently, formatting is NOT applied automatically, but +manually using `clang-format` for newly developed files is highly encouraged. +To check if a file needs formatting: + +```bash +clang-format -style=file --dry-run some.cpp +``` + +The output will show things to be fixed, if any. To actually format the file: + +```bash +clang-format -style=file -i some.cpp +``` + +Note that the `-style-file` option searches the parent directories for the +`.clang-format` file, i.e. the commands above can be run in any subdirectory +of the pybind11 repo. + +### Clang-Tidy + +[`clang-tidy`][clang-tidy] performs deeper static code analyses and is +more complex to run, compared to `clang-format`, but support for `clang-tidy` +is built into the pybind11 CMake configuration. To run `clang-tidy`, the +following recipe should work. Run the `docker` command from the top-level +directory inside your pybind11 git clone. Files will be modified in place, +so you can use git to monitor the changes. + +```bash +docker run --rm -v $PWD:/mounted_pybind11 -it silkeh/clang:15-bullseye +apt-get update && apt-get install -y git python3-dev python3-pytest +cmake -S /mounted_pybind11/ -B build -DCMAKE_CXX_CLANG_TIDY="$(which clang-tidy);--use-color" -DDOWNLOAD_EIGEN=ON -DDOWNLOAD_CATCH=ON -DCMAKE_CXX_STANDARD=17 +cmake --build build -j 2 +``` + +You can add `--fix` to the options list if you want. + +### Include what you use + +To run include what you use, install (`brew install include-what-you-use` on +macOS), then run: + +```bash +cmake -S . -B build-iwyu -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=$(which include-what-you-use) +cmake --build build +``` + +The report is sent to stderr; you can pipe it into a file if you wish. + +### Build recipes + +This builds with the Intel compiler (assuming it is in your path, along with a +recent CMake and Python): + +```bash +python3 -m venv venv +. venv/bin/activate +pip install pytest +cmake -S . -B build-intel -DCMAKE_CXX_COMPILER=$(which icpc) -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON -DPYBIND11_WERROR=ON +``` + +This will test the PGI compilers: + +```bash +docker run --rm -it -v $PWD:/pybind11 nvcr.io/hpc/pgi-compilers:ce +apt-get update && apt-get install -y python3-dev python3-pip python3-pytest +wget -qO- "https://cmake.org/files/v3.18/cmake-3.18.2-Linux-x86_64.tar.gz" | tar --strip-components=1 -xz -C /usr/local +cmake -S pybind11/ -B build +cmake --build build +``` + +### Explanation of the SDist/wheel building design + +> These details below are _only_ for packaging the Python sources from git. The +> SDists and wheels created do not have any extra requirements at all and are +> completely normal. + +The main objective of the packaging system is to create SDists (Python's source +distribution packages) and wheels (Python's binary distribution packages) that +include everything that is needed to work with pybind11, and which can be +installed without any additional dependencies. This is more complex than it +appears: in order to support CMake as a first class language even when using +the PyPI package, they must include the _generated_ CMake files (so as not to +require CMake when installing the `pybind11` package itself). They should also +provide the option to install to the "standard" location +(`/include/pybind11` and `/share/cmake/pybind11`) so they are +easy to find with CMake, but this can cause problems if you are not an +environment or using ``pyproject.toml`` requirements. This was solved by having +two packages; the "nice" pybind11 package that stores the includes and CMake +files inside the package, that you get access to via functions in the package, +and a `pybind11-global` package that can be included via `pybind11[global]` if +you want the more invasive but discoverable file locations. + +If you want to install or package the GitHub source, it is best to have Pip 10 +or newer on Windows, macOS, or Linux (manylinux1 compatible, includes most +distributions). You can then build the SDists, or run any procedure that makes +SDists internally, like making wheels or installing. + + +```bash +# Editable development install example +python3 -m pip install -e . +``` + +Since Pip itself does not have an `sdist` command (it does have `wheel` and +`install`), you may want to use the upcoming `build` package: + +```bash +python3 -m pip install build + +# Normal package +python3 -m build -s . + +# Global extra +PYBIND11_GLOBAL_SDIST=1 python3 -m build -s . +``` + +If you want to use the classic "direct" usage of `python setup.py`, you will +need CMake 3.15+ and either `make` or `ninja` preinstalled (possibly via `pip +install cmake ninja`), since directly running Python on `setup.py` cannot pick +up and install `pyproject.toml` requirements. As long as you have those two +things, though, everything works the way you would expect: + +```bash +# Normal package +python3 setup.py sdist + +# Global extra +PYBIND11_GLOBAL_SDIST=1 python3 setup.py sdist +``` + +A detailed explanation of the build procedure design for developers wanting to +work on or maintain the packaging system is as follows: + +#### 1. Building from the source directory + +When you invoke any `setup.py` command from the source directory, including +`pip wheel .` and `pip install .`, you will activate a full source build. This +is made of the following steps: + +1. If the tool is PEP 518 compliant, like Pip 10+, it will create a temporary + virtual environment and install the build requirements (mostly CMake) into + it. (if you are not on Windows, macOS, or a manylinux compliant system, you + can disable this with `--no-build-isolation` as long as you have CMake 3.15+ + installed) +2. The environment variable `PYBIND11_GLOBAL_SDIST` is checked - if it is set + and truthy, this will be make the accessory `pybind11-global` package, + instead of the normal `pybind11` package. This package is used for + installing the files directly to your environment root directory, using + `pybind11[global]`. +2. `setup.py` reads the version from `pybind11/_version.py` and verifies it + matches `includes/pybind11/detail/common.h`. +3. CMake is run with `-DCMAKE_INSTALL_PREIFX=pybind11`. Since the CMake install + procedure uses only relative paths and is identical on all platforms, these + files are valid as long as they stay in the correct relative position to the + includes. `pybind11/share/cmake/pybind11` has the CMake files, and + `pybind11/include` has the includes. The build directory is discarded. +4. Simpler files are placed in the SDist: `tools/setup_*.py.in`, + `tools/pyproject.toml` (`main` or `global`) +5. The package is created by running the setup function in the + `tools/setup_*.py`. `setup_main.py` fills in Python packages, and + `setup_global.py` fills in only the data/header slots. +6. A context manager cleans up the temporary CMake install directory (even if + an error is thrown). + +### 2. Building from SDist + +Since the SDist has the rendered template files in `tools` along with the +includes and CMake files in the correct locations, the builds are completely +trivial and simple. No extra requirements are required. You can even use Pip 9 +if you really want to. + + +[pre-commit]: https://pre-commit.com +[clang-format]: https://clang.llvm.org/docs/ClangFormat.html +[clang-tidy]: https://clang.llvm.org/extra/clang-tidy/ +[pybind11.readthedocs.org]: http://pybind11.readthedocs.org/en/latest +[issue tracker]: https://github.com/pybind/pybind11/issues +[gitter]: https://gitter.im/pybind/Lobby +[using pull requests]: https://help.github.com/articles/using-pull-requests diff --git a/third_party/CityFlow/extern/pybind11/.github/dependabot.yml b/third_party/CityFlow/extern/pybind11/.github/dependabot.yml index 22c34bd74d4a0dff11e7e5d1e091a4b1e64aac18..df71cea1ffefa658953a0bfb0d58fbf193fac822 100644 --- a/third_party/CityFlow/extern/pybind11/.github/dependabot.yml +++ b/third_party/CityFlow/extern/pybind11/.github/dependabot.yml @@ -1,15 +1,15 @@ -version: 2 -updates: - # Maintain dependencies for GitHub Actions - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" - groups: - actions: - patterns: - - "*" - ignore: - - dependency-name: actions/checkout - versions: - - "<5" +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + groups: + actions: + patterns: + - "*" + ignore: + - dependency-name: actions/checkout + versions: + - "<5" diff --git a/third_party/CityFlow/extern/pybind11/.github/labeler.yml b/third_party/CityFlow/extern/pybind11/.github/labeler.yml index abb0d05aaa3f1ce86f027249b47ce2bc5f7f2e7b..bfc404344b6a58e4a087c104937a64c66df2f0db 100644 --- a/third_party/CityFlow/extern/pybind11/.github/labeler.yml +++ b/third_party/CityFlow/extern/pybind11/.github/labeler.yml @@ -1,8 +1,8 @@ -docs: -- any: - - 'docs/**/*.rst' - - '!docs/changelog.rst' - - '!docs/upgrade.rst' - -ci: -- '.github/workflows/*.yml' +docs: +- any: + - 'docs/**/*.rst' + - '!docs/changelog.rst' + - '!docs/upgrade.rst' + +ci: +- '.github/workflows/*.yml' diff --git a/third_party/CityFlow/extern/pybind11/.github/labeler_merged.yml b/third_party/CityFlow/extern/pybind11/.github/labeler_merged.yml index 2374ad42e4597965da5a0aecb2afeb213da10445..6f20e7a30f58d6772d9f6c3c908de159c56b20c6 100644 --- a/third_party/CityFlow/extern/pybind11/.github/labeler_merged.yml +++ b/third_party/CityFlow/extern/pybind11/.github/labeler_merged.yml @@ -1,3 +1,3 @@ -needs changelog: -- all: - - '!docs/changelog.rst' +needs changelog: +- all: + - '!docs/changelog.rst' diff --git a/third_party/CityFlow/extern/pybind11/.github/pull_request_template.md b/third_party/CityFlow/extern/pybind11/.github/pull_request_template.md index 54b7f5100d3bdfbf58a825347745ae24462c1a3c..d1e0b3b750a2f6c59964d7f1d3a00008f3c2de7c 100644 --- a/third_party/CityFlow/extern/pybind11/.github/pull_request_template.md +++ b/third_party/CityFlow/extern/pybind11/.github/pull_request_template.md @@ -1,19 +1,19 @@ - -## Description - - - - -## Suggested changelog entry: - - - -```rst - -``` - - + +## Description + + + + +## Suggested changelog entry: + + + +```rst + +``` + + diff --git a/third_party/CityFlow/extern/pybind11/.gitignore b/third_party/CityFlow/extern/pybind11/.gitignore index 43d5094c967f4f839be18e71cc398f6af50722ae..3765924c89e4e56c36ef895ff0542951b22ac208 100644 --- a/third_party/CityFlow/extern/pybind11/.gitignore +++ b/third_party/CityFlow/extern/pybind11/.gitignore @@ -1,46 +1,46 @@ -CMakeCache.txt -CMakeFiles -Makefile -cmake_install.cmake -cmake_uninstall.cmake -.DS_Store -*.so -*.pyd -*.dll -*.sln -*.sdf -*.opensdf -*.vcxproj -*.vcxproj.user -*.filters -example.dir -Win32 -x64 -Release -Debug -.vs -CTestTestfile.cmake -Testing -autogen -MANIFEST -/.ninja_* -/*.ninja -/docs/.build -*.py[co] -*.egg-info -*~ -.*.swp -.DS_Store -/dist -/*build* -.cache/ -sosize-*.txt -pybind11Config*.cmake -pybind11Targets.cmake -/*env* -/.vscode -/pybind11/include/* -/pybind11/share/* -/docs/_build/* -.ipynb_checkpoints/ -tests/main.cpp +CMakeCache.txt +CMakeFiles +Makefile +cmake_install.cmake +cmake_uninstall.cmake +.DS_Store +*.so +*.pyd +*.dll +*.sln +*.sdf +*.opensdf +*.vcxproj +*.vcxproj.user +*.filters +example.dir +Win32 +x64 +Release +Debug +.vs +CTestTestfile.cmake +Testing +autogen +MANIFEST +/.ninja_* +/*.ninja +/docs/.build +*.py[co] +*.egg-info +*~ +.*.swp +.DS_Store +/dist +/*build* +.cache/ +sosize-*.txt +pybind11Config*.cmake +pybind11Targets.cmake +/*env* +/.vscode +/pybind11/include/* +/pybind11/share/* +/docs/_build/* +.ipynb_checkpoints/ +tests/main.cpp diff --git a/third_party/CityFlow/extern/pybind11/.pre-commit-config.yaml b/third_party/CityFlow/extern/pybind11/.pre-commit-config.yaml index 2bb47b21cb82b191440a8f5163c1d701fc889857..8aa122afb1b46b4d2c9f7bec8a83aa7685fb5b56 100644 --- a/third_party/CityFlow/extern/pybind11/.pre-commit-config.yaml +++ b/third_party/CityFlow/extern/pybind11/.pre-commit-config.yaml @@ -1,155 +1,155 @@ -# To use: -# -# pre-commit run -a -# -# Or: -# -# pre-commit install # (runs every time you commit in git) -# -# To update this file: -# -# pre-commit autoupdate -# -# See https://github.com/pre-commit/pre-commit - - -ci: - autoupdate_commit_msg: "chore(deps): update pre-commit hooks" - autofix_commit_msg: "style: pre-commit fixes" - autoupdate_schedule: monthly - -# third-party content -exclude: ^tools/JoinPaths.cmake$ - -repos: - -# Clang format the codebase automatically -- repo: https://github.com/pre-commit/mirrors-clang-format - rev: "v17.0.6" - hooks: - - id: clang-format - types_or: [c++, c, cuda] - -# Ruff, the Python auto-correcting linter/formatter written in Rust -- repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.2.0 - hooks: - - id: ruff - args: ["--fix", "--show-fixes"] - - id: ruff-format - -# Check static types with mypy -- repo: https://github.com/pre-commit/mirrors-mypy - rev: "v1.8.0" - hooks: - - id: mypy - args: [] - exclude: ^(tests|docs)/ - additional_dependencies: - - markdown-it-py<3 # Drop this together with dropping Python 3.7 support. - - nox - - rich - - types-setuptools - -# CMake formatting -- repo: https://github.com/cheshirekow/cmake-format-precommit - rev: "v0.6.13" - hooks: - - id: cmake-format - additional_dependencies: [pyyaml] - types: [file] - files: (\.cmake|CMakeLists.txt)(.in)?$ - -# Standard hooks -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: "v4.5.0" - hooks: - - id: check-added-large-files - - id: check-case-conflict - - id: check-docstring-first - - id: check-merge-conflict - - id: check-symlinks - - id: check-toml - - id: check-yaml - - id: debug-statements - - id: end-of-file-fixer - - id: mixed-line-ending - - id: requirements-txt-fixer - - id: trailing-whitespace - -# Also code format the docs -- repo: https://github.com/asottile/blacken-docs - rev: "1.16.0" - hooks: - - id: blacken-docs - additional_dependencies: - - black==23.* - -# Changes tabs to spaces -- repo: https://github.com/Lucas-C/pre-commit-hooks - rev: "v1.5.4" - hooks: - - id: remove-tabs - -# Avoid directional quotes -- repo: https://github.com/sirosen/texthooks - rev: "0.6.4" - hooks: - - id: fix-ligatures - - id: fix-smartquotes - -# Checking for common mistakes -- repo: https://github.com/pre-commit/pygrep-hooks - rev: "v1.10.0" - hooks: - - id: rst-backticks - - id: rst-directive-colons - - id: rst-inline-touching-normal - -# Checks the manifest for missing files (native support) -- repo: https://github.com/mgedmin/check-manifest - rev: "0.49" - hooks: - - id: check-manifest - # This is a slow hook, so only run this if --hook-stage manual is passed - stages: [manual] - additional_dependencies: [cmake, ninja] - -# Check for spelling -# Use tools/codespell_ignore_lines_from_errors.py -# to rebuild .codespell-ignore-lines -- repo: https://github.com/codespell-project/codespell - rev: "v2.2.6" - hooks: - - id: codespell - exclude: ".supp$" - args: ["-x.codespell-ignore-lines", "-Lccompiler"] - -# Check for common shell mistakes -- repo: https://github.com/shellcheck-py/shellcheck-py - rev: "v0.9.0.6" - hooks: - - id: shellcheck - -# Disallow some common capitalization mistakes -- repo: local - hooks: - - id: disallow-caps - name: Disallow improper capitalization - language: pygrep - entry: PyBind|\bNumpy\b|Cmake|CCache|PyTest - exclude: ^\.pre-commit-config.yaml$ - -# PyLint has native support - not always usable, but works for us -- repo: https://github.com/PyCQA/pylint - rev: "v3.0.3" - hooks: - - id: pylint - files: ^pybind11 - -- repo: https://github.com/python-jsonschema/check-jsonschema - rev: 0.28.0 - hooks: - - id: check-readthedocs - - id: check-github-workflows - - id: check-dependabot +# To use: +# +# pre-commit run -a +# +# Or: +# +# pre-commit install # (runs every time you commit in git) +# +# To update this file: +# +# pre-commit autoupdate +# +# See https://github.com/pre-commit/pre-commit + + +ci: + autoupdate_commit_msg: "chore(deps): update pre-commit hooks" + autofix_commit_msg: "style: pre-commit fixes" + autoupdate_schedule: monthly + +# third-party content +exclude: ^tools/JoinPaths.cmake$ + +repos: + +# Clang format the codebase automatically +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: "v17.0.6" + hooks: + - id: clang-format + types_or: [c++, c, cuda] + +# Ruff, the Python auto-correcting linter/formatter written in Rust +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.2.0 + hooks: + - id: ruff + args: ["--fix", "--show-fixes"] + - id: ruff-format + +# Check static types with mypy +- repo: https://github.com/pre-commit/mirrors-mypy + rev: "v1.8.0" + hooks: + - id: mypy + args: [] + exclude: ^(tests|docs)/ + additional_dependencies: + - markdown-it-py<3 # Drop this together with dropping Python 3.7 support. + - nox + - rich + - types-setuptools + +# CMake formatting +- repo: https://github.com/cheshirekow/cmake-format-precommit + rev: "v0.6.13" + hooks: + - id: cmake-format + additional_dependencies: [pyyaml] + types: [file] + files: (\.cmake|CMakeLists.txt)(.in)?$ + +# Standard hooks +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: "v4.5.0" + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-docstring-first + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-yaml + - id: debug-statements + - id: end-of-file-fixer + - id: mixed-line-ending + - id: requirements-txt-fixer + - id: trailing-whitespace + +# Also code format the docs +- repo: https://github.com/asottile/blacken-docs + rev: "1.16.0" + hooks: + - id: blacken-docs + additional_dependencies: + - black==23.* + +# Changes tabs to spaces +- repo: https://github.com/Lucas-C/pre-commit-hooks + rev: "v1.5.4" + hooks: + - id: remove-tabs + +# Avoid directional quotes +- repo: https://github.com/sirosen/texthooks + rev: "0.6.4" + hooks: + - id: fix-ligatures + - id: fix-smartquotes + +# Checking for common mistakes +- repo: https://github.com/pre-commit/pygrep-hooks + rev: "v1.10.0" + hooks: + - id: rst-backticks + - id: rst-directive-colons + - id: rst-inline-touching-normal + +# Checks the manifest for missing files (native support) +- repo: https://github.com/mgedmin/check-manifest + rev: "0.49" + hooks: + - id: check-manifest + # This is a slow hook, so only run this if --hook-stage manual is passed + stages: [manual] + additional_dependencies: [cmake, ninja] + +# Check for spelling +# Use tools/codespell_ignore_lines_from_errors.py +# to rebuild .codespell-ignore-lines +- repo: https://github.com/codespell-project/codespell + rev: "v2.2.6" + hooks: + - id: codespell + exclude: ".supp$" + args: ["-x.codespell-ignore-lines", "-Lccompiler"] + +# Check for common shell mistakes +- repo: https://github.com/shellcheck-py/shellcheck-py + rev: "v0.9.0.6" + hooks: + - id: shellcheck + +# Disallow some common capitalization mistakes +- repo: local + hooks: + - id: disallow-caps + name: Disallow improper capitalization + language: pygrep + entry: PyBind|\bNumpy\b|Cmake|CCache|PyTest + exclude: ^\.pre-commit-config.yaml$ + +# PyLint has native support - not always usable, but works for us +- repo: https://github.com/PyCQA/pylint + rev: "v3.0.3" + hooks: + - id: pylint + files: ^pybind11 + +- repo: https://github.com/python-jsonschema/check-jsonschema + rev: 0.28.0 + hooks: + - id: check-readthedocs + - id: check-github-workflows + - id: check-dependabot diff --git a/third_party/CityFlow/extern/pybind11/.readthedocs.yml b/third_party/CityFlow/extern/pybind11/.readthedocs.yml index a2b802f73d46da4df9699053db6fe33d317313f5..7c78189c23d4a81cb2ab0a9347c5e167064c066b 100644 --- a/third_party/CityFlow/extern/pybind11/.readthedocs.yml +++ b/third_party/CityFlow/extern/pybind11/.readthedocs.yml @@ -1,20 +1,20 @@ -# https://blog.readthedocs.com/migrate-configuration-v2/ - -version: 2 - -build: - os: ubuntu-22.04 - apt_packages: - - librsvg2-bin - tools: - python: "3.11" - -sphinx: - configuration: docs/conf.py - -python: - install: - - requirements: docs/requirements.txt - -formats: - - pdf +# https://blog.readthedocs.com/migrate-configuration-v2/ + +version: 2 + +build: + os: ubuntu-22.04 + apt_packages: + - librsvg2-bin + tools: + python: "3.11" + +sphinx: + configuration: docs/conf.py + +python: + install: + - requirements: docs/requirements.txt + +formats: + - pdf diff --git a/third_party/CityFlow/extern/pybind11/CMakeLists.txt b/third_party/CityFlow/extern/pybind11/CMakeLists.txt index 7db1bf668f765865f244f16f50fe65d2783379e9..6e8e3b6f0c13464ecb603fc70570bb358c37dda1 100644 --- a/third_party/CityFlow/extern/pybind11/CMakeLists.txt +++ b/third_party/CityFlow/extern/pybind11/CMakeLists.txt @@ -1,373 +1,373 @@ -# CMakeLists.txt -- Build system for the pybind11 modules -# -# Copyright (c) 2015 Wenzel Jakob -# -# All rights reserved. Use of this source code is governed by a -# BSD-style license that can be found in the LICENSE file. - -# Propagate this policy (FindPythonInterp removal) so it can be detected later -if(NOT CMAKE_VERSION VERSION_LESS "3.27") - cmake_policy(GET CMP0148 _pybind11_cmp0148) -endif() - -cmake_minimum_required(VERSION 3.5) - -# The `cmake_minimum_required(VERSION 3.5...3.27)` syntax does not work with -# some versions of VS that have a patched CMake 3.11. This forces us to emulate -# the behavior using the following workaround: -if(${CMAKE_VERSION} VERSION_LESS 3.27) - cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) -else() - cmake_policy(VERSION 3.27) -endif() - -if(_pybind11_cmp0148) - cmake_policy(SET CMP0148 ${_pybind11_cmp0148}) - unset(_pybind11_cmp0148) -endif() - -# Avoid infinite recursion if tests include this as a subdirectory -if(DEFINED PYBIND11_MASTER_PROJECT) - return() -endif() - -# Extract project version from source -file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/pybind11/detail/common.h" - pybind11_version_defines REGEX "#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) ") - -foreach(ver ${pybind11_version_defines}) - if(ver MATCHES [[#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$]]) - set(PYBIND11_VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}") - endif() -endforeach() - -if(PYBIND11_VERSION_PATCH MATCHES [[\.([a-zA-Z0-9]+)$]]) - set(pybind11_VERSION_TYPE "${CMAKE_MATCH_1}") -endif() -string(REGEX MATCH "^[0-9]+" PYBIND11_VERSION_PATCH "${PYBIND11_VERSION_PATCH}") - -project( - pybind11 - LANGUAGES CXX - VERSION "${PYBIND11_VERSION_MAJOR}.${PYBIND11_VERSION_MINOR}.${PYBIND11_VERSION_PATCH}") - -# Standard includes -include(GNUInstallDirs) -include(CMakePackageConfigHelpers) -include(CMakeDependentOption) - -if(NOT pybind11_FIND_QUIETLY) - message(STATUS "pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}") -endif() - -# Check if pybind11 is being used directly or via add_subdirectory -if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) - ### Warn if not an out-of-source builds - if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) - set(lines - "You are building in-place. If that is not what you intended to " - "do, you can clean the source directory with:\n" - "rm -r CMakeCache.txt CMakeFiles/ cmake_uninstall.cmake pybind11Config.cmake " - "pybind11ConfigVersion.cmake tests/CMakeFiles/\n") - message(AUTHOR_WARNING ${lines}) - endif() - - set(PYBIND11_MASTER_PROJECT ON) - - if(OSX AND CMAKE_VERSION VERSION_LESS 3.7) - # Bug in macOS CMake < 3.7 is unable to download catch - message(WARNING "CMAKE 3.7+ needed on macOS to download catch, and newer HIGHLY recommended") - elseif(WINDOWS AND CMAKE_VERSION VERSION_LESS 3.8) - # Only tested with 3.8+ in CI. - message(WARNING "CMAKE 3.8+ tested on Windows, previous versions untested") - endif() - - message(STATUS "CMake ${CMAKE_VERSION}") - - if(CMAKE_CXX_STANDARD) - set(CMAKE_CXX_EXTENSIONS OFF) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - endif() - - set(pybind11_system "") - - set_property(GLOBAL PROPERTY USE_FOLDERS ON) - if(CMAKE_VERSION VERSION_LESS "3.18") - set(_pybind11_findpython_default OFF) - else() - set(_pybind11_findpython_default ON) - endif() -else() - set(PYBIND11_MASTER_PROJECT OFF) - set(pybind11_system SYSTEM) - set(_pybind11_findpython_default OFF) -endif() - -# Options -option(PYBIND11_INSTALL "Install pybind11 header files?" ${PYBIND11_MASTER_PROJECT}) -option(PYBIND11_TEST "Build pybind11 test suite?" ${PYBIND11_MASTER_PROJECT}) -option(PYBIND11_NOPYTHON "Disable search for Python" OFF) -option(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION - "To enforce that a handle_type_name<> specialization exists" OFF) -option(PYBIND11_SIMPLE_GIL_MANAGEMENT - "Use simpler GIL management logic that does not support disassociation" OFF) -option(PYBIND11_NUMPY_1_ONLY - "Disable NumPy 2 support to avoid changes to previous pybind11 versions." OFF) -set(PYBIND11_INTERNALS_VERSION - "" - CACHE STRING "Override the ABI version, may be used to enable the unstable ABI.") - -if(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION) - add_compile_definitions(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION) -endif() -if(PYBIND11_SIMPLE_GIL_MANAGEMENT) - add_compile_definitions(PYBIND11_SIMPLE_GIL_MANAGEMENT) -endif() -if(PYBIND11_NUMPY_1_ONLY) - add_compile_definitions(PYBIND11_NUMPY_1_ONLY) -endif() - -cmake_dependent_option( - USE_PYTHON_INCLUDE_DIR - "Install pybind11 headers in Python include directory instead of default installation prefix" - OFF "PYBIND11_INSTALL" OFF) - -cmake_dependent_option(PYBIND11_FINDPYTHON "Force new FindPython" ${_pybind11_findpython_default} - "NOT CMAKE_VERSION VERSION_LESS 3.12" OFF) - -# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests -# (makes transition easier while we support both modes). -if(PYBIND11_MASTER_PROJECT - AND PYBIND11_FINDPYTHON - AND DEFINED PYTHON_EXECUTABLE - AND NOT DEFINED Python_EXECUTABLE) - set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}") -endif() - -# NB: when adding a header don't forget to also add it to setup.py -set(PYBIND11_HEADERS - include/pybind11/detail/class.h - include/pybind11/detail/common.h - include/pybind11/detail/descr.h - include/pybind11/detail/init.h - include/pybind11/detail/internals.h - include/pybind11/detail/type_caster_base.h - include/pybind11/detail/typeid.h - include/pybind11/attr.h - include/pybind11/buffer_info.h - include/pybind11/cast.h - include/pybind11/chrono.h - include/pybind11/common.h - include/pybind11/complex.h - include/pybind11/options.h - include/pybind11/eigen.h - include/pybind11/eigen/common.h - include/pybind11/eigen/matrix.h - include/pybind11/eigen/tensor.h - include/pybind11/embed.h - include/pybind11/eval.h - include/pybind11/gil.h - include/pybind11/gil_safe_call_once.h - include/pybind11/iostream.h - include/pybind11/functional.h - include/pybind11/numpy.h - include/pybind11/operators.h - include/pybind11/pybind11.h - include/pybind11/pytypes.h - include/pybind11/stl.h - include/pybind11/stl_bind.h - include/pybind11/stl/filesystem.h - include/pybind11/type_caster_pyobject_ptr.h - include/pybind11/typing.h) - -# Compare with grep and warn if mismatched -if(PYBIND11_MASTER_PROJECT AND NOT CMAKE_VERSION VERSION_LESS 3.12) - file( - GLOB_RECURSE _pybind11_header_check - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - CONFIGURE_DEPENDS "include/pybind11/*.h") - set(_pybind11_here_only ${PYBIND11_HEADERS}) - set(_pybind11_disk_only ${_pybind11_header_check}) - list(REMOVE_ITEM _pybind11_here_only ${_pybind11_header_check}) - list(REMOVE_ITEM _pybind11_disk_only ${PYBIND11_HEADERS}) - if(_pybind11_here_only) - message(AUTHOR_WARNING "PYBIND11_HEADERS has extra files:" ${_pybind11_here_only}) - endif() - if(_pybind11_disk_only) - message(AUTHOR_WARNING "PYBIND11_HEADERS is missing files:" ${_pybind11_disk_only}) - endif() -endif() - -# CMake 3.12 added list(TRANSFORM PREPEND -# But we can't use it yet -string(REPLACE "include/" "${CMAKE_CURRENT_SOURCE_DIR}/include/" PYBIND11_HEADERS - "${PYBIND11_HEADERS}") - -# Cache variable so this can be used in parent projects -set(pybind11_INCLUDE_DIR - "${CMAKE_CURRENT_LIST_DIR}/include" - CACHE INTERNAL "Directory where pybind11 headers are located") - -# Backward compatible variable for add_subdirectory mode -if(NOT PYBIND11_MASTER_PROJECT) - set(PYBIND11_INCLUDE_DIR - "${pybind11_INCLUDE_DIR}" - CACHE INTERNAL "") -endif() - -# Note: when creating targets, you cannot use if statements at configure time - -# you need generator expressions, because those will be placed in the target file. -# You can also place ifs *in* the Config.in, but not here. - -# This section builds targets, but does *not* touch Python -# Non-IMPORT targets cannot be defined twice -if(NOT TARGET pybind11_headers) - # Build the headers-only target (no Python included): - # (long name used here to keep this from clashing in subdirectory mode) - add_library(pybind11_headers INTERFACE) - add_library(pybind11::pybind11_headers ALIAS pybind11_headers) # to match exported target - add_library(pybind11::headers ALIAS pybind11_headers) # easier to use/remember - - target_include_directories( - pybind11_headers ${pybind11_system} INTERFACE $ - $) - - target_compile_features(pybind11_headers INTERFACE cxx_inheriting_constructors cxx_user_literals - cxx_right_angle_brackets) - if(NOT "${PYBIND11_INTERNALS_VERSION}" STREQUAL "") - target_compile_definitions( - pybind11_headers INTERFACE "PYBIND11_INTERNALS_VERSION=${PYBIND11_INTERNALS_VERSION}") - endif() -else() - # It is invalid to install a target twice, too. - set(PYBIND11_INSTALL OFF) -endif() - -include("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11Common.cmake") -# https://github.com/jtojnar/cmake-snips/#concatenating-paths-when-building-pkg-config-files -# TODO: cmake 3.20 adds the cmake_path() function, which obsoletes this snippet -include("${CMAKE_CURRENT_SOURCE_DIR}/tools/JoinPaths.cmake") - -# Relative directory setting -if(USE_PYTHON_INCLUDE_DIR AND DEFINED Python_INCLUDE_DIRS) - file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${Python_INCLUDE_DIRS}) -elseif(USE_PYTHON_INCLUDE_DIR AND DEFINED PYTHON_INCLUDE_DIR) - file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${PYTHON_INCLUDE_DIRS}) -endif() - -if(PYBIND11_INSTALL) - install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) - set(PYBIND11_CMAKECONFIG_INSTALL_DIR - "${CMAKE_INSTALL_DATAROOTDIR}/cmake/${PROJECT_NAME}" - CACHE STRING "install path for pybind11Config.cmake") - - if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") - set(pybind11_INCLUDEDIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}") - else() - set(pybind11_INCLUDEDIR "\$\{PACKAGE_PREFIX_DIR\}/${CMAKE_INSTALL_INCLUDEDIR}") - endif() - - configure_package_config_file( - tools/${PROJECT_NAME}Config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" - INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) - - if(CMAKE_VERSION VERSION_LESS 3.14) - # Remove CMAKE_SIZEOF_VOID_P from ConfigVersion.cmake since the library does - # not depend on architecture specific settings or libraries. - set(_PYBIND11_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) - unset(CMAKE_SIZEOF_VOID_P) - - write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake - VERSION ${PROJECT_VERSION} - COMPATIBILITY AnyNewerVersion) - - set(CMAKE_SIZEOF_VOID_P ${_PYBIND11_CMAKE_SIZEOF_VOID_P}) - else() - # CMake 3.14+ natively supports header-only libraries - write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake - VERSION ${PROJECT_VERSION} - COMPATIBILITY AnyNewerVersion ARCH_INDEPENDENT) - endif() - - install( - FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake - ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake - tools/FindPythonLibsNew.cmake - tools/pybind11Common.cmake - tools/pybind11Tools.cmake - tools/pybind11NewTools.cmake - DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) - - if(NOT PYBIND11_EXPORT_NAME) - set(PYBIND11_EXPORT_NAME "${PROJECT_NAME}Targets") - endif() - - install(TARGETS pybind11_headers EXPORT "${PYBIND11_EXPORT_NAME}") - - install( - EXPORT "${PYBIND11_EXPORT_NAME}" - NAMESPACE "pybind11::" - DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) - - # pkg-config support - if(NOT prefix_for_pc_file) - if(IS_ABSOLUTE "${CMAKE_INSTALL_DATAROOTDIR}") - set(prefix_for_pc_file "${CMAKE_INSTALL_PREFIX}") - else() - set(pc_datarootdir "${CMAKE_INSTALL_DATAROOTDIR}") - if(CMAKE_VERSION VERSION_LESS 3.20) - set(prefix_for_pc_file "\${pcfiledir}/..") - while(pc_datarootdir) - get_filename_component(pc_datarootdir "${pc_datarootdir}" DIRECTORY) - string(APPEND prefix_for_pc_file "/..") - endwhile() - else() - cmake_path(RELATIVE_PATH CMAKE_INSTALL_PREFIX BASE_DIRECTORY CMAKE_INSTALL_DATAROOTDIR - OUTPUT_VARIABLE prefix_for_pc_file) - endif() - endif() - endif() - join_paths(includedir_for_pc_file "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11.pc.in" - "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc" @ONLY) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc" - DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/") - - # Uninstall target - if(PYBIND11_MASTER_PROJECT) - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake_uninstall.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) - - add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P - ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) - endif() -endif() - -# BUILD_TESTING takes priority, but only if this is the master project -if(PYBIND11_MASTER_PROJECT AND DEFINED BUILD_TESTING) - if(BUILD_TESTING) - if(_pybind11_nopython) - message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode") - else() - add_subdirectory(tests) - endif() - endif() -else() - if(PYBIND11_TEST) - if(_pybind11_nopython) - message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode") - else() - add_subdirectory(tests) - endif() - endif() -endif() - -# Better symmetry with find_package(pybind11 CONFIG) mode. -if(NOT PYBIND11_MASTER_PROJECT) - set(pybind11_FOUND - TRUE - CACHE INTERNAL "True if pybind11 and all required components found on the system") -endif() +# CMakeLists.txt -- Build system for the pybind11 modules +# +# Copyright (c) 2015 Wenzel Jakob +# +# All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +# Propagate this policy (FindPythonInterp removal) so it can be detected later +if(NOT CMAKE_VERSION VERSION_LESS "3.27") + cmake_policy(GET CMP0148 _pybind11_cmp0148) +endif() + +cmake_minimum_required(VERSION 3.5) + +# The `cmake_minimum_required(VERSION 3.5...3.27)` syntax does not work with +# some versions of VS that have a patched CMake 3.11. This forces us to emulate +# the behavior using the following workaround: +if(${CMAKE_VERSION} VERSION_LESS 3.27) + cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) +else() + cmake_policy(VERSION 3.27) +endif() + +if(_pybind11_cmp0148) + cmake_policy(SET CMP0148 ${_pybind11_cmp0148}) + unset(_pybind11_cmp0148) +endif() + +# Avoid infinite recursion if tests include this as a subdirectory +if(DEFINED PYBIND11_MASTER_PROJECT) + return() +endif() + +# Extract project version from source +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/pybind11/detail/common.h" + pybind11_version_defines REGEX "#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) ") + +foreach(ver ${pybind11_version_defines}) + if(ver MATCHES [[#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$]]) + set(PYBIND11_VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}") + endif() +endforeach() + +if(PYBIND11_VERSION_PATCH MATCHES [[\.([a-zA-Z0-9]+)$]]) + set(pybind11_VERSION_TYPE "${CMAKE_MATCH_1}") +endif() +string(REGEX MATCH "^[0-9]+" PYBIND11_VERSION_PATCH "${PYBIND11_VERSION_PATCH}") + +project( + pybind11 + LANGUAGES CXX + VERSION "${PYBIND11_VERSION_MAJOR}.${PYBIND11_VERSION_MINOR}.${PYBIND11_VERSION_PATCH}") + +# Standard includes +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) +include(CMakeDependentOption) + +if(NOT pybind11_FIND_QUIETLY) + message(STATUS "pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}") +endif() + +# Check if pybind11 is being used directly or via add_subdirectory +if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) + ### Warn if not an out-of-source builds + if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) + set(lines + "You are building in-place. If that is not what you intended to " + "do, you can clean the source directory with:\n" + "rm -r CMakeCache.txt CMakeFiles/ cmake_uninstall.cmake pybind11Config.cmake " + "pybind11ConfigVersion.cmake tests/CMakeFiles/\n") + message(AUTHOR_WARNING ${lines}) + endif() + + set(PYBIND11_MASTER_PROJECT ON) + + if(OSX AND CMAKE_VERSION VERSION_LESS 3.7) + # Bug in macOS CMake < 3.7 is unable to download catch + message(WARNING "CMAKE 3.7+ needed on macOS to download catch, and newer HIGHLY recommended") + elseif(WINDOWS AND CMAKE_VERSION VERSION_LESS 3.8) + # Only tested with 3.8+ in CI. + message(WARNING "CMAKE 3.8+ tested on Windows, previous versions untested") + endif() + + message(STATUS "CMake ${CMAKE_VERSION}") + + if(CMAKE_CXX_STANDARD) + set(CMAKE_CXX_EXTENSIONS OFF) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + endif() + + set(pybind11_system "") + + set_property(GLOBAL PROPERTY USE_FOLDERS ON) + if(CMAKE_VERSION VERSION_LESS "3.18") + set(_pybind11_findpython_default OFF) + else() + set(_pybind11_findpython_default ON) + endif() +else() + set(PYBIND11_MASTER_PROJECT OFF) + set(pybind11_system SYSTEM) + set(_pybind11_findpython_default OFF) +endif() + +# Options +option(PYBIND11_INSTALL "Install pybind11 header files?" ${PYBIND11_MASTER_PROJECT}) +option(PYBIND11_TEST "Build pybind11 test suite?" ${PYBIND11_MASTER_PROJECT}) +option(PYBIND11_NOPYTHON "Disable search for Python" OFF) +option(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION + "To enforce that a handle_type_name<> specialization exists" OFF) +option(PYBIND11_SIMPLE_GIL_MANAGEMENT + "Use simpler GIL management logic that does not support disassociation" OFF) +option(PYBIND11_NUMPY_1_ONLY + "Disable NumPy 2 support to avoid changes to previous pybind11 versions." OFF) +set(PYBIND11_INTERNALS_VERSION + "" + CACHE STRING "Override the ABI version, may be used to enable the unstable ABI.") + +if(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION) + add_compile_definitions(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION) +endif() +if(PYBIND11_SIMPLE_GIL_MANAGEMENT) + add_compile_definitions(PYBIND11_SIMPLE_GIL_MANAGEMENT) +endif() +if(PYBIND11_NUMPY_1_ONLY) + add_compile_definitions(PYBIND11_NUMPY_1_ONLY) +endif() + +cmake_dependent_option( + USE_PYTHON_INCLUDE_DIR + "Install pybind11 headers in Python include directory instead of default installation prefix" + OFF "PYBIND11_INSTALL" OFF) + +cmake_dependent_option(PYBIND11_FINDPYTHON "Force new FindPython" ${_pybind11_findpython_default} + "NOT CMAKE_VERSION VERSION_LESS 3.12" OFF) + +# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests +# (makes transition easier while we support both modes). +if(PYBIND11_MASTER_PROJECT + AND PYBIND11_FINDPYTHON + AND DEFINED PYTHON_EXECUTABLE + AND NOT DEFINED Python_EXECUTABLE) + set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}") +endif() + +# NB: when adding a header don't forget to also add it to setup.py +set(PYBIND11_HEADERS + include/pybind11/detail/class.h + include/pybind11/detail/common.h + include/pybind11/detail/descr.h + include/pybind11/detail/init.h + include/pybind11/detail/internals.h + include/pybind11/detail/type_caster_base.h + include/pybind11/detail/typeid.h + include/pybind11/attr.h + include/pybind11/buffer_info.h + include/pybind11/cast.h + include/pybind11/chrono.h + include/pybind11/common.h + include/pybind11/complex.h + include/pybind11/options.h + include/pybind11/eigen.h + include/pybind11/eigen/common.h + include/pybind11/eigen/matrix.h + include/pybind11/eigen/tensor.h + include/pybind11/embed.h + include/pybind11/eval.h + include/pybind11/gil.h + include/pybind11/gil_safe_call_once.h + include/pybind11/iostream.h + include/pybind11/functional.h + include/pybind11/numpy.h + include/pybind11/operators.h + include/pybind11/pybind11.h + include/pybind11/pytypes.h + include/pybind11/stl.h + include/pybind11/stl_bind.h + include/pybind11/stl/filesystem.h + include/pybind11/type_caster_pyobject_ptr.h + include/pybind11/typing.h) + +# Compare with grep and warn if mismatched +if(PYBIND11_MASTER_PROJECT AND NOT CMAKE_VERSION VERSION_LESS 3.12) + file( + GLOB_RECURSE _pybind11_header_check + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + CONFIGURE_DEPENDS "include/pybind11/*.h") + set(_pybind11_here_only ${PYBIND11_HEADERS}) + set(_pybind11_disk_only ${_pybind11_header_check}) + list(REMOVE_ITEM _pybind11_here_only ${_pybind11_header_check}) + list(REMOVE_ITEM _pybind11_disk_only ${PYBIND11_HEADERS}) + if(_pybind11_here_only) + message(AUTHOR_WARNING "PYBIND11_HEADERS has extra files:" ${_pybind11_here_only}) + endif() + if(_pybind11_disk_only) + message(AUTHOR_WARNING "PYBIND11_HEADERS is missing files:" ${_pybind11_disk_only}) + endif() +endif() + +# CMake 3.12 added list(TRANSFORM PREPEND +# But we can't use it yet +string(REPLACE "include/" "${CMAKE_CURRENT_SOURCE_DIR}/include/" PYBIND11_HEADERS + "${PYBIND11_HEADERS}") + +# Cache variable so this can be used in parent projects +set(pybind11_INCLUDE_DIR + "${CMAKE_CURRENT_LIST_DIR}/include" + CACHE INTERNAL "Directory where pybind11 headers are located") + +# Backward compatible variable for add_subdirectory mode +if(NOT PYBIND11_MASTER_PROJECT) + set(PYBIND11_INCLUDE_DIR + "${pybind11_INCLUDE_DIR}" + CACHE INTERNAL "") +endif() + +# Note: when creating targets, you cannot use if statements at configure time - +# you need generator expressions, because those will be placed in the target file. +# You can also place ifs *in* the Config.in, but not here. + +# This section builds targets, but does *not* touch Python +# Non-IMPORT targets cannot be defined twice +if(NOT TARGET pybind11_headers) + # Build the headers-only target (no Python included): + # (long name used here to keep this from clashing in subdirectory mode) + add_library(pybind11_headers INTERFACE) + add_library(pybind11::pybind11_headers ALIAS pybind11_headers) # to match exported target + add_library(pybind11::headers ALIAS pybind11_headers) # easier to use/remember + + target_include_directories( + pybind11_headers ${pybind11_system} INTERFACE $ + $) + + target_compile_features(pybind11_headers INTERFACE cxx_inheriting_constructors cxx_user_literals + cxx_right_angle_brackets) + if(NOT "${PYBIND11_INTERNALS_VERSION}" STREQUAL "") + target_compile_definitions( + pybind11_headers INTERFACE "PYBIND11_INTERNALS_VERSION=${PYBIND11_INTERNALS_VERSION}") + endif() +else() + # It is invalid to install a target twice, too. + set(PYBIND11_INSTALL OFF) +endif() + +include("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11Common.cmake") +# https://github.com/jtojnar/cmake-snips/#concatenating-paths-when-building-pkg-config-files +# TODO: cmake 3.20 adds the cmake_path() function, which obsoletes this snippet +include("${CMAKE_CURRENT_SOURCE_DIR}/tools/JoinPaths.cmake") + +# Relative directory setting +if(USE_PYTHON_INCLUDE_DIR AND DEFINED Python_INCLUDE_DIRS) + file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${Python_INCLUDE_DIRS}) +elseif(USE_PYTHON_INCLUDE_DIR AND DEFINED PYTHON_INCLUDE_DIR) + file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${PYTHON_INCLUDE_DIRS}) +endif() + +if(PYBIND11_INSTALL) + install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + set(PYBIND11_CMAKECONFIG_INSTALL_DIR + "${CMAKE_INSTALL_DATAROOTDIR}/cmake/${PROJECT_NAME}" + CACHE STRING "install path for pybind11Config.cmake") + + if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") + set(pybind11_INCLUDEDIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}") + else() + set(pybind11_INCLUDEDIR "\$\{PACKAGE_PREFIX_DIR\}/${CMAKE_INSTALL_INCLUDEDIR}") + endif() + + configure_package_config_file( + tools/${PROJECT_NAME}Config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) + + if(CMAKE_VERSION VERSION_LESS 3.14) + # Remove CMAKE_SIZEOF_VOID_P from ConfigVersion.cmake since the library does + # not depend on architecture specific settings or libraries. + set(_PYBIND11_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) + unset(CMAKE_SIZEOF_VOID_P) + + write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY AnyNewerVersion) + + set(CMAKE_SIZEOF_VOID_P ${_PYBIND11_CMAKE_SIZEOF_VOID_P}) + else() + # CMake 3.14+ natively supports header-only libraries + write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY AnyNewerVersion ARCH_INDEPENDENT) + endif() + + install( + FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + tools/FindPythonLibsNew.cmake + tools/pybind11Common.cmake + tools/pybind11Tools.cmake + tools/pybind11NewTools.cmake + DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) + + if(NOT PYBIND11_EXPORT_NAME) + set(PYBIND11_EXPORT_NAME "${PROJECT_NAME}Targets") + endif() + + install(TARGETS pybind11_headers EXPORT "${PYBIND11_EXPORT_NAME}") + + install( + EXPORT "${PYBIND11_EXPORT_NAME}" + NAMESPACE "pybind11::" + DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) + + # pkg-config support + if(NOT prefix_for_pc_file) + if(IS_ABSOLUTE "${CMAKE_INSTALL_DATAROOTDIR}") + set(prefix_for_pc_file "${CMAKE_INSTALL_PREFIX}") + else() + set(pc_datarootdir "${CMAKE_INSTALL_DATAROOTDIR}") + if(CMAKE_VERSION VERSION_LESS 3.20) + set(prefix_for_pc_file "\${pcfiledir}/..") + while(pc_datarootdir) + get_filename_component(pc_datarootdir "${pc_datarootdir}" DIRECTORY) + string(APPEND prefix_for_pc_file "/..") + endwhile() + else() + cmake_path(RELATIVE_PATH CMAKE_INSTALL_PREFIX BASE_DIRECTORY CMAKE_INSTALL_DATAROOTDIR + OUTPUT_VARIABLE prefix_for_pc_file) + endif() + endif() + endif() + join_paths(includedir_for_pc_file "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}") + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11.pc.in" + "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc" @ONLY) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc" + DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/") + + # Uninstall target + if(PYBIND11_MASTER_PROJECT) + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) + + add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P + ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) + endif() +endif() + +# BUILD_TESTING takes priority, but only if this is the master project +if(PYBIND11_MASTER_PROJECT AND DEFINED BUILD_TESTING) + if(BUILD_TESTING) + if(_pybind11_nopython) + message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode") + else() + add_subdirectory(tests) + endif() + endif() +else() + if(PYBIND11_TEST) + if(_pybind11_nopython) + message(FATAL_ERROR "Cannot activate tests in NOPYTHON mode") + else() + add_subdirectory(tests) + endif() + endif() +endif() + +# Better symmetry with find_package(pybind11 CONFIG) mode. +if(NOT PYBIND11_MASTER_PROJECT) + set(pybind11_FOUND + TRUE + CACHE INTERNAL "True if pybind11 and all required components found on the system") +endif() diff --git a/third_party/CityFlow/extern/pybind11/LICENSE b/third_party/CityFlow/extern/pybind11/LICENSE index e466b0dfda14f3a7c8ece512937eb99c8b7b6d68..46b7deda3da0daac2b9c2547237aa38cf449f6b1 100644 --- a/third_party/CityFlow/extern/pybind11/LICENSE +++ b/third_party/CityFlow/extern/pybind11/LICENSE @@ -1,29 +1,29 @@ -Copyright (c) 2016 Wenzel Jakob , All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of -external contributions to this project including patches, pull requests, etc. +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. diff --git a/third_party/CityFlow/extern/pybind11/MANIFEST.in b/third_party/CityFlow/extern/pybind11/MANIFEST.in index 7ce83c5527ccd0685ac8238c083972533872a062..3415ea0c0bb33ba50b1fdaaf0a8947a407562b54 100644 --- a/third_party/CityFlow/extern/pybind11/MANIFEST.in +++ b/third_party/CityFlow/extern/pybind11/MANIFEST.in @@ -1,6 +1,6 @@ -prune tests -recursive-include pybind11/include/pybind11 *.h -recursive-include pybind11 *.py -recursive-include pybind11 py.typed -include pybind11/share/cmake/pybind11/*.cmake -include LICENSE README.rst SECURITY.md pyproject.toml setup.py setup.cfg +prune tests +recursive-include pybind11/include/pybind11 *.h +recursive-include pybind11 *.py +recursive-include pybind11 py.typed +include pybind11/share/cmake/pybind11/*.cmake +include LICENSE README.rst SECURITY.md pyproject.toml setup.py setup.cfg diff --git a/third_party/CityFlow/extern/pybind11/README.rst b/third_party/CityFlow/extern/pybind11/README.rst index 4032f97a57c3bf17d49fe8e60b82f22a9ccacc4f..2f695990196c649eb5e926f92d2bf8a13fa71ad3 100644 --- a/third_party/CityFlow/extern/pybind11/README.rst +++ b/third_party/CityFlow/extern/pybind11/README.rst @@ -1,181 +1,181 @@ -.. figure:: https://github.com/pybind/pybind11/raw/master/docs/pybind11-logo.png - :alt: pybind11 logo - -**pybind11 — Seamless operability between C++11 and Python** - -|Latest Documentation Status| |Stable Documentation Status| |Gitter chat| |GitHub Discussions| |CI| |Build status| - -|Repology| |PyPI package| |Conda-forge| |Python Versions| - -`Setuptools example `_ -• `Scikit-build example `_ -• `CMake example `_ - -.. start - - -**pybind11** is a lightweight header-only library that exposes C++ types -in Python and vice versa, mainly to create Python bindings of existing -C++ code. Its goals and syntax are similar to the excellent -`Boost.Python `_ -library by David Abrahams: to minimize boilerplate code in traditional -extension modules by inferring type information using compile-time -introspection. - -The main issue with Boost.Python—and the reason for creating such a -similar project—is Boost. Boost is an enormously large and complex suite -of utility libraries that works with almost every C++ compiler in -existence. This compatibility has its cost: arcane template tricks and -workarounds are necessary to support the oldest and buggiest of compiler -specimens. Now that C++11-compatible compilers are widely available, -this heavy machinery has become an excessively large and unnecessary -dependency. - -Think of this library as a tiny self-contained version of Boost.Python -with everything stripped away that isn't relevant for binding -generation. Without comments, the core header files only require ~4K -lines of code and depend on Python (3.6+, or PyPy) and the C++ -standard library. This compact implementation was possible thanks to -some C++11 language features (specifically: tuples, lambda functions and -variadic templates). Since its creation, this library has grown beyond -Boost.Python in many ways, leading to dramatically simpler binding code in many -common situations. - -Tutorial and reference documentation is provided at -`pybind11.readthedocs.io `_. -A PDF version of the manual is available -`here `_. -And the source code is always available at -`github.com/pybind/pybind11 `_. - - -Core features -------------- - - -pybind11 can map the following core C++ features to Python: - -- Functions accepting and returning custom data structures per value, - reference, or pointer -- Instance methods and static methods -- Overloaded functions -- Instance attributes and static attributes -- Arbitrary exception types -- Enumerations -- Callbacks -- Iterators and ranges -- Custom operators -- Single and multiple inheritance -- STL data structures -- Smart pointers with reference counting like ``std::shared_ptr`` -- Internal references with correct reference counting -- C++ classes with virtual (and pure virtual) methods can be extended - in Python -- Integrated NumPy support (NumPy 2 requires pybind11 2.12+) - -Goodies -------- - -In addition to the core functionality, pybind11 provides some extra -goodies: - -- Python 3.6+, and PyPy3 7.3 are supported with an implementation-agnostic - interface (pybind11 2.9 was the last version to support Python 2 and 3.5). - -- It is possible to bind C++11 lambda functions with captured - variables. The lambda capture data is stored inside the resulting - Python function object. - -- pybind11 uses C++11 move constructors and move assignment operators - whenever possible to efficiently transfer custom data types. - -- It's easy to expose the internal storage of custom data types through - Pythons' buffer protocols. This is handy e.g. for fast conversion - between C++ matrix classes like Eigen and NumPy without expensive - copy operations. - -- pybind11 can automatically vectorize functions so that they are - transparently applied to all entries of one or more NumPy array - arguments. - -- Python's slice-based access and assignment operations can be - supported with just a few lines of code. - -- Everything is contained in just a few header files; there is no need - to link against any additional libraries. - -- Binaries are generally smaller by a factor of at least 2 compared to - equivalent bindings generated by Boost.Python. A recent pybind11 - conversion of PyRosetta, an enormous Boost.Python binding project, - `reported `_ - a binary size reduction of **5.4x** and compile time reduction by - **5.8x**. - -- Function signatures are precomputed at compile time (using - ``constexpr``), leading to smaller binaries. - -- With little extra effort, C++ types can be pickled and unpickled - similar to regular Python objects. - -Supported compilers -------------------- - -1. Clang/LLVM 3.3 or newer (for Apple Xcode's clang, this is 5.0.0 or - newer) -2. GCC 4.8 or newer -3. Microsoft Visual Studio 2017 or newer -4. Intel classic C++ compiler 18 or newer (ICC 20.2 tested in CI) -5. Cygwin/GCC (previously tested on 2.5.1) -6. NVCC (CUDA 11.0 tested in CI) -7. NVIDIA PGI (20.9 tested in CI) - -About ------ - -This project was created by `Wenzel -Jakob `_. Significant features and/or -improvements to the code were contributed by Jonas Adler, Lori A. Burns, -Sylvain Corlay, Eric Cousineau, Aaron Gokaslan, Ralf Grosse-Kunstleve, Trent Houliston, Axel -Huebl, @hulucc, Yannick Jadoul, Sergey Lyskov, Johan Mabille, Tomasz Miąsko, -Dean Moldovan, Ben Pritchard, Jason Rhinelander, Boris Schäling, Pim -Schellart, Henry Schreiner, Ivan Smirnov, Boris Staletic, and Patrick Stewart. - -We thank Google for a generous financial contribution to the continuous -integration infrastructure used by this project. - - -Contributing -~~~~~~~~~~~~ - -See the `contributing -guide `_ -for information on building and contributing to pybind11. - -License -~~~~~~~ - -pybind11 is provided under a BSD-style license that can be found in the -`LICENSE `_ -file. By using, distributing, or contributing to this project, you agree -to the terms and conditions of this license. - -.. |Latest Documentation Status| image:: https://readthedocs.org/projects/pybind11/badge?version=latest - :target: http://pybind11.readthedocs.org/en/latest -.. |Stable Documentation Status| image:: https://img.shields.io/badge/docs-stable-blue.svg - :target: http://pybind11.readthedocs.org/en/stable -.. |Gitter chat| image:: https://img.shields.io/gitter/room/gitterHQ/gitter.svg - :target: https://gitter.im/pybind/Lobby -.. |CI| image:: https://github.com/pybind/pybind11/workflows/CI/badge.svg - :target: https://github.com/pybind/pybind11/actions -.. |Build status| image:: https://ci.appveyor.com/api/projects/status/riaj54pn4h08xy40?svg=true - :target: https://ci.appveyor.com/project/wjakob/pybind11 -.. |PyPI package| image:: https://img.shields.io/pypi/v/pybind11.svg - :target: https://pypi.org/project/pybind11/ -.. |Conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pybind11.svg - :target: https://github.com/conda-forge/pybind11-feedstock -.. |Repology| image:: https://repology.org/badge/latest-versions/python:pybind11.svg - :target: https://repology.org/project/python:pybind11/versions -.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pybind11.svg - :target: https://pypi.org/project/pybind11/ -.. |GitHub Discussions| image:: https://img.shields.io/static/v1?label=Discussions&message=Ask&color=blue&logo=github - :target: https://github.com/pybind/pybind11/discussions +.. figure:: https://github.com/pybind/pybind11/raw/master/docs/pybind11-logo.png + :alt: pybind11 logo + +**pybind11 — Seamless operability between C++11 and Python** + +|Latest Documentation Status| |Stable Documentation Status| |Gitter chat| |GitHub Discussions| |CI| |Build status| + +|Repology| |PyPI package| |Conda-forge| |Python Versions| + +`Setuptools example `_ +• `Scikit-build example `_ +• `CMake example `_ + +.. start + + +**pybind11** is a lightweight header-only library that exposes C++ types +in Python and vice versa, mainly to create Python bindings of existing +C++ code. Its goals and syntax are similar to the excellent +`Boost.Python `_ +library by David Abrahams: to minimize boilerplate code in traditional +extension modules by inferring type information using compile-time +introspection. + +The main issue with Boost.Python—and the reason for creating such a +similar project—is Boost. Boost is an enormously large and complex suite +of utility libraries that works with almost every C++ compiler in +existence. This compatibility has its cost: arcane template tricks and +workarounds are necessary to support the oldest and buggiest of compiler +specimens. Now that C++11-compatible compilers are widely available, +this heavy machinery has become an excessively large and unnecessary +dependency. + +Think of this library as a tiny self-contained version of Boost.Python +with everything stripped away that isn't relevant for binding +generation. Without comments, the core header files only require ~4K +lines of code and depend on Python (3.6+, or PyPy) and the C++ +standard library. This compact implementation was possible thanks to +some C++11 language features (specifically: tuples, lambda functions and +variadic templates). Since its creation, this library has grown beyond +Boost.Python in many ways, leading to dramatically simpler binding code in many +common situations. + +Tutorial and reference documentation is provided at +`pybind11.readthedocs.io `_. +A PDF version of the manual is available +`here `_. +And the source code is always available at +`github.com/pybind/pybind11 `_. + + +Core features +------------- + + +pybind11 can map the following core C++ features to Python: + +- Functions accepting and returning custom data structures per value, + reference, or pointer +- Instance methods and static methods +- Overloaded functions +- Instance attributes and static attributes +- Arbitrary exception types +- Enumerations +- Callbacks +- Iterators and ranges +- Custom operators +- Single and multiple inheritance +- STL data structures +- Smart pointers with reference counting like ``std::shared_ptr`` +- Internal references with correct reference counting +- C++ classes with virtual (and pure virtual) methods can be extended + in Python +- Integrated NumPy support (NumPy 2 requires pybind11 2.12+) + +Goodies +------- + +In addition to the core functionality, pybind11 provides some extra +goodies: + +- Python 3.6+, and PyPy3 7.3 are supported with an implementation-agnostic + interface (pybind11 2.9 was the last version to support Python 2 and 3.5). + +- It is possible to bind C++11 lambda functions with captured + variables. The lambda capture data is stored inside the resulting + Python function object. + +- pybind11 uses C++11 move constructors and move assignment operators + whenever possible to efficiently transfer custom data types. + +- It's easy to expose the internal storage of custom data types through + Pythons' buffer protocols. This is handy e.g. for fast conversion + between C++ matrix classes like Eigen and NumPy without expensive + copy operations. + +- pybind11 can automatically vectorize functions so that they are + transparently applied to all entries of one or more NumPy array + arguments. + +- Python's slice-based access and assignment operations can be + supported with just a few lines of code. + +- Everything is contained in just a few header files; there is no need + to link against any additional libraries. + +- Binaries are generally smaller by a factor of at least 2 compared to + equivalent bindings generated by Boost.Python. A recent pybind11 + conversion of PyRosetta, an enormous Boost.Python binding project, + `reported `_ + a binary size reduction of **5.4x** and compile time reduction by + **5.8x**. + +- Function signatures are precomputed at compile time (using + ``constexpr``), leading to smaller binaries. + +- With little extra effort, C++ types can be pickled and unpickled + similar to regular Python objects. + +Supported compilers +------------------- + +1. Clang/LLVM 3.3 or newer (for Apple Xcode's clang, this is 5.0.0 or + newer) +2. GCC 4.8 or newer +3. Microsoft Visual Studio 2017 or newer +4. Intel classic C++ compiler 18 or newer (ICC 20.2 tested in CI) +5. Cygwin/GCC (previously tested on 2.5.1) +6. NVCC (CUDA 11.0 tested in CI) +7. NVIDIA PGI (20.9 tested in CI) + +About +----- + +This project was created by `Wenzel +Jakob `_. Significant features and/or +improvements to the code were contributed by Jonas Adler, Lori A. Burns, +Sylvain Corlay, Eric Cousineau, Aaron Gokaslan, Ralf Grosse-Kunstleve, Trent Houliston, Axel +Huebl, @hulucc, Yannick Jadoul, Sergey Lyskov, Johan Mabille, Tomasz Miąsko, +Dean Moldovan, Ben Pritchard, Jason Rhinelander, Boris Schäling, Pim +Schellart, Henry Schreiner, Ivan Smirnov, Boris Staletic, and Patrick Stewart. + +We thank Google for a generous financial contribution to the continuous +integration infrastructure used by this project. + + +Contributing +~~~~~~~~~~~~ + +See the `contributing +guide `_ +for information on building and contributing to pybind11. + +License +~~~~~~~ + +pybind11 is provided under a BSD-style license that can be found in the +`LICENSE `_ +file. By using, distributing, or contributing to this project, you agree +to the terms and conditions of this license. + +.. |Latest Documentation Status| image:: https://readthedocs.org/projects/pybind11/badge?version=latest + :target: http://pybind11.readthedocs.org/en/latest +.. |Stable Documentation Status| image:: https://img.shields.io/badge/docs-stable-blue.svg + :target: http://pybind11.readthedocs.org/en/stable +.. |Gitter chat| image:: https://img.shields.io/gitter/room/gitterHQ/gitter.svg + :target: https://gitter.im/pybind/Lobby +.. |CI| image:: https://github.com/pybind/pybind11/workflows/CI/badge.svg + :target: https://github.com/pybind/pybind11/actions +.. |Build status| image:: https://ci.appveyor.com/api/projects/status/riaj54pn4h08xy40?svg=true + :target: https://ci.appveyor.com/project/wjakob/pybind11 +.. |PyPI package| image:: https://img.shields.io/pypi/v/pybind11.svg + :target: https://pypi.org/project/pybind11/ +.. |Conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pybind11.svg + :target: https://github.com/conda-forge/pybind11-feedstock +.. |Repology| image:: https://repology.org/badge/latest-versions/python:pybind11.svg + :target: https://repology.org/project/python:pybind11/versions +.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pybind11.svg + :target: https://pypi.org/project/pybind11/ +.. |GitHub Discussions| image:: https://img.shields.io/static/v1?label=Discussions&message=Ask&color=blue&logo=github + :target: https://github.com/pybind/pybind11/discussions diff --git a/third_party/CityFlow/extern/pybind11/SECURITY.md b/third_party/CityFlow/extern/pybind11/SECURITY.md index 3d74611f2db85d7981287ad4314e2a868a1280d5..ce0b96640f6a12db26cc23473c7ed917f1c49a20 100644 --- a/third_party/CityFlow/extern/pybind11/SECURITY.md +++ b/third_party/CityFlow/extern/pybind11/SECURITY.md @@ -1,13 +1,13 @@ -# Security Policy - -## Supported Versions - -Security updates are applied only to the latest release. - -## Reporting a Vulnerability - -If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. - -Please disclose it at [security advisory](https://github.com/pybind/pybind11/security/advisories/new). - -This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please disclose it at [security advisory](https://github.com/pybind/pybind11/security/advisories/new). + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/third_party/CityFlow/extern/pybind11/docs/Doxyfile b/third_party/CityFlow/extern/pybind11/docs/Doxyfile index 09138db364a83888b793dafd7bcc680458e6570f..59bd9f60a0f7a12e4e274cc419eba88561fb5752 100644 --- a/third_party/CityFlow/extern/pybind11/docs/Doxyfile +++ b/third_party/CityFlow/extern/pybind11/docs/Doxyfile @@ -1,21 +1,21 @@ -PROJECT_NAME = pybind11 -INPUT = ../include/pybind11/ -RECURSIVE = YES - -GENERATE_HTML = NO -GENERATE_LATEX = NO -GENERATE_XML = YES -XML_OUTPUT = .build/doxygenxml -XML_PROGRAMLISTING = YES - -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = YES -EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION - -ALIASES = "rst=\verbatim embed:rst" -ALIASES += "endrst=\endverbatim" - -QUIET = YES -WARNINGS = YES -WARN_IF_UNDOCUMENTED = NO -PREDEFINED = PYBIND11_NOINLINE +PROJECT_NAME = pybind11 +INPUT = ../include/pybind11/ +RECURSIVE = YES + +GENERATE_HTML = NO +GENERATE_LATEX = NO +GENERATE_XML = YES +XML_OUTPUT = .build/doxygenxml +XML_PROGRAMLISTING = YES + +MACRO_EXPANSION = YES +EXPAND_ONLY_PREDEF = YES +EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION + +ALIASES = "rst=\verbatim embed:rst" +ALIASES += "endrst=\endverbatim" + +QUIET = YES +WARNINGS = YES +WARN_IF_UNDOCUMENTED = NO +PREDEFINED = PYBIND11_NOINLINE diff --git a/third_party/CityFlow/extern/pybind11/docs/basics.rst b/third_party/CityFlow/extern/pybind11/docs/basics.rst index e9b24c7fa72bf51de10d991e988e12632038a3a2..47b605d3d51a442c9a8aa1c19698f3673fb500ae 100644 --- a/third_party/CityFlow/extern/pybind11/docs/basics.rst +++ b/third_party/CityFlow/extern/pybind11/docs/basics.rst @@ -1,307 +1,307 @@ -.. _basics: - -First steps -########### - -This sections demonstrates the basic features of pybind11. Before getting -started, make sure that development environment is set up to compile the -included set of test cases. - - -Compiling the test cases -======================== - -Linux/macOS ------------ - -On Linux you'll need to install the **python-dev** or **python3-dev** packages as -well as **cmake**. On macOS, the included python version works out of the box, -but **cmake** must still be installed. - -After installing the prerequisites, run - -.. code-block:: bash - - mkdir build - cd build - cmake .. - make check -j 4 - -The last line will both compile and run the tests. - -Windows -------- - -On Windows, only **Visual Studio 2017** and newer are supported. - -.. Note:: - - To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag - ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When - building with Visual Studio 2019, this is not strictly necessary, but still advised. - -.. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017 - -To compile and run the tests: - -.. code-block:: batch - - mkdir build - cd build - cmake .. - cmake --build . --config Release --target check - -This will create a Visual Studio project, compile and run the target, all from the -command line. - -.. Note:: - - If all tests fail, make sure that the Python binary and the testcases are compiled - for the same processor type and bitness (i.e. either **i386** or **x86_64**). You - can specify **x86_64** as the target architecture for the generated Visual Studio - project using ``cmake -A x64 ..``. - -.. seealso:: - - Advanced users who are already familiar with Boost.Python may want to skip - the tutorial and look at the test cases in the :file:`tests` directory, - which exercise all features of pybind11. - -Header and namespace conventions -================================ - -For brevity, all code examples assume that the following two lines are present: - -.. code-block:: cpp - - #include - - namespace py = pybind11; - -Some features may require additional headers, but those will be specified as needed. - -.. _simple_example: - -Creating bindings for a simple function -======================================= - -Let's start by creating Python bindings for an extremely simple function, which -adds two numbers and returns their result: - -.. code-block:: cpp - - int add(int i, int j) { - return i + j; - } - -For simplicity [#f1]_, we'll put both this function and the binding code into -a file named :file:`example.cpp` with the following contents: - -.. code-block:: cpp - - #include - - int add(int i, int j) { - return i + j; - } - - PYBIND11_MODULE(example, m) { - m.doc() = "pybind11 example plugin"; // optional module docstring - - m.def("add", &add, "A function that adds two numbers"); - } - -.. [#f1] In practice, implementation and binding code will generally be located - in separate files. - -The :func:`PYBIND11_MODULE` macro creates a function that will be called when an -``import`` statement is issued from within Python. The module name (``example``) -is given as the first macro argument (it should not be in quotes). The second -argument (``m``) defines a variable of type :class:`py::module_ ` which -is the main interface for creating bindings. The method :func:`module_::def` -generates binding code that exposes the ``add()`` function to Python. - -.. note:: - - Notice how little code was needed to expose our function to Python: all - details regarding the function's parameters and return value were - automatically inferred using template metaprogramming. This overall - approach and the used syntax are borrowed from Boost.Python, though the - underlying implementation is very different. - -pybind11 is a header-only library, hence it is not necessary to link against -any special libraries and there are no intermediate (magic) translation steps. -On Linux, the above example can be compiled using the following command: - -.. code-block:: bash - - $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) - -.. note:: - - If you used :ref:`include_as_a_submodule` to get the pybind11 source, then - use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of - ``$(python3 -m pybind11 --includes)`` in the above compilation, as - explained in :ref:`building_manually`. - -For more details on the required compiler flags on Linux and macOS, see -:ref:`building_manually`. For complete cross-platform compilation instructions, -refer to the :ref:`compiling` page. - -The `python_example`_ and `cmake_example`_ repositories are also a good place -to start. They are both complete project examples with cross-platform build -systems. The only difference between the two is that `python_example`_ uses -Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake -(which may be preferable for existing C++ projects). - -.. _python_example: https://github.com/pybind/python_example -.. _cmake_example: https://github.com/pybind/cmake_example - -Building the above C++ code will produce a binary module file that can be -imported to Python. Assuming that the compiled module is located in the -current directory, the following interactive Python session shows how to -load and execute the example: - -.. code-block:: pycon - - $ python - Python 3.9.10 (main, Jan 15 2022, 11:48:04) - [Clang 13.0.0 (clang-1300.0.29.3)] on darwin - Type "help", "copyright", "credits" or "license" for more information. - >>> import example - >>> example.add(1, 2) - 3 - >>> - -.. _keyword_args: - -Keyword arguments -================= - -With a simple code modification, it is possible to inform Python about the -names of the arguments ("i" and "j" in this case). - -.. code-block:: cpp - - m.def("add", &add, "A function which adds two numbers", - py::arg("i"), py::arg("j")); - -:class:`arg` is one of several special tag classes which can be used to pass -metadata into :func:`module_::def`. With this modified binding code, we can now -call the function using keyword arguments, which is a more readable alternative -particularly for functions taking many parameters: - -.. code-block:: pycon - - >>> import example - >>> example.add(i=1, j=2) - 3L - -The keyword names also appear in the function signatures within the documentation. - -.. code-block:: pycon - - >>> help(example) - - .... - - FUNCTIONS - add(...) - Signature : (i: int, j: int) -> int - - A function which adds two numbers - -A shorter notation for named arguments is also available: - -.. code-block:: cpp - - // regular notation - m.def("add1", &add, py::arg("i"), py::arg("j")); - // shorthand - using namespace pybind11::literals; - m.def("add2", &add, "i"_a, "j"_a); - -The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`. -Note that the literal operator must first be made visible with the directive -``using namespace pybind11::literals``. This does not bring in anything else -from the ``pybind11`` namespace except for literals. - -.. _default_args: - -Default arguments -================= - -Suppose now that the function to be bound has default arguments, e.g.: - -.. code-block:: cpp - - int add(int i = 1, int j = 2) { - return i + j; - } - -Unfortunately, pybind11 cannot automatically extract these parameters, since they -are not part of the function's type information. However, they are simple to specify -using an extension of :class:`arg`: - -.. code-block:: cpp - - m.def("add", &add, "A function which adds two numbers", - py::arg("i") = 1, py::arg("j") = 2); - -The default values also appear within the documentation. - -.. code-block:: pycon - - >>> help(example) - - .... - - FUNCTIONS - add(...) - Signature : (i: int = 1, j: int = 2) -> int - - A function which adds two numbers - -The shorthand notation is also available for default arguments: - -.. code-block:: cpp - - // regular notation - m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2); - // shorthand - m.def("add2", &add, "i"_a=1, "j"_a=2); - -Exporting variables -=================== - -To expose a value from C++, use the ``attr`` function to register it in a -module as shown below. Built-in types and general objects (more on that later) -are automatically converted when assigned as attributes, and can be explicitly -converted using the function ``py::cast``. - -.. code-block:: cpp - - PYBIND11_MODULE(example, m) { - m.attr("the_answer") = 42; - py::object world = py::cast("World"); - m.attr("what") = world; - } - -These are then accessible from Python: - -.. code-block:: pycon - - >>> import example - >>> example.the_answer - 42 - >>> example.what - 'World' - -.. _supported_types: - -Supported data types -==================== - -A large number of data types are supported out of the box and can be used -seamlessly as functions arguments, return values or with ``py::cast`` in general. -For a full overview, see the :doc:`advanced/cast/index` section. +.. _basics: + +First steps +########### + +This sections demonstrates the basic features of pybind11. Before getting +started, make sure that development environment is set up to compile the +included set of test cases. + + +Compiling the test cases +======================== + +Linux/macOS +----------- + +On Linux you'll need to install the **python-dev** or **python3-dev** packages as +well as **cmake**. On macOS, the included python version works out of the box, +but **cmake** must still be installed. + +After installing the prerequisites, run + +.. code-block:: bash + + mkdir build + cd build + cmake .. + make check -j 4 + +The last line will both compile and run the tests. + +Windows +------- + +On Windows, only **Visual Studio 2017** and newer are supported. + +.. Note:: + + To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag + ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When + building with Visual Studio 2019, this is not strictly necessary, but still advised. + +.. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017 + +To compile and run the tests: + +.. code-block:: batch + + mkdir build + cd build + cmake .. + cmake --build . --config Release --target check + +This will create a Visual Studio project, compile and run the target, all from the +command line. + +.. Note:: + + If all tests fail, make sure that the Python binary and the testcases are compiled + for the same processor type and bitness (i.e. either **i386** or **x86_64**). You + can specify **x86_64** as the target architecture for the generated Visual Studio + project using ``cmake -A x64 ..``. + +.. seealso:: + + Advanced users who are already familiar with Boost.Python may want to skip + the tutorial and look at the test cases in the :file:`tests` directory, + which exercise all features of pybind11. + +Header and namespace conventions +================================ + +For brevity, all code examples assume that the following two lines are present: + +.. code-block:: cpp + + #include + + namespace py = pybind11; + +Some features may require additional headers, but those will be specified as needed. + +.. _simple_example: + +Creating bindings for a simple function +======================================= + +Let's start by creating Python bindings for an extremely simple function, which +adds two numbers and returns their result: + +.. code-block:: cpp + + int add(int i, int j) { + return i + j; + } + +For simplicity [#f1]_, we'll put both this function and the binding code into +a file named :file:`example.cpp` with the following contents: + +.. code-block:: cpp + + #include + + int add(int i, int j) { + return i + j; + } + + PYBIND11_MODULE(example, m) { + m.doc() = "pybind11 example plugin"; // optional module docstring + + m.def("add", &add, "A function that adds two numbers"); + } + +.. [#f1] In practice, implementation and binding code will generally be located + in separate files. + +The :func:`PYBIND11_MODULE` macro creates a function that will be called when an +``import`` statement is issued from within Python. The module name (``example``) +is given as the first macro argument (it should not be in quotes). The second +argument (``m``) defines a variable of type :class:`py::module_ ` which +is the main interface for creating bindings. The method :func:`module_::def` +generates binding code that exposes the ``add()`` function to Python. + +.. note:: + + Notice how little code was needed to expose our function to Python: all + details regarding the function's parameters and return value were + automatically inferred using template metaprogramming. This overall + approach and the used syntax are borrowed from Boost.Python, though the + underlying implementation is very different. + +pybind11 is a header-only library, hence it is not necessary to link against +any special libraries and there are no intermediate (magic) translation steps. +On Linux, the above example can be compiled using the following command: + +.. code-block:: bash + + $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) + +.. note:: + + If you used :ref:`include_as_a_submodule` to get the pybind11 source, then + use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of + ``$(python3 -m pybind11 --includes)`` in the above compilation, as + explained in :ref:`building_manually`. + +For more details on the required compiler flags on Linux and macOS, see +:ref:`building_manually`. For complete cross-platform compilation instructions, +refer to the :ref:`compiling` page. + +The `python_example`_ and `cmake_example`_ repositories are also a good place +to start. They are both complete project examples with cross-platform build +systems. The only difference between the two is that `python_example`_ uses +Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake +(which may be preferable for existing C++ projects). + +.. _python_example: https://github.com/pybind/python_example +.. _cmake_example: https://github.com/pybind/cmake_example + +Building the above C++ code will produce a binary module file that can be +imported to Python. Assuming that the compiled module is located in the +current directory, the following interactive Python session shows how to +load and execute the example: + +.. code-block:: pycon + + $ python + Python 3.9.10 (main, Jan 15 2022, 11:48:04) + [Clang 13.0.0 (clang-1300.0.29.3)] on darwin + Type "help", "copyright", "credits" or "license" for more information. + >>> import example + >>> example.add(1, 2) + 3 + >>> + +.. _keyword_args: + +Keyword arguments +================= + +With a simple code modification, it is possible to inform Python about the +names of the arguments ("i" and "j" in this case). + +.. code-block:: cpp + + m.def("add", &add, "A function which adds two numbers", + py::arg("i"), py::arg("j")); + +:class:`arg` is one of several special tag classes which can be used to pass +metadata into :func:`module_::def`. With this modified binding code, we can now +call the function using keyword arguments, which is a more readable alternative +particularly for functions taking many parameters: + +.. code-block:: pycon + + >>> import example + >>> example.add(i=1, j=2) + 3L + +The keyword names also appear in the function signatures within the documentation. + +.. code-block:: pycon + + >>> help(example) + + .... + + FUNCTIONS + add(...) + Signature : (i: int, j: int) -> int + + A function which adds two numbers + +A shorter notation for named arguments is also available: + +.. code-block:: cpp + + // regular notation + m.def("add1", &add, py::arg("i"), py::arg("j")); + // shorthand + using namespace pybind11::literals; + m.def("add2", &add, "i"_a, "j"_a); + +The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`. +Note that the literal operator must first be made visible with the directive +``using namespace pybind11::literals``. This does not bring in anything else +from the ``pybind11`` namespace except for literals. + +.. _default_args: + +Default arguments +================= + +Suppose now that the function to be bound has default arguments, e.g.: + +.. code-block:: cpp + + int add(int i = 1, int j = 2) { + return i + j; + } + +Unfortunately, pybind11 cannot automatically extract these parameters, since they +are not part of the function's type information. However, they are simple to specify +using an extension of :class:`arg`: + +.. code-block:: cpp + + m.def("add", &add, "A function which adds two numbers", + py::arg("i") = 1, py::arg("j") = 2); + +The default values also appear within the documentation. + +.. code-block:: pycon + + >>> help(example) + + .... + + FUNCTIONS + add(...) + Signature : (i: int = 1, j: int = 2) -> int + + A function which adds two numbers + +The shorthand notation is also available for default arguments: + +.. code-block:: cpp + + // regular notation + m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2); + // shorthand + m.def("add2", &add, "i"_a=1, "j"_a=2); + +Exporting variables +=================== + +To expose a value from C++, use the ``attr`` function to register it in a +module as shown below. Built-in types and general objects (more on that later) +are automatically converted when assigned as attributes, and can be explicitly +converted using the function ``py::cast``. + +.. code-block:: cpp + + PYBIND11_MODULE(example, m) { + m.attr("the_answer") = 42; + py::object world = py::cast("World"); + m.attr("what") = world; + } + +These are then accessible from Python: + +.. code-block:: pycon + + >>> import example + >>> example.the_answer + 42 + >>> example.what + 'World' + +.. _supported_types: + +Supported data types +==================== + +A large number of data types are supported out of the box and can be used +seamlessly as functions arguments, return values or with ``py::cast`` in general. +For a full overview, see the :doc:`advanced/cast/index` section. diff --git a/third_party/CityFlow/extern/pybind11/docs/benchmark.py b/third_party/CityFlow/extern/pybind11/docs/benchmark.py index fb49fd04882996f0cd6838ef91edeb72d7d85b6b..5ce72fb67677f3ec85b652a91414f0d37a2525a3 100644 --- a/third_party/CityFlow/extern/pybind11/docs/benchmark.py +++ b/third_party/CityFlow/extern/pybind11/docs/benchmark.py @@ -1,87 +1,87 @@ -import datetime as dt -import os -import random - -nfns = 4 # Functions per class -nargs = 4 # Arguments per function - - -def generate_dummy_code_pybind11(nclasses=10): - decl = "" - bindings = "" - - for cl in range(nclasses): - decl += f"class cl{cl:03};\n" - decl += "\n" - - for cl in range(nclasses): - decl += f"class {cl:03} {{\n" - decl += "public:\n" - bindings += f' py::class_(m, "cl{cl:03}")\n' - for fn in range(nfns): - ret = random.randint(0, nclasses - 1) - params = [random.randint(0, nclasses - 1) for i in range(nargs)] - decl += f" cl{ret:03} *fn_{fn:03}(" - decl += ", ".join(f"cl{p:03} *" for p in params) - decl += ");\n" - bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03})\n' - decl += "};\n\n" - bindings += " ;\n" - - result = "#include \n\n" - result += "namespace py = pybind11;\n\n" - result += decl + "\n" - result += "PYBIND11_MODULE(example, m) {\n" - result += bindings - result += "}" - return result - - -def generate_dummy_code_boost(nclasses=10): - decl = "" - bindings = "" - - for cl in range(nclasses): - decl += f"class cl{cl:03};\n" - decl += "\n" - - for cl in range(nclasses): - decl += "class cl%03i {\n" % cl - decl += "public:\n" - bindings += f' py::class_("cl{cl:03}")\n' - for fn in range(nfns): - ret = random.randint(0, nclasses - 1) - params = [random.randint(0, nclasses - 1) for i in range(nargs)] - decl += f" cl{ret:03} *fn_{fn:03}(" - decl += ", ".join(f"cl{p:03} *" for p in params) - decl += ");\n" - bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03}, py::return_value_policy())\n' - decl += "};\n\n" - bindings += " ;\n" - - result = "#include \n\n" - result += "namespace py = boost::python;\n\n" - result += decl + "\n" - result += "BOOST_PYTHON_MODULE(example) {\n" - result += bindings - result += "}" - return result - - -for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: - print("{") - for i in range(10): - nclasses = 2**i - with open("test.cpp", "w") as f: - f.write(codegen(nclasses)) - n1 = dt.datetime.now() - os.system( - "g++ -Os -shared -rdynamic -undefined dynamic_lookup " - "-fvisibility=hidden -std=c++14 test.cpp -I include " - "-I /System/Library/Frameworks/Python.framework/Headers -o test.so" - ) - n2 = dt.datetime.now() - elapsed = (n2 - n1).total_seconds() - size = os.stat("test.so").st_size - print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) - print("}") +import datetime as dt +import os +import random + +nfns = 4 # Functions per class +nargs = 4 # Arguments per function + + +def generate_dummy_code_pybind11(nclasses=10): + decl = "" + bindings = "" + + for cl in range(nclasses): + decl += f"class cl{cl:03};\n" + decl += "\n" + + for cl in range(nclasses): + decl += f"class {cl:03} {{\n" + decl += "public:\n" + bindings += f' py::class_(m, "cl{cl:03}")\n' + for fn in range(nfns): + ret = random.randint(0, nclasses - 1) + params = [random.randint(0, nclasses - 1) for i in range(nargs)] + decl += f" cl{ret:03} *fn_{fn:03}(" + decl += ", ".join(f"cl{p:03} *" for p in params) + decl += ");\n" + bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03})\n' + decl += "};\n\n" + bindings += " ;\n" + + result = "#include \n\n" + result += "namespace py = pybind11;\n\n" + result += decl + "\n" + result += "PYBIND11_MODULE(example, m) {\n" + result += bindings + result += "}" + return result + + +def generate_dummy_code_boost(nclasses=10): + decl = "" + bindings = "" + + for cl in range(nclasses): + decl += f"class cl{cl:03};\n" + decl += "\n" + + for cl in range(nclasses): + decl += "class cl%03i {\n" % cl + decl += "public:\n" + bindings += f' py::class_("cl{cl:03}")\n' + for fn in range(nfns): + ret = random.randint(0, nclasses - 1) + params = [random.randint(0, nclasses - 1) for i in range(nargs)] + decl += f" cl{ret:03} *fn_{fn:03}(" + decl += ", ".join(f"cl{p:03} *" for p in params) + decl += ");\n" + bindings += f' .def("fn_{fn:03}", &cl{cl:03}::fn_{fn:03}, py::return_value_policy())\n' + decl += "};\n\n" + bindings += " ;\n" + + result = "#include \n\n" + result += "namespace py = boost::python;\n\n" + result += decl + "\n" + result += "BOOST_PYTHON_MODULE(example) {\n" + result += bindings + result += "}" + return result + + +for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: + print("{") + for i in range(10): + nclasses = 2**i + with open("test.cpp", "w") as f: + f.write(codegen(nclasses)) + n1 = dt.datetime.now() + os.system( + "g++ -Os -shared -rdynamic -undefined dynamic_lookup " + "-fvisibility=hidden -std=c++14 test.cpp -I include " + "-I /System/Library/Frameworks/Python.framework/Headers -o test.so" + ) + n2 = dt.datetime.now() + elapsed = (n2 - n1).total_seconds() + size = os.stat("test.so").st_size + print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) + print("}") diff --git a/third_party/CityFlow/extern/pybind11/docs/benchmark.rst b/third_party/CityFlow/extern/pybind11/docs/benchmark.rst index 02c2ccde7dc00db1e57b73a7523521f9c39a5639..02d142e6225955467c04d7573de144cab2ebe07b 100644 --- a/third_party/CityFlow/extern/pybind11/docs/benchmark.rst +++ b/third_party/CityFlow/extern/pybind11/docs/benchmark.rst @@ -1,95 +1,95 @@ -Benchmark -========= - -The following is the result of a synthetic benchmark comparing both compilation -time and module size of pybind11 against Boost.Python. A detailed report about a -Boost.Python to pybind11 conversion of a real project is available here: [#f1]_. - -.. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf - -Setup ------ - -A python script (see the ``docs/benchmark.py`` file) was used to generate a set -of files with dummy classes whose count increases for each successive benchmark -(between 1 and 2048 classes in powers of two). Each class has four methods with -a randomly generated signature with a return value and four arguments. (There -was no particular reason for this setup other than the desire to generate many -unique function signatures whose count could be controlled in a simple way.) - -Here is an example of the binding code for one class: - -.. code-block:: cpp - - ... - class cl034 { - public: - cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); - cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); - cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); - cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); - }; - ... - - PYBIND11_MODULE(example, m) { - ... - py::class_(m, "cl034") - .def("fn_000", &cl034::fn_000) - .def("fn_001", &cl034::fn_001) - .def("fn_002", &cl034::fn_002) - .def("fn_003", &cl034::fn_003) - ... - } - -The Boost.Python version looks almost identical except that a return value -policy had to be specified as an argument to ``def()``. For both libraries, -compilation was done with - -.. code-block:: bash - - Apple LLVM version 7.0.2 (clang-700.1.81) - -and the following compilation flags - -.. code-block:: bash - - g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14 - -Compilation time ----------------- - -The following log-log plot shows how the compilation time grows for an -increasing number of class and function declarations. pybind11 includes many -fewer headers, which initially leads to shorter compilation times, but the -performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for -the largest largest file with 2048 classes and a total of 8192 methods -- a -modest **1.2x** speedup relative to Boost.Python, which required 116.35 -seconds). - -.. only:: not latex - - .. image:: pybind11_vs_boost_python1.svg - -.. only:: latex - - .. image:: pybind11_vs_boost_python1.png - -Module size ------------ - -Differences between the two libraries become much more pronounced when -considering the file size of the generated Python plugin: for the largest file, -the binary generated by Boost.Python required 16.8 MiB, which was **2.17 -times** / **9.1 megabytes** larger than the output generated by pybind11. For -very small inputs, Boost.Python has an edge in the plot below -- however, note -that it stores many definitions in an external library, whose size was not -included here, hence the comparison is slightly shifted in Boost.Python's -favor. - -.. only:: not latex - - .. image:: pybind11_vs_boost_python2.svg - -.. only:: latex - - .. image:: pybind11_vs_boost_python2.png +Benchmark +========= + +The following is the result of a synthetic benchmark comparing both compilation +time and module size of pybind11 against Boost.Python. A detailed report about a +Boost.Python to pybind11 conversion of a real project is available here: [#f1]_. + +.. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf + +Setup +----- + +A python script (see the ``docs/benchmark.py`` file) was used to generate a set +of files with dummy classes whose count increases for each successive benchmark +(between 1 and 2048 classes in powers of two). Each class has four methods with +a randomly generated signature with a return value and four arguments. (There +was no particular reason for this setup other than the desire to generate many +unique function signatures whose count could be controlled in a simple way.) + +Here is an example of the binding code for one class: + +.. code-block:: cpp + + ... + class cl034 { + public: + cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); + cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); + cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); + cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); + }; + ... + + PYBIND11_MODULE(example, m) { + ... + py::class_(m, "cl034") + .def("fn_000", &cl034::fn_000) + .def("fn_001", &cl034::fn_001) + .def("fn_002", &cl034::fn_002) + .def("fn_003", &cl034::fn_003) + ... + } + +The Boost.Python version looks almost identical except that a return value +policy had to be specified as an argument to ``def()``. For both libraries, +compilation was done with + +.. code-block:: bash + + Apple LLVM version 7.0.2 (clang-700.1.81) + +and the following compilation flags + +.. code-block:: bash + + g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14 + +Compilation time +---------------- + +The following log-log plot shows how the compilation time grows for an +increasing number of class and function declarations. pybind11 includes many +fewer headers, which initially leads to shorter compilation times, but the +performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for +the largest largest file with 2048 classes and a total of 8192 methods -- a +modest **1.2x** speedup relative to Boost.Python, which required 116.35 +seconds). + +.. only:: not latex + + .. image:: pybind11_vs_boost_python1.svg + +.. only:: latex + + .. image:: pybind11_vs_boost_python1.png + +Module size +----------- + +Differences between the two libraries become much more pronounced when +considering the file size of the generated Python plugin: for the largest file, +the binary generated by Boost.Python required 16.8 MiB, which was **2.17 +times** / **9.1 megabytes** larger than the output generated by pybind11. For +very small inputs, Boost.Python has an edge in the plot below -- however, note +that it stores many definitions in an external library, whose size was not +included here, hence the comparison is slightly shifted in Boost.Python's +favor. + +.. only:: not latex + + .. image:: pybind11_vs_boost_python2.svg + +.. only:: latex + + .. image:: pybind11_vs_boost_python2.png diff --git a/third_party/CityFlow/extern/pybind11/docs/changelog.rst b/third_party/CityFlow/extern/pybind11/docs/changelog.rst index d2285f237e0774e0db5a1365939a25d363cfe950..ba13b4ed663b154f2acfec842266b6d19a62a477 100644 --- a/third_party/CityFlow/extern/pybind11/docs/changelog.rst +++ b/third_party/CityFlow/extern/pybind11/docs/changelog.rst @@ -1,3006 +1,3006 @@ -.. _changelog: - -Changelog -######### - -Starting with version 1.8.0, pybind11 releases use a `semantic versioning -`_ policy. - -Changes will be added here periodically from the "Suggested changelog entry" -block in pull request descriptions. - - -IN DEVELOPMENT --------------- - -Changes will be summarized here periodically. - -Version 2.12.0 (March 27, 2025) -------------------------------- - -New Features: - -* ``pybind11`` now supports compiling for - `NumPy 2 `_. Most - code shouldn't change (see :ref:`upgrade-guide-2.12` for details). However, - if you experience issues you can define ``PYBIND11_NUMPY_1_ONLY`` to disable - the new support for now, but this will be removed in the future. - `#5050 `_ - -* ``pybind11/gil_safe_call_once.h`` was added (it needs to be included - explicitly). The primary use case is GIL-safe initialization of C++ - ``static`` variables. - `#4877 `_ - -* Support move-only iterators in ``py::make_iterator``, - ``py::make_key_iterator``, ``py::make_value_iterator``. - `#4834 `_ - -* Two simple ``py::set_error()`` functions were added and the documentation was - updated accordingly. In particular, ``py::exception<>::operator()`` was - deprecated (use one of the new functions instead). The documentation for - ``py::exception<>`` was further updated to not suggest code that may result - in undefined behavior. - `#4772 `_ - -Bug fixes: - -* Removes potential for Undefined Behavior during process teardown. - `#4897 `_ - -* Improve compatibility with the nvcc compiler (especially CUDA 12.1/12.2). - `#4893 `_ - -* ``pybind11/numpy.h`` now imports NumPy's ``multiarray`` and ``_internal`` - submodules with paths depending on the installed version of NumPy (for - compatibility with NumPy 2). - `#4857 `_ - -* Builtins collections names in docstrings are now consistently rendered in - lowercase (list, set, dict, tuple), in accordance with PEP 585. - `#4833 `_ - -* Added ``py::typing::Iterator``, ``py::typing::Iterable``. - `#4832 `_ - -* Render ``py::function`` as ``Callable`` in docstring. - `#4829 `_ - -* Also bump ``PYBIND11_INTERNALS_VERSION`` for MSVC, which unlocks two new - features without creating additional incompatibilities. - `#4819 `_ - -* Guard against crashes/corruptions caused by modules built with different MSVC - versions. - `#4779 `_ - -* A long-standing bug in the handling of Python multiple inheritance was fixed. - See PR #4762 for the rather complex details. - `#4762 `_ - -* Fix ``bind_map`` with ``using`` declarations. - `#4952 `_ - -* Qualify ``py::detail::concat`` usage to avoid ADL selecting one from - somewhere else, such as modernjson's concat. - `#4955 `_ - -* Use new PyCode API on Python 3.12+. - `#4916 `_ - -* Minor cleanup from warnings reported by Clazy. - `#4988 `_ - -* Remove typing and duplicate ``class_`` for ``KeysView``/``ValuesView``/``ItemsView``. - `#4985 `_ - -* Use ``PyObject_VisitManagedDict()`` and ``PyObject_ClearManagedDict()`` on Python 3.13 and newer. - `#4973 `_ - -* Update ``make_static_property_type()`` to make it compatible with Python 3.13. - `#4971 `_ - -.. fix(types) - -* Render typed iterators for ``make_iterator``, ``make_key_iterator``, - ``make_value_iterator``. - `#4876 `_ - -* Add several missing type name specializations. - `#5073 `_ - -* Change docstring render for ``py::buffer``, ``py::sequence`` and - ``py::handle`` (to ``Buffer``, ``Sequence``, ``Any``). - `#4831 `_ - -* Fixed ``base_enum.__str__`` docstring. - `#4827 `_ - -* Enforce single line docstring signatures. - `#4735 `_ - -* Special 'typed' wrappers now available in ``typing.h`` to annotate tuple, dict, - list, set, and function. - `#4259 `_ - -* Create ``handle_type_name`` specialization to type-hint variable length tuples. - `#5051 `_ - -.. fix(build) - -* Setting ``PYBIND11_FINDPYTHON`` to OFF will force the old FindPythonLibs mechanism to be used. - `#5042 `_ - -* Skip empty ``PYBIND11_PYTHON_EXECUTABLE_LAST`` for the first cmake run. - `#4856 `_ - -* Fix FindPython mode exports & avoid ``pkg_resources`` if - ``importlib.metadata`` available. - `#4941 `_ - -* ``Python_ADDITIONAL_VERSIONS`` (classic search) now includes 3.12. - `#4909 `_ - -* ``pybind11.pc`` is now relocatable by default as long as install destinations - are not absolute paths. - `#4830 `_ - -* Correctly detect CMake FindPython removal when used as a subdirectory. - `#4806 `_ - -* Don't require the libs component on CMake 3.18+ when using - PYBIND11_FINDPYTHON (fixes manylinux builds). - `#4805 `_ - -* ``pybind11_strip`` is no longer automatically applied when - ``CMAKE_BUILD_TYPE`` is unset. - `#4780 `_ - -* Support ``DEBUG_POSFIX`` correctly for debug builds. - `#4761 `_ - -* Hardcode lto/thin lto for Emscripten cross-compiles. - `#4642 `_ - -* Upgrade maximum supported CMake version to 3.27 to fix CMP0148 warnings. - `#4786 `_ - -Documentation: - -* Small fix to grammar in ``functions.rst``. - `#4791 `_ - -* Remove upper bound in example pyproject.toml for setuptools. - `#4774 `_ - -CI: - -* CI: Update NVHPC to 23.5 and Ubuntu 20.04. - `#4764 `_ - -* Test on PyPy 3.10. - `#4714 `_ - -Other: - -* Use Ruff formatter instead of Black. - `#4912 `_ - -* An ``assert()`` was added to help Coverty avoid generating a false positive. - `#4817 `_ - - -Version 2.11.1 (July 17, 2023) ------------------------------- - -Changes: - -* ``PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF`` is now provided as an option - for disabling the default-on ``PyGILState_Check()``'s in - ``pybind11::handle``'s ``inc_ref()`` & ``dec_ref()``. - `#4753 `_ - -* ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`` was disabled for PyPy in general - (not just PyPy Windows). - `#4751 `_ - - -Version 2.11.0 (July 14, 2023) ------------------------------- - -New features: - -* The newly added ``pybind11::detail::is_move_constructible`` trait can be - specialized for cases in which ``std::is_move_constructible`` does not work - as needed. This is very similar to the long-established - ``pybind11::detail::is_copy_constructible``. - `#4631 `_ - -* Introduce ``recursive_container_traits``. - `#4623 `_ - -* ``pybind11/type_caster_pyobject_ptr.h`` was added to support automatic - wrapping of APIs that make use of ``PyObject *``. This header needs to - included explicitly (i.e. it is not included implicitly - with ``pybind/pybind11.h``). - `#4601 `_ - -* ``format_descriptor<>`` & ``npy_format_descriptor<>`` ``PyObject *`` - specializations were added. The latter enables ``py::array_t`` - to/from-python conversions. - `#4674 `_ - -* ``buffer_info`` gained an ``item_type_is_equivalent_to()`` member - function. - `#4674 `_ - -* The ``capsule`` API gained a user-friendly constructor - (``py::capsule(ptr, "name", dtor)``). - `#4720 `_ - -Changes: - -* ``PyGILState_Check()``'s in ``pybind11::handle``'s ``inc_ref()`` & - ``dec_ref()`` are now enabled by default again. - `#4246 `_ - -* ``py::initialize_interpreter()`` using ``PyConfig_InitPythonConfig()`` - instead of ``PyConfig_InitIsolatedConfig()``, to obtain complete - ``sys.path``. - `#4473 `_ - -* Cast errors now always include Python type information, even if - ``PYBIND11_DETAILED_ERROR_MESSAGES`` is not defined. This increases binary - sizes slightly (~1.5%) but the error messages are much more informative. - `#4463 `_ - -* The docstring generation for the ``std::array``-list caster was fixed. - Previously, signatures included the size of the list in a non-standard, - non-spec compliant way. The new format conforms to PEP 593. - **Tooling for processing the docstrings may need to be updated accordingly.** - `#4679 `_ - -* Setter return values (which are inaccessible for all practical purposes) are - no longer converted to Python (only to be discarded). - `#4621 `_ - -* Allow lambda specified to function definition to be ``noexcept(true)`` - in C++17. - `#4593 `_ - -* Get rid of recursive template instantiations for concatenating type - signatures on C++17 and higher. - `#4587 `_ - -* Compatibility with Python 3.12 (beta). Note that the minimum pybind11 - ABI version for Python 3.12 is version 5. (The default ABI version - for Python versions up to and including 3.11 is still version 4.). - `#4570 `_ - -* With ``PYBIND11_INTERNALS_VERSION 5`` (default for Python 3.12+), MSVC builds - use ``std::hash`` and ``std::equal_to`` - instead of string-based type comparisons. This resolves issues when binding - types defined in the unnamed namespace. - `#4319 `_ - -* Python exception ``__notes__`` (introduced with Python 3.11) are now added to - the ``error_already_set::what()`` output. - `#4678 `_ - -Build system improvements: - -* CMake 3.27 support was added, CMake 3.4 support was dropped. - FindPython will be used if ``FindPythonInterp`` is not present. - `#4719 `_ - -* Update clang-tidy to 15 in CI. - `#4387 `_ - -* Moved the linting framework over to Ruff. - `#4483 `_ - -* Skip ``lto`` checks and target generation when - ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is defined. - `#4643 `_ - -* No longer inject ``-stdlib=libc++``, not needed for modern Pythons - (macOS 10.9+). - `#4639 `_ - -* PyPy 3.10 support was added, PyPy 3.7 support was dropped. - `#4728 `_ - -* Testing with Python 3.12 beta releases was added. - `#4713 `_ - - -Version 2.10.4 (Mar 16, 2023) ------------------------------ - -Changes: - -* ``python3 -m pybind11`` gained a ``--version`` option (prints the version and - exits). - `#4526 `_ - -Bug Fixes: - -* Fix a warning when pydebug is enabled on Python 3.11. - `#4461 `_ - -* Ensure ``gil_scoped_release`` RAII is non-copyable. - `#4490 `_ - -* Ensure the tests dir does not show up with new versions of setuptools. - `#4510 `_ - -* Better stacklevel for a warning in setuptools helpers. - `#4516 `_ - -Version 2.10.3 (Jan 3, 2023) ----------------------------- - -Changes: - -* Temporarily made our GIL status assertions (added in 2.10.2) disabled by - default (re-enable manually by defining - ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF``, will be enabled in 2.11). - `#4432 `_ - -* Improved error messages when ``inc_ref``/``dec_ref`` are called with an - invalid GIL state. - `#4427 `_ - `#4436 `_ - -Bug Fixes: - -* Some minor touchups found by static analyzers. - `#4440 `_ - - -Version 2.10.2 (Dec 20, 2022) ------------------------------ - -Changes: - -* ``scoped_interpreter`` constructor taking ``PyConfig``. - `#4330 `_ - -* ``pybind11/eigen/tensor.h`` adds converters to and from ``Eigen::Tensor`` and - ``Eigen::TensorMap``. - `#4201 `_ - -* ``PyGILState_Check()``'s were integrated to ``pybind11::handle`` - ``inc_ref()`` & ``dec_ref()``. The added GIL checks are guarded by - ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF``, which is the default only if - ``NDEBUG`` is not defined. (Made non-default in 2.10.3, will be active in 2.11) - `#4246 `_ - -* Add option for enable/disable enum members in docstring. - `#2768 `_ - -* Fixed typing of ``KeysView``, ``ValuesView`` and ``ItemsView`` in ``bind_map``. - `#4353 `_ - -Bug fixes: - -* Bug fix affecting only Python 3.6 under very specific, uncommon conditions: - move ``PyEval_InitThreads()`` call to the correct location. - `#4350 `_ - -* Fix segfault bug when passing foreign native functions to functional.h. - `#4254 `_ - -Build system improvements: - -* Support setting PYTHON_LIBRARIES manually for Windows ARM cross-compilation - (classic mode). - `#4406 `_ - -* Extend IPO/LTO detection for ICX (a.k.a IntelLLVM) compiler. - `#4402 `_ - -* Allow calling ``find_package(pybind11 CONFIG)`` multiple times from separate - directories in the same CMake project and properly link Python (new mode). - `#4401 `_ - -* ``multiprocessing_set_spawn`` in pytest fixture for added safety. - `#4377 `_ - -* Fixed a bug in two pybind11/tools cmake scripts causing "Unknown arguments specified" errors. - `#4327 `_ - - - -Version 2.10.1 (Oct 31, 2022) ------------------------------ - -This is the first version to fully support embedding the newly released Python 3.11. - -Changes: - -* Allow ``pybind11::capsule`` constructor to take null destructor pointers. - `#4221 `_ - -* ``embed.h`` was changed so that ``PYTHONPATH`` is used also with Python 3.11 - (established behavior). - `#4119 `_ - -* A ``PYBIND11_SIMPLE_GIL_MANAGEMENT`` option was added (cmake, C++ define), - along with many additional tests in ``test_gil_scoped.py``. The option may be - useful to try when debugging GIL-related issues, to determine if the more - complex default implementation is or is not to blame. See #4216 for - background. WARNING: Please be careful to not create ODR violations when - using the option: everything that is linked together with mutual symbol - visibility needs to be rebuilt. - `#4216 `_ - -* ``PYBIND11_EXPORT_EXCEPTION`` was made non-empty only under macOS. This makes - Linux builds safer, and enables the removal of warning suppression pragmas for - Windows. - `#4298 `_ - -Bug fixes: - -* Fixed a bug where ``UnicodeDecodeError`` was not propagated from various - ``py::str`` ctors when decoding surrogate utf characters. - `#4294 `_ - -* Revert perfect forwarding for ``make_iterator``. This broke at least one - valid use case. May revisit later. - `#4234 `_ - -* Fix support for safe casts to ``void*`` (regression in 2.10.0). - `#4275 `_ - -* Fix ``char8_t`` support (regression in 2.9). - `#4278 `_ - -* Unicode surrogate character in Python exception message leads to process - termination in ``error_already_set::what()``. - `#4297 `_ - -* Fix MSVC 2019 v.1924 & C++14 mode error for ``overload_cast``. - `#4188 `_ - -* Make augmented assignment operators non-const for the object-api. Behavior - was previously broken for augmented assignment operators. - `#4065 `_ - -* Add proper error checking to C++ bindings for Python list append and insert. - `#4208 `_ - -* Work-around for Nvidia's CUDA nvcc compiler in versions 11.4.0 - 11.8.0. - `#4220 `_ - -* A workaround for PyPy was added in the ``py::error_already_set`` - implementation, related to PR `#1895 `_ - released with v2.10.0. - `#4079 `_ - -* Fixed compiler errors when C++23 ``std::forward_like`` is available. - `#4136 `_ - -* Properly raise exceptions in contains methods (like when an object in unhashable). - `#4209 `_ - -* Further improve another error in exception handling. - `#4232 `_ - -* ``get_local_internals()`` was made compatible with - ``finalize_interpreter()``, fixing potential freezes during interpreter - finalization. - `#4192 `_ - -Performance and style: - -* Reserve space in set and STL map casters if possible. This will prevent - unnecessary rehashing / resizing by knowing the number of keys ahead of time - for Python to C++ casting. This improvement will greatly speed up the casting - of large unordered maps and sets. - `#4194 `_ - -* GIL RAII scopes are non-copyable to avoid potential bugs. - `#4183 `_ - -* Explicitly default all relevant ctors for pytypes in the ``PYBIND11_OBJECT`` - macros and enforce the clang-tidy checks ``modernize-use-equals-default`` in - macros as well. - `#4017 `_ - -* Optimize iterator advancement in C++ bindings. - `#4237 `_ - -* Use the modern ``PyObject_GenericGetDict`` and ``PyObject_GenericSetDict`` - for handling dynamic attribute dictionaries. - `#4106 `_ - -* Document that users should use ``PYBIND11_NAMESPACE`` instead of using ``pybind11`` when - opening namespaces. Using namespace declarations and namespace qualification - remain the same as ``pybind11``. This is done to ensure consistent symbol - visibility. - `#4098 `_ - -* Mark ``detail::forward_like`` as constexpr. - `#4147 `_ - -* Optimize unpacking_collector when processing ``arg_v`` arguments. - `#4219 `_ - -* Optimize casting C++ object to ``None``. - `#4269 `_ - - -Build system improvements: - -* CMake: revert overwrite behavior, now opt-in with ``PYBIND11_PYTHONLIBS_OVERRWRITE OFF``. - `#4195 `_ - -* Include a pkg-config file when installing pybind11, such as in the Python - package. - `#4077 `_ - -* Avoid stripping debug symbols when ``CMAKE_BUILD_TYPE`` is set to ``DEBUG`` - instead of ``Debug``. - `#4078 `_ - -* Followup to `#3948 `_, fixing vcpkg again. - `#4123 `_ - -Version 2.10.0 (Jul 15, 2022) ------------------------------ - -Removed support for Python 2.7, Python 3.5, and MSVC 2015. Support for MSVC -2017 is limited due to availability of CI runners; we highly recommend MSVC -2019 or 2022 be used. Initial support added for Python 3.11. - -New features: - -* ``py::anyset`` & ``py::frozenset`` were added, with copying (cast) to - ``std::set`` (similar to ``set``). - `#3901 `_ - -* Support bytearray casting to string. - `#3707 `_ - -* ``type_caster`` was added. ``std::monostate`` is a tag type - that allows ``std::variant`` to act as an optional, or allows default - construction of a ``std::variant`` holding a non-default constructible type. - `#3818 `_ - -* ``pybind11::capsule::set_name`` added to mutate the name of the capsule instance. - `#3866 `_ - -* NumPy: dtype constructor from type number added, accessors corresponding to - Python API ``dtype.num``, ``dtype.byteorder``, ``dtype.flags`` and - ``dtype.alignment`` added. - `#3868 `_ - - -Changes: - -* Python 3.6 is now the minimum supported version. - `#3688 `_ - `#3719 `_ - -* The minimum version for MSVC is now 2017. - `#3722 `_ - -* Fix issues with CPython 3.11 betas and add to supported test matrix. - `#3923 `_ - -* ``error_already_set`` is now safer and more performant, especially for - exceptions with long tracebacks, by delaying computation. - `#1895 `_ - -* Improve exception handling in python ``str`` bindings. - `#3826 `_ - -* The bindings for capsules now have more consistent exception handling. - `#3825 `_ - -* ``PYBIND11_OBJECT_CVT`` and ``PYBIND11_OBJECT_CVT_DEFAULT`` macro can now be - used to define classes in namespaces other than pybind11. - `#3797 `_ - -* Error printing code now uses ``PYBIND11_DETAILED_ERROR_MESSAGES`` instead of - requiring ``NDEBUG``, allowing use with release builds if desired. - `#3913 `_ - -* Implicit conversion of the literal ``0`` to ``pybind11::handle`` is now disabled. - `#4008 `_ - - -Bug fixes: - -* Fix exception handling when ``pybind11::weakref()`` fails. - `#3739 `_ - -* ``module_::def_submodule`` was missing proper error handling. This is fixed now. - `#3973 `_ - -* The behavior or ``error_already_set`` was made safer and the highly opaque - "Unknown internal error occurred" message was replaced with a more helpful - message. - `#3982 `_ - -* ``error_already_set::what()`` now handles non-normalized exceptions correctly. - `#3971 `_ - -* Support older C++ compilers where filesystem is not yet part of the standard - library and is instead included in ``std::experimental::filesystem``. - `#3840 `_ - -* Fix ``-Wfree-nonheap-object`` warnings produced by GCC by avoiding returning - pointers to static objects with ``return_value_policy::take_ownership``. - `#3946 `_ - -* Fix cast from pytype rvalue to another pytype. - `#3949 `_ - -* Ensure proper behavior when garbage collecting classes with dynamic attributes in Python >=3.9. - `#4051 `_ - -* A couple long-standing ``PYBIND11_NAMESPACE`` - ``__attribute__((visibility("hidden")))`` inconsistencies are now fixed - (affects only unusual environments). - `#4043 `_ - -* ``pybind11::detail::get_internals()`` is now resilient to in-flight Python - exceptions. - `#3981 `_ - -* Arrays with a dimension of size 0 are now properly converted to dynamic Eigen - matrices (more common in NumPy 1.23). - `#4038 `_ - -* Avoid catching unrelated errors when importing NumPy. - `#3974 `_ - -Performance and style: - -* Added an accessor overload of ``(object &&key)`` to reference steal the - object when using python types as keys. This prevents unnecessary reference - count overhead for attr, dictionary, tuple, and sequence look ups. Added - additional regression tests. Fixed a performance bug the caused accessor - assignments to potentially perform unnecessary copies. - `#3970 `_ - -* Perfect forward all args of ``make_iterator``. - `#3980 `_ - -* Avoid potential bug in pycapsule destructor by adding an ``error_guard`` to - one of the dtors. - `#3958 `_ - -* Optimize dictionary access in ``strip_padding`` for numpy. - `#3994 `_ - -* ``stl_bind.h`` bindings now take slice args as a const-ref. - `#3852 `_ - -* Made slice constructor more consistent, and improve performance of some - casters by allowing reference stealing. - `#3845 `_ - -* Change numpy dtype from_args method to use const ref. - `#3878 `_ - -* Follow rule of three to ensure ``PyErr_Restore`` is called only once. - `#3872 `_ - -* Added missing perfect forwarding for ``make_iterator`` functions. - `#3860 `_ - -* Optimize c++ to python function casting by using the rvalue caster. - `#3966 `_ - -* Optimize Eigen sparse matrix casting by removing unnecessary temporary. - `#4064 `_ - -* Avoid potential implicit copy/assignment constructors causing double free in - ``strdup_gaurd``. - `#3905 `_ - -* Enable clang-tidy checks ``misc-definitions-in-headers``, - ``modernize-loop-convert``, and ``modernize-use-nullptr``. - `#3881 `_ - `#3988 `_ - - -Build system improvements: - -* CMake: Fix file extension on Windows with cp36 and cp37 using FindPython. - `#3919 `_ - -* CMake: Support multiple Python targets (such as on vcpkg). - `#3948 `_ - -* CMake: Fix issue with NVCC on Windows. - `#3947 `_ - -* CMake: Drop the bitness check on cross compiles (like targeting WebAssembly - via Emscripten). - `#3959 `_ - -* Add MSVC builds in debug mode to CI. - `#3784 `_ - -* MSVC 2022 C++20 coverage was added to GitHub Actions, including Eigen. - `#3732 `_, - `#3741 `_ - - -Backend and tidying up: - -* New theme for the documentation. - `#3109 `_ - -* Remove idioms in code comments. Use more inclusive language. - `#3809 `_ - -* ``#include `` was removed from the ``pybind11/stl.h`` header. Your - project may break if it has a transitive dependency on this include. The fix - is to "Include What You Use". - `#3928 `_ - -* Avoid ``setup.py `` usage in internal tests. - `#3734 `_ - - -Version 2.9.2 (Mar 29, 2022) ----------------------------- - -Changes: - -* Enum now has an ``__index__`` method on Python <3.8 too. - `#3700 `_ - -* Local internals are now cleared after finalizing the interpreter. - `#3744 `_ - -Bug fixes: - -* Better support for Python 3.11 alphas. - `#3694 `_ - -* ``PYBIND11_TYPE_CASTER`` now uses fully qualified symbols, so it can be used - outside of ``pybind11::detail``. - `#3758 `_ - -* Some fixes for PyPy 3.9. - `#3768 `_ - -* Fixed a potential memleak in PyPy in ``get_type_override``. - `#3774 `_ - -* Fix usage of ``VISIBILITY_INLINES_HIDDEN``. - `#3721 `_ - - -Build system improvements: - -* Uses ``sysconfig`` module to determine installation locations on Python >= - 3.10, instead of ``distutils`` which has been deprecated. - `#3764 `_ - -* Support Catch 2.13.5+ (supporting GLIBC 2.34+). - `#3679 `_ - -* Fix test failures with numpy 1.22 by ignoring whitespace when comparing - ``str()`` of dtypes. - `#3682 `_ - - -Backend and tidying up: - -* clang-tidy: added ``readability-qualified-auto``, - ``readability-braces-around-statements``, - ``cppcoreguidelines-prefer-member-initializer``, - ``clang-analyzer-optin.performance.Padding``, - ``cppcoreguidelines-pro-type-static-cast-downcast``, and - ``readability-inconsistent-declaration-parameter-name``. - `#3702 `_, - `#3699 `_, - `#3716 `_, - `#3709 `_ - -* clang-format was added to the pre-commit actions, and the entire code base - automatically reformatted (after several iterations preparing for this leap). - `#3713 `_ - - -Version 2.9.1 (Feb 2, 2022) ---------------------------- - -Changes: - -* If possible, attach Python exception with ``py::raise_from`` to ``TypeError`` - when casting from C++ to Python. This will give additional info if Python - exceptions occur in the caster. Adds a test case of trying to convert a set - from C++ to Python when the hash function is not defined in Python. - `#3605 `_ - -* Add a mapping of C++11 nested exceptions to their Python exception - equivalent using ``py::raise_from``. This attaches the nested exceptions in - Python using the ``__cause__`` field. - `#3608 `_ - -* Propagate Python exception traceback using ``raise_from`` if a pybind11 - function runs out of overloads. - `#3671 `_ - -* ``py::multiple_inheritance`` is now only needed when C++ bases are hidden - from pybind11. - `#3650 `_ and - `#3659 `_ - - -Bug fixes: - -* Remove a boolean cast in ``numpy.h`` that causes MSVC C4800 warnings when - compiling against Python 3.10 or newer. - `#3669 `_ - -* Render ``py::bool_`` and ``py::float_`` as ``bool`` and ``float`` - respectively. - `#3622 `_ - -Build system improvements: - -* Fix CMake extension suffix computation on Python 3.10+. - `#3663 `_ - -* Allow ``CMAKE_ARGS`` to override CMake args in pybind11's own ``setup.py``. - `#3577 `_ - -* Remove a few deprecated c-headers. - `#3610 `_ - -* More uniform handling of test targets. - `#3590 `_ - -* Add clang-tidy readability check to catch potentially swapped function args. - `#3611 `_ - - -Version 2.9.0 (Dec 28, 2021) ----------------------------- - -This is the last version to support Python 2.7 and 3.5. - -New Features: - -* Allow ``py::args`` to be followed by other arguments; the remaining arguments - are implicitly keyword-only, as if a ``py::kw_only{}`` annotation had been - used. - `#3402 `_ - -Changes: - -* Make str/bytes/memoryview more interoperable with ``std::string_view``. - `#3521 `_ - -* Replace ``_`` with ``const_name`` in internals, avoid defining ``pybind::_`` - if ``_`` defined as macro (common gettext usage) - `#3423 `_ - - -Bug fixes: - -* Fix a rare warning about extra copy in an Eigen constructor. - `#3486 `_ - -* Fix caching of the C++ overrides. - `#3465 `_ - -* Add missing ``std::forward`` calls to some ``cpp_function`` overloads. - `#3443 `_ - -* Support PyPy 7.3.7 and the PyPy3.8 beta. Test python-3.11 on PRs with the - ``python dev`` label. - `#3419 `_ - -* Replace usage of deprecated ``Eigen::MappedSparseMatrix`` with - ``Eigen::Map>`` for Eigen 3.3+. - `#3499 `_ - -* Tweaks to support Microsoft Visual Studio 2022. - `#3497 `_ - -Build system improvements: - -* Nicer CMake printout and IDE organisation for pybind11's own tests. - `#3479 `_ - -* CMake: report version type as part of the version string to avoid a spurious - space in the package status message. - `#3472 `_ - -* Flags starting with ``-g`` in ``$CFLAGS`` and ``$CPPFLAGS`` are no longer - overridden by ``.Pybind11Extension``. - `#3436 `_ - -* Ensure ThreadPool is closed in ``setup_helpers``. - `#3548 `_ - -* Avoid LTS on ``mips64`` and ``ppc64le`` (reported broken). - `#3557 `_ - - -v2.8.1 (Oct 27, 2021) ---------------------- - -Changes and additions: - -* The simple namespace creation shortcut added in 2.8.0 was deprecated due to - usage of CPython internal API, and will be removed soon. Use - ``py::module_::import("types").attr("SimpleNamespace")``. - `#3374 `_ - -* Add C++ Exception type to throw and catch ``AttributeError``. Useful for - defining custom ``__setattr__`` and ``__getattr__`` methods. - `#3387 `_ - -Fixes: - -* Fixed the potential for dangling references when using properties with - ``std::optional`` types. - `#3376 `_ - -* Modernize usage of ``PyCodeObject`` on Python 3.9+ (moving toward support for - Python 3.11a1) - `#3368 `_ - -* A long-standing bug in ``eigen.h`` was fixed (originally PR #3343). The bug - was unmasked by newly added ``static_assert``'s in the Eigen 3.4.0 release. - `#3352 `_ - -* Support multiple raw inclusion of CMake helper files (Conan.io does this for - multi-config generators). - `#3420 `_ - -* Fix harmless warning on upcoming CMake 3.22. - `#3368 `_ - -* Fix 2.8.0 regression with MSVC 2017 + C++17 mode + Python 3. - `#3407 `_ - -* Fix 2.8.0 regression that caused undefined behavior (typically - segfaults) in ``make_key_iterator``/``make_value_iterator`` if dereferencing - the iterator returned a temporary value instead of a reference. - `#3348 `_ - - -v2.8.0 (Oct 4, 2021) --------------------- - -New features: - -* Added ``py::raise_from`` to enable chaining exceptions. - `#3215 `_ - -* Allow exception translators to be optionally registered local to a module - instead of applying globally across all pybind11 modules. Use - ``register_local_exception_translator(ExceptionTranslator&& translator)`` - instead of ``register_exception_translator(ExceptionTranslator&& - translator)`` to keep your exception remapping code local to the module. - `#2650 `_ - -* Add ``make_simple_namespace`` function for instantiating Python - ``SimpleNamespace`` objects. **Deprecated in 2.8.1.** - `#2840 `_ - -* ``pybind11::scoped_interpreter`` and ``initialize_interpreter`` have new - arguments to allow ``sys.argv`` initialization. - `#2341 `_ - -* Allow Python builtins to be used as callbacks in CPython. - `#1413 `_ - -* Added ``view`` to view arrays with a different datatype. - `#987 `_ - -* Implemented ``reshape`` on arrays. - `#984 `_ - -* Enable defining custom ``__new__`` methods on classes by fixing bug - preventing overriding methods if they have non-pybind11 siblings. - `#3265 `_ - -* Add ``make_value_iterator()``, and fix ``make_key_iterator()`` to return - references instead of copies. - `#3293 `_ - -* Improve the classes generated by ``bind_map``: `#3310 `_ - - * Change ``.items`` from an iterator to a dictionary view. - * Add ``.keys`` and ``.values`` (both dictionary views). - * Allow ``__contains__`` to take any object. - -* ``pybind11::custom_type_setup`` was added, for customizing the - ``PyHeapTypeObject`` corresponding to a class, which may be useful for - enabling garbage collection support, among other things. - `#3287 `_ - - -Changes: - -* Set ``__file__`` constant when running ``eval_file`` in an embedded interpreter. - `#3233 `_ - -* Python objects and (C++17) ``std::optional`` now accepted in ``py::slice`` - constructor. - `#1101 `_ - -* The pybind11 proxy types ``str``, ``bytes``, ``bytearray``, ``tuple``, - ``list`` now consistently support passing ``ssize_t`` values for sizes and - indexes. Previously, only ``size_t`` was accepted in several interfaces. - `#3219 `_ - -* Avoid evaluating ``PYBIND11_TLS_REPLACE_VALUE`` arguments more than once. - `#3290 `_ - -Fixes: - -* Bug fix: enum value's ``__int__`` returning non-int when underlying type is - bool or of char type. - `#1334 `_ - -* Fixes bug in setting error state in Capsule's pointer methods. - `#3261 `_ - -* A long-standing memory leak in ``py::cpp_function::initialize`` was fixed. - `#3229 `_ - -* Fixes thread safety for some ``pybind11::type_caster`` which require lifetime - extension, such as for ``std::string_view``. - `#3237 `_ - -* Restore compatibility with gcc 4.8.4 as distributed by ubuntu-trusty, linuxmint-17. - `#3270 `_ - - -Build system improvements: - -* Fix regression in CMake Python package config: improper use of absolute path. - `#3144 `_ - -* Cached Python version information could become stale when CMake was re-run - with a different Python version. The build system now detects this and - updates this information. - `#3299 `_ - -* Specified UTF8-encoding in setup.py calls of open(). - `#3137 `_ - -* Fix a harmless warning from CMake 3.21 with the classic Python discovery. - `#3220 `_ - -* Eigen repo and version can now be specified as cmake options. - `#3324 `_ - - -Backend and tidying up: - -* Reduced thread-local storage required for keeping alive temporary data for - type conversion to one key per ABI version, rather than one key per extension - module. This makes the total thread-local storage required by pybind11 2 - keys per ABI version. - `#3275 `_ - -* Optimize NumPy array construction with additional moves. - `#3183 `_ - -* Conversion to ``std::string`` and ``std::string_view`` now avoids making an - extra copy of the data on Python >= 3.3. - `#3257 `_ - -* Remove const modifier from certain C++ methods on Python collections - (``list``, ``set``, ``dict``) such as (``clear()``, ``append()``, - ``insert()``, etc...) and annotated them with ``py-non-const``. - -* Enable readability ``clang-tidy-const-return`` and remove useless consts. - `#3254 `_ - `#3194 `_ - -* The clang-tidy ``google-explicit-constructor`` option was enabled. - `#3250 `_ - -* Mark a pytype move constructor as noexcept (perf). - `#3236 `_ - -* Enable clang-tidy check to guard against inheritance slicing. - `#3210 `_ - -* Legacy warning suppression pragma were removed from eigen.h. On Unix - platforms, please use -isystem for Eigen include directories, to suppress - compiler warnings originating from Eigen headers. Note that CMake does this - by default. No adjustments are needed for Windows. - `#3198 `_ - -* Format pybind11 with isort consistent ordering of imports - `#3195 `_ - -* The warnings-suppression "pragma clamp" at the top/bottom of pybind11 was - removed, clearing the path to refactoring and IWYU cleanup. - `#3186 `_ - -* Enable most bugprone checks in clang-tidy and fix the found potential bugs - and poor coding styles. - `#3166 `_ - -* Add ``clang-tidy-readability`` rules to make boolean casts explicit improving - code readability. Also enabled other misc and readability clang-tidy checks. - `#3148 `_ - -* Move object in ``.pop()`` for list. - `#3116 `_ - - - - -v2.7.1 (Aug 3, 2021) ---------------------- - -Minor missing functionality added: - -* Allow Python builtins to be used as callbacks in CPython. - `#1413 `_ - -Bug fixes: - -* Fix regression in CMake Python package config: improper use of absolute path. - `#3144 `_ - -* Fix Mingw64 and add to the CI testing matrix. - `#3132 `_ - -* Specified UTF8-encoding in setup.py calls of open(). - `#3137 `_ - -* Add clang-tidy-readability rules to make boolean casts explicit improving - code readability. Also enabled other misc and readability clang-tidy checks. - `#3148 `_ - -* Move object in ``.pop()`` for list. - `#3116 `_ - -Backend and tidying up: - -* Removed and fixed warning suppressions. - `#3127 `_ - `#3129 `_ - `#3135 `_ - `#3141 `_ - `#3142 `_ - `#3150 `_ - `#3152 `_ - `#3160 `_ - `#3161 `_ - - -v2.7.0 (Jul 16, 2021) ---------------------- - -New features: - -* Enable ``py::implicitly_convertible`` for - ``py::class_``-wrapped types. - `#3059 `_ - -* Allow function pointer extraction from overloaded functions. - `#2944 `_ - -* NumPy: added ``.char_()`` to type which gives the NumPy public ``char`` - result, which also distinguishes types by bit length (unlike ``.kind()``). - `#2864 `_ - -* Add ``pybind11::bytearray`` to manipulate ``bytearray`` similar to ``bytes``. - `#2799 `_ - -* ``pybind11/stl/filesystem.h`` registers a type caster that, on C++17/Python - 3.6+, converts ``std::filesystem::path`` to ``pathlib.Path`` and any - ``os.PathLike`` to ``std::filesystem::path``. - `#2730 `_ - -* A ``PYBIND11_VERSION_HEX`` define was added, similar to ``PY_VERSION_HEX``. - `#3120 `_ - - - -Changes: - -* ``py::str`` changed to exclusively hold ``PyUnicodeObject``. Previously - ``py::str`` could also hold ``bytes``, which is probably surprising, was - never documented, and can mask bugs (e.g. accidental use of ``py::str`` - instead of ``py::bytes``). - `#2409 `_ - -* Add a safety guard to ensure that the Python GIL is held when C++ calls back - into Python via ``object_api<>::operator()`` (e.g. ``py::function`` - ``__call__``). (This feature is available for Python 3.6+ only.) - `#2919 `_ - -* Catch a missing ``self`` argument in calls to ``__init__()``. - `#2914 `_ - -* Use ``std::string_view`` if available to avoid a copy when passing an object - to a ``std::ostream``. - `#3042 `_ - -* An important warning about thread safety was added to the ``iostream.h`` - documentation; attempts to make ``py::scoped_ostream_redirect`` thread safe - have been removed, as it was only partially effective. - `#2995 `_ - - -Fixes: - -* Performance: avoid unnecessary strlen calls. - `#3058 `_ - -* Fix auto-generated documentation string when using ``const T`` in - ``pyarray_t``. - `#3020 `_ - -* Unify error messages thrown by ``simple_collector``/``unpacking_collector``. - `#3013 `_ - -* ``pybind11::builtin_exception`` is now explicitly exported, which means the - types included/defined in different modules are identical, and exceptions - raised in different modules can be caught correctly. The documentation was - updated to explain that custom exceptions that are used across module - boundaries need to be explicitly exported as well. - `#2999 `_ - -* Fixed exception when printing UTF-8 to a ``scoped_ostream_redirect``. - `#2982 `_ - -* Pickle support enhancement: ``setstate`` implementation will attempt to - ``setattr`` ``__dict__`` only if the unpickled ``dict`` object is not empty, - to not force use of ``py::dynamic_attr()`` unnecessarily. - `#2972 `_ - -* Allow negative timedelta values to roundtrip. - `#2870 `_ - -* Fix unchecked errors could potentially swallow signals/other exceptions. - `#2863 `_ - -* Add null pointer check with ``std::localtime``. - `#2846 `_ - -* Fix the ``weakref`` constructor from ``py::object`` to create a new - ``weakref`` on conversion. - `#2832 `_ - -* Avoid relying on exceptions in C++17 when getting a ``shared_ptr`` holder - from a ``shared_from_this`` class. - `#2819 `_ - -* Allow the codec's exception to be raised instead of :code:`RuntimeError` when - casting from :code:`py::str` to :code:`std::string`. - `#2903 `_ - - -Build system improvements: - -* In ``setup_helpers.py``, test for platforms that have some multiprocessing - features but lack semaphores, which ``ParallelCompile`` requires. - `#3043 `_ - -* Fix ``pybind11_INCLUDE_DIR`` in case ``CMAKE_INSTALL_INCLUDEDIR`` is - absolute. - `#3005 `_ - -* Fix bug not respecting ``WITH_SOABI`` or ``WITHOUT_SOABI`` to CMake. - `#2938 `_ - -* Fix the default ``Pybind11Extension`` compilation flags with a Mingw64 python. - `#2921 `_ - -* Clang on Windows: do not pass ``/MP`` (ignored flag). - `#2824 `_ - -* ``pybind11.setup_helpers.intree_extensions`` can be used to generate - ``Pybind11Extension`` instances from cpp files placed in the Python package - source tree. - `#2831 `_ - -Backend and tidying up: - -* Enable clang-tidy performance, readability, and modernization checks - throughout the codebase to enforce best coding practices. - `#3046 `_, - `#3049 `_, - `#3051 `_, - `#3052 `_, - `#3080 `_, and - `#3094 `_ - - -* Checks for common misspellings were added to the pre-commit hooks. - `#3076 `_ - -* Changed ``Werror`` to stricter ``Werror-all`` for Intel compiler and fixed - minor issues. - `#2948 `_ - -* Fixed compilation with GCC < 5 when the user defines ``_GLIBCXX_USE_CXX11_ABI``. - `#2956 `_ - -* Added nox support for easier local testing and linting of contributions. - `#3101 `_ and - `#3121 `_ - -* Avoid RTD style issue with docutils 0.17+. - `#3119 `_ - -* Support pipx run, such as ``pipx run pybind11 --include`` for a quick compile. - `#3117 `_ - - - -v2.6.2 (Jan 26, 2021) ---------------------- - -Minor missing functionality added: - -* enum: add missing Enum.value property. - `#2739 `_ - -* Allow thread termination to be avoided during shutdown for CPython 3.7+ via - ``.disarm`` for ``gil_scoped_acquire``/``gil_scoped_release``. - `#2657 `_ - -Fixed or improved behavior in a few special cases: - -* Fix bug where the constructor of ``object`` subclasses would not throw on - being passed a Python object of the wrong type. - `#2701 `_ - -* The ``type_caster`` for integers does not convert Python objects with - ``__int__`` anymore with ``noconvert`` or during the first round of trying - overloads. - `#2698 `_ - -* When casting to a C++ integer, ``__index__`` is always called and not - considered as conversion, consistent with Python 3.8+. - `#2801 `_ - -Build improvements: - -* Setup helpers: ``extra_compile_args`` and ``extra_link_args`` automatically set by - Pybind11Extension are now prepended, which allows them to be overridden - by user-set ``extra_compile_args`` and ``extra_link_args``. - `#2808 `_ - -* Setup helpers: Don't trigger unused parameter warning. - `#2735 `_ - -* CMake: Support running with ``--warn-uninitialized`` active. - `#2806 `_ - -* CMake: Avoid error if included from two submodule directories. - `#2804 `_ - -* CMake: Fix ``STATIC`` / ``SHARED`` being ignored in FindPython mode. - `#2796 `_ - -* CMake: Respect the setting for ``CMAKE_CXX_VISIBILITY_PRESET`` if defined. - `#2793 `_ - -* CMake: Fix issue with FindPython2/FindPython3 not working with ``pybind11::embed``. - `#2662 `_ - -* CMake: mixing local and installed pybind11's would prioritize the installed - one over the local one (regression in 2.6.0). - `#2716 `_ - - -Bug fixes: - -* Fixed segfault in multithreaded environments when using - ``scoped_ostream_redirect``. - `#2675 `_ - -* Leave docstring unset when all docstring-related options are disabled, rather - than set an empty string. - `#2745 `_ - -* The module key in builtins that pybind11 uses to store its internals changed - from std::string to a python str type (more natural on Python 2, no change on - Python 3). - `#2814 `_ - -* Fixed assertion error related to unhandled (later overwritten) exception in - CPython 3.8 and 3.9 debug builds. - `#2685 `_ - -* Fix ``py::gil_scoped_acquire`` assert with CPython 3.9 debug build. - `#2683 `_ - -* Fix issue with a test failing on pytest 6.2. - `#2741 `_ - -Warning fixes: - -* Fix warning modifying constructor parameter 'flag' that shadows a field of - 'set_flag' ``[-Wshadow-field-in-constructor-modified]``. - `#2780 `_ - -* Suppressed some deprecation warnings about old-style - ``__init__``/``__setstate__`` in the tests. - `#2759 `_ - -Valgrind work: - -* Fix invalid access when calling a pybind11 ``__init__`` on a non-pybind11 - class instance. - `#2755 `_ - -* Fixed various minor memory leaks in pybind11's test suite. - `#2758 `_ - -* Resolved memory leak in cpp_function initialization when exceptions occurred. - `#2756 `_ - -* Added a Valgrind build, checking for leaks and memory-related UB, to CI. - `#2746 `_ - -Compiler support: - -* Intel compiler was not activating C++14 support due to a broken define. - `#2679 `_ - -* Support ICC and NVIDIA HPC SDK in C++17 mode. - `#2729 `_ - -* Support Intel OneAPI compiler (ICC 20.2) and add to CI. - `#2573 `_ - - - -v2.6.1 (Nov 11, 2020) ---------------------- - -* ``py::exec``, ``py::eval``, and ``py::eval_file`` now add the builtins module - as ``"__builtins__"`` to their ``globals`` argument, better matching ``exec`` - and ``eval`` in pure Python. - `#2616 `_ - -* ``setup_helpers`` will no longer set a minimum macOS version higher than the - current version. - `#2622 `_ - -* Allow deleting static properties. - `#2629 `_ - -* Seal a leak in ``def_buffer``, cleaning up the ``capture`` object after the - ``class_`` object goes out of scope. - `#2634 `_ - -* ``pybind11_INCLUDE_DIRS`` was incorrect, potentially causing a regression if - it was expected to include ``PYTHON_INCLUDE_DIRS`` (please use targets - instead). - `#2636 `_ - -* Added parameter names to the ``py::enum_`` constructor and methods, avoiding - ``arg0`` in the generated docstrings. - `#2637 `_ - -* Added ``needs_recompile`` optional function to the ``ParallelCompiler`` - helper, to allow a recompile to be skipped based on a user-defined function. - `#2643 `_ - - -v2.6.0 (Oct 21, 2020) ---------------------- - -See :ref:`upgrade-guide-2.6` for help upgrading to the new version. - -New features: - -* Keyword-only arguments supported in Python 2 or 3 with ``py::kw_only()``. - `#2100 `_ - -* Positional-only arguments supported in Python 2 or 3 with ``py::pos_only()``. - `#2459 `_ - -* ``py::is_final()`` class modifier to block subclassing (CPython only). - `#2151 `_ - -* Added ``py::prepend()``, allowing a function to be placed at the beginning of - the overload chain. - `#1131 `_ - -* Access to the type object now provided with ``py::type::of()`` and - ``py::type::of(h)``. - `#2364 `_ - -* Perfect forwarding support for methods. - `#2048 `_ - -* Added ``py::error_already_set::discard_as_unraisable()``. - `#2372 `_ - -* ``py::hash`` is now public. - `#2217 `_ - -* ``py::class_`` is now supported. Note that writing to one data - member of the union and reading another (type punning) is UB in C++. Thus - pybind11-bound enums should never be used for such conversions. - `#2320 `_. - -* Classes now check local scope when registering members, allowing a subclass - to have a member with the same name as a parent (such as an enum). - `#2335 `_ - -Code correctness features: - -* Error now thrown when ``__init__`` is forgotten on subclasses. - `#2152 `_ - -* Throw error if conversion to a pybind11 type if the Python object isn't a - valid instance of that type, such as ``py::bytes(o)`` when ``py::object o`` - isn't a bytes instance. - `#2349 `_ - -* Throw if conversion to ``str`` fails. - `#2477 `_ - - -API changes: - -* ``py::module`` was renamed ``py::module_`` to avoid issues with C++20 when - used unqualified, but an alias ``py::module`` is provided for backward - compatibility. - `#2489 `_ - -* Public constructors for ``py::module_`` have been deprecated; please use - ``pybind11::module_::create_extension_module`` if you were using the public - constructor (fairly rare after ``PYBIND11_MODULE`` was introduced). - `#2552 `_ - -* ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function replaced by - correctly-named ``PYBIND11_OVERRIDE*`` and ``get_override``, fixing - inconsistencies in the presence of a closing ``;`` in these macros. - ``get_type_overload`` is deprecated. - `#2325 `_ - -Packaging / building improvements: - -* The Python package was reworked to be more powerful and useful. - `#2433 `_ - - * :ref:`build-setuptools` is easier thanks to a new - ``pybind11.setup_helpers`` module, which provides utilities to use - setuptools with pybind11. It can be used via PEP 518, ``setup_requires``, - or by directly importing or copying ``setup_helpers.py`` into your project. - - * CMake configuration files are now included in the Python package. Use - ``pybind11.get_cmake_dir()`` or ``python -m pybind11 --cmakedir`` to get - the directory with the CMake configuration files, or include the - site-packages location in your ``CMAKE_MODULE_PATH``. Or you can use the - new ``pybind11[global]`` extra when you install ``pybind11``, which - installs the CMake files and headers into your base environment in the - standard location. - - * ``pybind11-config`` is another way to write ``python -m pybind11`` if you - have your PATH set up. - - * Added external typing support to the helper module, code from - ``import pybind11`` can now be type checked. - `#2588 `_ - -* Minimum CMake required increased to 3.4. - `#2338 `_ and - `#2370 `_ - - * Full integration with CMake's C++ standard system and compile features - replaces ``PYBIND11_CPP_STANDARD``. - - * Generated config file is now portable to different Python/compiler/CMake - versions. - - * Virtual environments prioritized if ``PYTHON_EXECUTABLE`` is not set - (``venv``, ``virtualenv``, and ``conda``) (similar to the new FindPython - mode). - - * Other CMake features now natively supported, like - ``CMAKE_INTERPROCEDURAL_OPTIMIZATION``, ``set(CMAKE_CXX_VISIBILITY_PRESET - hidden)``. - - * ``CUDA`` as a language is now supported. - - * Helper functions ``pybind11_strip``, ``pybind11_extension``, - ``pybind11_find_import`` added, see :doc:`cmake/index`. - - * Optional :ref:`find-python-mode` and :ref:`nopython-mode` with CMake. - `#2370 `_ - -* Uninstall target added. - `#2265 `_ and - `#2346 `_ - -* ``pybind11_add_module()`` now accepts an optional ``OPT_SIZE`` flag that - switches the binding target to size-based optimization if the global build - type can not always be fixed to ``MinSizeRel`` (except in debug mode, where - optimizations remain disabled). ``MinSizeRel`` or this flag reduces binary - size quite substantially (~25% on some platforms). - `#2463 `_ - -Smaller or developer focused features and fixes: - -* Moved ``mkdoc.py`` to a new repo, `pybind11-mkdoc`_. There are no longer - submodules in the main repo. - -* ``py::memoryview`` segfault fix and update, with new - ``py::memoryview::from_memory`` in Python 3, and documentation. - `#2223 `_ - -* Fix for ``buffer_info`` on Python 2. - `#2503 `_ - -* If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to - ``None``. - `#2291 `_ - -* ``py::ellipsis`` now also works on Python 2. - `#2360 `_ - -* Pointer to ``std::tuple`` & ``std::pair`` supported in cast. - `#2334 `_ - -* Small fixes in NumPy support. ``py::array`` now uses ``py::ssize_t`` as first - argument type. - `#2293 `_ - -* Added missing signature for ``py::array``. - `#2363 `_ - -* ``unchecked_mutable_reference`` has access to operator ``()`` and ``[]`` when - const. - `#2514 `_ - -* ``py::vectorize`` is now supported on functions that return void. - `#1969 `_ - -* ``py::capsule`` supports ``get_pointer`` and ``set_pointer``. - `#1131 `_ - -* Fix crash when different instances share the same pointer of the same type. - `#2252 `_ - -* Fix for ``py::len`` not clearing Python's error state when it fails and throws. - `#2575 `_ - -* Bugfixes related to more extensive testing, new GitHub Actions CI. - `#2321 `_ - -* Bug in timezone issue in Eastern hemisphere midnight fixed. - `#2438 `_ - -* ``std::chrono::time_point`` now works when the resolution is not the same as - the system. - `#2481 `_ - -* Bug fixed where ``py::array_t`` could accept arrays that did not match the - requested ordering. - `#2484 `_ - -* Avoid a segfault on some compilers when types are removed in Python. - `#2564 `_ - -* ``py::arg::none()`` is now also respected when passing keyword arguments. - `#2611 `_ - -* PyPy fixes, PyPy 7.3.x now supported, including PyPy3. (Known issue with - PyPy2 and Windows `#2596 `_). - `#2146 `_ - -* CPython 3.9.0 workaround for undefined behavior (macOS segfault). - `#2576 `_ - -* CPython 3.9 warning fixes. - `#2253 `_ - -* Improved C++20 support, now tested in CI. - `#2489 `_ - `#2599 `_ - -* Improved but still incomplete debug Python interpreter support. - `#2025 `_ - -* NVCC (CUDA 11) now supported and tested in CI. - `#2461 `_ - -* NVIDIA PGI compilers now supported and tested in CI. - `#2475 `_ - -* At least Intel 18 now explicitly required when compiling with Intel. - `#2577 `_ - -* Extensive style checking in CI, with `pre-commit`_ support. Code - modernization, checked by clang-tidy. - -* Expanded docs, including new main page, new installing section, and CMake - helpers page, along with over a dozen new sections on existing pages. - -* In GitHub, new docs for contributing and new issue templates. - -.. _pre-commit: https://pre-commit.com - -.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc - -v2.5.0 (Mar 31, 2020) ------------------------------------------------------ - -* Use C++17 fold expressions in type casters, if available. This can - improve performance during overload resolution when functions have - multiple arguments. - `#2043 `_. - -* Changed include directory resolution in ``pybind11/__init__.py`` - and installation in ``setup.py``. This fixes a number of open issues - where pybind11 headers could not be found in certain environments. - `#1995 `_. - -* C++20 ``char8_t`` and ``u8string`` support. `#2026 - `_. - -* CMake: search for Python 3.9. `bb9c91 - `_. - -* Fixes for MSYS-based build environments. - `#2087 `_, - `#2053 `_. - -* STL bindings for ``std::vector<...>::clear``. `#2074 - `_. - -* Read-only flag for ``py::buffer``. `#1466 - `_. - -* Exception handling during module initialization. - `bf2b031 `_. - -* Support linking against a CPython debug build. - `#2025 `_. - -* Fixed issues involving the availability and use of aligned ``new`` and - ``delete``. `#1988 `_, - `759221 `_. - -* Fixed a resource leak upon interpreter shutdown. - `#2020 `_. - -* Fixed error handling in the boolean caster. - `#1976 `_. - -v2.4.3 (Oct 15, 2019) ------------------------------------------------------ - -* Adapt pybind11 to a C API convention change in Python 3.8. `#1950 - `_. - -v2.4.2 (Sep 21, 2019) ------------------------------------------------------ - -* Replaced usage of a C++14 only construct. `#1929 - `_. - -* Made an ifdef future-proof for Python >= 4. `f3109d - `_. - -v2.4.1 (Sep 20, 2019) ------------------------------------------------------ - -* Fixed a problem involving implicit conversion from enumerations to integers - on Python 3.8. `#1780 `_. - -v2.4.0 (Sep 19, 2019) ------------------------------------------------------ - -* Try harder to keep pybind11-internal data structures separate when there - are potential ABI incompatibilities. Fixes crashes that occurred when loading - multiple pybind11 extensions that were e.g. compiled by GCC (libstdc++) - and Clang (libc++). - `#1588 `_ and - `c9f5a `_. - -* Added support for ``__await__``, ``__aiter__``, and ``__anext__`` protocols. - `#1842 `_. - -* ``pybind11_add_module()``: don't strip symbols when compiling in - ``RelWithDebInfo`` mode. `#1980 - `_. - -* ``enum_``: Reproduce Python behavior when comparing against invalid values - (e.g. ``None``, strings, etc.). Add back support for ``__invert__()``. - `#1912 `_, - `#1907 `_. - -* List insertion operation for ``py::list``. - Added ``.empty()`` to all collection types. - Added ``py::set::contains()`` and ``py::dict::contains()``. - `#1887 `_, - `#1884 `_, - `#1888 `_. - -* ``py::details::overload_cast_impl`` is available in C++11 mode, can be used - like ``overload_cast`` with an additional set of parentheses. - `#1581 `_. - -* Fixed ``get_include()`` on Conda. - `#1877 `_. - -* ``stl_bind.h``: negative indexing support. - `#1882 `_. - -* Minor CMake fix to add MinGW compatibility. - `#1851 `_. - -* GIL-related fixes. - `#1836 `_, - `8b90b `_. - -* Other very minor/subtle fixes and improvements. - `#1329 `_, - `#1910 `_, - `#1863 `_, - `#1847 `_, - `#1890 `_, - `#1860 `_, - `#1848 `_, - `#1821 `_, - `#1837 `_, - `#1833 `_, - `#1748 `_, - `#1852 `_. - -v2.3.0 (June 11, 2019) ------------------------------------------------------ - -* Significantly reduced module binary size (10-20%) when compiled in C++11 mode - with GCC/Clang, or in any mode with MSVC. Function signatures are now always - precomputed at compile time (this was previously only available in C++14 mode - for non-MSVC compilers). - `#934 `_. - -* Add basic support for tag-based static polymorphism, where classes - provide a method to returns the desired type of an instance. - `#1326 `_. - -* Python type wrappers (``py::handle``, ``py::object``, etc.) - now support map Python's number protocol onto C++ arithmetic - operators such as ``operator+``, ``operator/=``, etc. - `#1511 `_. - -* A number of improvements related to enumerations: - - 1. The ``enum_`` implementation was rewritten from scratch to reduce - code bloat. Rather than instantiating a full implementation for each - enumeration, most code is now contained in a generic base class. - `#1511 `_. - - 2. The ``value()`` method of ``py::enum_`` now accepts an optional - docstring that will be shown in the documentation of the associated - enumeration. `#1160 `_. - - 3. check for already existing enum value and throw an error if present. - `#1453 `_. - -* Support for over-aligned type allocation via C++17's aligned ``new`` - statement. `#1582 `_. - -* Added ``py::ellipsis()`` method for slicing of multidimensional NumPy arrays - `#1502 `_. - -* Numerous Improvements to the ``mkdoc.py`` script for extracting documentation - from C++ header files. - `#1788 `_. - -* ``pybind11_add_module()``: allow including Python as a ``SYSTEM`` include path. - `#1416 `_. - -* ``pybind11/stl.h`` does not convert strings to ``vector`` anymore. - `#1258 `_. - -* Mark static methods as such to fix auto-generated Sphinx documentation. - `#1732 `_. - -* Re-throw forced unwind exceptions (e.g. during pthread termination). - `#1208 `_. - -* Added ``__contains__`` method to the bindings of maps (``std::map``, - ``std::unordered_map``). - `#1767 `_. - -* Improvements to ``gil_scoped_acquire``. - `#1211 `_. - -* Type caster support for ``std::deque``. - `#1609 `_. - -* Support for ``std::unique_ptr`` holders, whose deleters differ between a base and derived - class. `#1353 `_. - -* Construction of STL array/vector-like data structures from - iterators. Added an ``extend()`` operation. - `#1709 `_, - -* CMake build system improvements for projects that include non-C++ - files (e.g. plain C, CUDA) in ``pybind11_add_module`` et al. - `#1678 `_. - -* Fixed asynchronous invocation and deallocation of Python functions - wrapped in ``std::function``. - `#1595 `_. - -* Fixes regarding return value policy propagation in STL type casters. - `#1603 `_. - -* Fixed scoped enum comparisons. - `#1571 `_. - -* Fixed iostream redirection for code that releases the GIL. - `#1368 `_, - -* A number of CI-related fixes. - `#1757 `_, - `#1744 `_, - `#1670 `_. - -v2.2.4 (September 11, 2018) ------------------------------------------------------ - -* Use new Python 3.7 Thread Specific Storage (TSS) implementation if available. - `#1454 `_, - `#1517 `_. - -* Fixes for newer MSVC versions and C++17 mode. - `#1347 `_, - `#1462 `_. - -* Propagate return value policies to type-specific casters - when casting STL containers. - `#1455 `_. - -* Allow ostream-redirection of more than 1024 characters. - `#1479 `_. - -* Set ``Py_DEBUG`` define when compiling against a debug Python build. - `#1438 `_. - -* Untangle integer logic in number type caster to work for custom - types that may only be castable to a restricted set of builtin types. - `#1442 `_. - -* CMake build system: Remember Python version in cache file. - `#1434 `_. - -* Fix for custom smart pointers: use ``std::addressof`` to obtain holder - address instead of ``operator&``. - `#1435 `_. - -* Properly report exceptions thrown during module initialization. - `#1362 `_. - -* Fixed a segmentation fault when creating empty-shaped NumPy array. - `#1371 `_. - -* The version of Intel C++ compiler must be >= 2017, and this is now checked by - the header files. `#1363 `_. - -* A few minor typo fixes and improvements to the test suite, and - patches that silence compiler warnings. - -* Vectors now support construction from generators, as well as ``extend()`` from a - list or generator. - `#1496 `_. - - -v2.2.3 (April 29, 2018) ------------------------------------------------------ - -* The pybind11 header location detection was replaced by a new implementation - that no longer depends on ``pip`` internals (the recently released ``pip`` - 10 has restricted access to this API). - `#1190 `_. - -* Small adjustment to an implementation detail to work around a compiler segmentation fault in Clang 3.3/3.4. - `#1350 `_. - -* The minimal supported version of the Intel compiler was >= 17.0 since - pybind11 v2.1. This check is now explicit, and a compile-time error is raised - if the compiler meet the requirement. - `#1363 `_. - -* Fixed an endianness-related fault in the test suite. - `#1287 `_. - -v2.2.2 (February 7, 2018) ------------------------------------------------------ - -* Fixed a segfault when combining embedded interpreter - shutdown/reinitialization with external loaded pybind11 modules. - `#1092 `_. - -* Eigen support: fixed a bug where Nx1/1xN numpy inputs couldn't be passed as - arguments to Eigen vectors (which for Eigen are simply compile-time fixed - Nx1/1xN matrices). - `#1106 `_. - -* Clarified to license by moving the licensing of contributions from - ``LICENSE`` into ``CONTRIBUTING.md``: the licensing of contributions is not - actually part of the software license as distributed. This isn't meant to be - a substantial change in the licensing of the project, but addresses concerns - that the clause made the license non-standard. - `#1109 `_. - -* Fixed a regression introduced in 2.1 that broke binding functions with lvalue - character literal arguments. - `#1128 `_. - -* MSVC: fix for compilation failures under /permissive-, and added the flag to - the appveyor test suite. - `#1155 `_. - -* Fixed ``__qualname__`` generation, and in turn, fixes how class names - (especially nested class names) are shown in generated docstrings. - `#1171 `_. - -* Updated the FAQ with a suggested project citation reference. - `#1189 `_. - -* Added fixes for deprecation warnings when compiled under C++17 with - ``-Wdeprecated`` turned on, and add ``-Wdeprecated`` to the test suite - compilation flags. - `#1191 `_. - -* Fixed outdated PyPI URLs in ``setup.py``. - `#1213 `_. - -* Fixed a refcount leak for arguments that end up in a ``py::args`` argument - for functions with both fixed positional and ``py::args`` arguments. - `#1216 `_. - -* Fixed a potential segfault resulting from possible premature destruction of - ``py::args``/``py::kwargs`` arguments with overloaded functions. - `#1223 `_. - -* Fixed ``del map[item]`` for a ``stl_bind.h`` bound stl map. - `#1229 `_. - -* Fixed a regression from v2.1.x where the aggregate initialization could - unintentionally end up at a constructor taking a templated - ``std::initializer_list`` argument. - `#1249 `_. - -* Fixed an issue where calling a function with a keep_alive policy on the same - nurse/patient pair would cause the internal patient storage to needlessly - grow (unboundedly, if the nurse is long-lived). - `#1251 `_. - -* Various other minor fixes. - -v2.2.1 (September 14, 2017) ------------------------------------------------------ - -* Added ``py::module_::reload()`` member function for reloading a module. - `#1040 `_. - -* Fixed a reference leak in the number converter. - `#1078 `_. - -* Fixed compilation with Clang on host GCC < 5 (old libstdc++ which isn't fully - C++11 compliant). `#1062 `_. - -* Fixed a regression where the automatic ``std::vector`` caster would - fail to compile. The same fix also applies to any container which returns - element proxies instead of references. - `#1053 `_. - -* Fixed a regression where the ``py::keep_alive`` policy could not be applied - to constructors. `#1065 `_. - -* Fixed a nullptr dereference when loading a ``py::module_local`` type - that's only registered in an external module. - `#1058 `_. - -* Fixed implicit conversion of accessors to types derived from ``py::object``. - `#1076 `_. - -* The ``name`` in ``PYBIND11_MODULE(name, variable)`` can now be a macro. - `#1082 `_. - -* Relaxed overly strict ``py::pickle()`` check for matching get and set types. - `#1064 `_. - -* Conversion errors now try to be more informative when it's likely that - a missing header is the cause (e.g. forgetting ````). - `#1077 `_. - -v2.2.0 (August 31, 2017) ------------------------------------------------------ - -* Support for embedding the Python interpreter. See the - :doc:`documentation page ` for a - full overview of the new features. - `#774 `_, - `#889 `_, - `#892 `_, - `#920 `_. - - .. code-block:: cpp - - #include - namespace py = pybind11; - - int main() { - py::scoped_interpreter guard{}; // start the interpreter and keep it alive - - py::print("Hello, World!"); // use the Python API - } - -* Support for inheriting from multiple C++ bases in Python. - `#693 `_. - - .. code-block:: python - - from cpp_module import CppBase1, CppBase2 - - - class PyDerived(CppBase1, CppBase2): - def __init__(self): - CppBase1.__init__(self) # C++ bases must be initialized explicitly - CppBase2.__init__(self) - -* ``PYBIND11_MODULE`` is now the preferred way to create module entry points. - ``PYBIND11_PLUGIN`` is deprecated. See :ref:`macros` for details. - `#879 `_. - - .. code-block:: cpp - - // new - PYBIND11_MODULE(example, m) { - m.def("add", [](int a, int b) { return a + b; }); - } - - // old - PYBIND11_PLUGIN(example) { - py::module m("example"); - m.def("add", [](int a, int b) { return a + b; }); - return m.ptr(); - } - -* pybind11's headers and build system now more strictly enforce hidden symbol - visibility for extension modules. This should be seamless for most users, - but see the :doc:`upgrade` if you use a custom build system. - `#995 `_. - -* Support for ``py::module_local`` types which allow multiple modules to - export the same C++ types without conflicts. This is useful for opaque - types like ``std::vector``. ``py::bind_vector`` and ``py::bind_map`` - now default to ``py::module_local`` if their elements are builtins or - local types. See :ref:`module_local` for details. - `#949 `_, - `#981 `_, - `#995 `_, - `#997 `_. - -* Custom constructors can now be added very easily using lambdas or factory - functions which return a class instance by value, pointer or holder. This - supersedes the old placement-new ``__init__`` technique. - See :ref:`custom_constructors` for details. - `#805 `_, - `#1014 `_. - - .. code-block:: cpp - - struct Example { - Example(std::string); - }; - - py::class_(m, "Example") - .def(py::init()) // existing constructor - .def(py::init([](int n) { // custom constructor - return std::make_unique(std::to_string(n)); - })); - -* Similarly to custom constructors, pickling support functions are now bound - using the ``py::pickle()`` adaptor which improves type safety. See the - :doc:`upgrade` and :ref:`pickling` for details. - `#1038 `_. - -* Builtin support for converting C++17 standard library types and general - conversion improvements: - - 1. C++17 ``std::variant`` is supported right out of the box. C++11/14 - equivalents (e.g. ``boost::variant``) can also be added with a simple - user-defined specialization. See :ref:`cpp17_container_casters` for details. - `#811 `_, - `#845 `_, - `#989 `_. - - 2. Out-of-the-box support for C++17 ``std::string_view``. - `#906 `_. - - 3. Improved compatibility of the builtin ``optional`` converter. - `#874 `_. - - 4. The ``bool`` converter now accepts ``numpy.bool_`` and types which - define ``__bool__`` (Python 3.x) or ``__nonzero__`` (Python 2.7). - `#925 `_. - - 5. C++-to-Python casters are now more efficient and move elements out - of rvalue containers whenever possible. - `#851 `_, - `#936 `_, - `#938 `_. - - 6. Fixed ``bytes`` to ``std::string/char*`` conversion on Python 3. - `#817 `_. - - 7. Fixed lifetime of temporary C++ objects created in Python-to-C++ conversions. - `#924 `_. - -* Scope guard call policy for RAII types, e.g. ``py::call_guard()``, - ``py::call_guard()``. See :ref:`call_policies` for details. - `#740 `_. - -* Utility for redirecting C++ streams to Python (e.g. ``std::cout`` -> - ``sys.stdout``). Scope guard ``py::scoped_ostream_redirect`` in C++ and - a context manager in Python. See :ref:`ostream_redirect`. - `#1009 `_. - -* Improved handling of types and exceptions across module boundaries. - `#915 `_, - `#951 `_, - `#995 `_. - -* Fixed destruction order of ``py::keep_alive`` nurse/patient objects - in reference cycles. - `#856 `_. - -* NumPy and buffer protocol related improvements: - - 1. Support for negative strides in Python buffer objects/numpy arrays. This - required changing integers from unsigned to signed for the related C++ APIs. - Note: If you have compiler warnings enabled, you may notice some new conversion - warnings after upgrading. These can be resolved with ``static_cast``. - `#782 `_. - - 2. Support ``std::complex`` and arrays inside ``PYBIND11_NUMPY_DTYPE``. - `#831 `_, - `#832 `_. - - 3. Support for constructing ``py::buffer_info`` and ``py::arrays`` using - arbitrary containers or iterators instead of requiring a ``std::vector``. - `#788 `_, - `#822 `_, - `#860 `_. - - 4. Explicitly check numpy version and require >= 1.7.0. - `#819 `_. - -* Support for allowing/prohibiting ``None`` for specific arguments and improved - ``None`` overload resolution order. See :ref:`none_arguments` for details. - `#843 `_. - `#859 `_. - -* Added ``py::exec()`` as a shortcut for ``py::eval()`` - and support for C++11 raw string literals as input. See :ref:`eval`. - `#766 `_, - `#827 `_. - -* ``py::vectorize()`` ignores non-vectorizable arguments and supports - member functions. - `#762 `_. - -* Support for bound methods as callbacks (``pybind11/functional.h``). - `#815 `_. - -* Allow aliasing pybind11 methods: ``cls.attr("foo") = cls.attr("bar")``. - `#802 `_. - -* Don't allow mixed static/non-static overloads. - `#804 `_. - -* Fixed overriding static properties in derived classes. - `#784 `_. - -* Added support for write only properties. - `#1144 `_. - -* Improved deduction of member functions of a derived class when its bases - aren't registered with pybind11. - `#855 `_. - - .. code-block:: cpp - - struct Base { - int foo() { return 42; } - } - - struct Derived : Base {} - - // Now works, but previously required also binding `Base` - py::class_(m, "Derived") - .def("foo", &Derived::foo); // function is actually from `Base` - -* The implementation of ``py::init<>`` now uses C++11 brace initialization - syntax to construct instances, which permits binding implicit constructors of - aggregate types. `#1015 `_. - - .. code-block:: cpp - - struct Aggregate { - int a; - std::string b; - }; - - py::class_(m, "Aggregate") - .def(py::init()); - -* Fixed issues with multiple inheritance with offset base/derived pointers. - `#812 `_, - `#866 `_, - `#960 `_. - -* Fixed reference leak of type objects. - `#1030 `_. - -* Improved support for the ``/std:c++14`` and ``/std:c++latest`` modes - on MSVC 2017. - `#841 `_, - `#999 `_. - -* Fixed detection of private operator new on MSVC. - `#893 `_, - `#918 `_. - -* Intel C++ compiler compatibility fixes. - `#937 `_. - -* Fixed implicit conversion of ``py::enum_`` to integer types on Python 2.7. - `#821 `_. - -* Added ``py::hash`` to fetch the hash value of Python objects, and - ``.def(hash(py::self))`` to provide the C++ ``std::hash`` as the Python - ``__hash__`` method. - `#1034 `_. - -* Fixed ``__truediv__`` on Python 2 and ``__itruediv__`` on Python 3. - `#867 `_. - -* ``py::capsule`` objects now support the ``name`` attribute. This is useful - for interfacing with ``scipy.LowLevelCallable``. - `#902 `_. - -* Fixed ``py::make_iterator``'s ``__next__()`` for past-the-end calls. - `#897 `_. - -* Added ``error_already_set::matches()`` for checking Python exceptions. - `#772 `_. - -* Deprecated ``py::error_already_set::clear()``. It's no longer needed - following a simplification of the ``py::error_already_set`` class. - `#954 `_. - -* Deprecated ``py::handle::operator==()`` in favor of ``py::handle::is()`` - `#825 `_. - -* Deprecated ``py::object::borrowed``/``py::object::stolen``. - Use ``py::object::borrowed_t{}``/``py::object::stolen_t{}`` instead. - `#771 `_. - -* Changed internal data structure versioning to avoid conflicts between - modules compiled with different revisions of pybind11. - `#1012 `_. - -* Additional compile-time and run-time error checking and more informative messages. - `#786 `_, - `#794 `_, - `#803 `_. - -* Various minor improvements and fixes. - `#764 `_, - `#791 `_, - `#795 `_, - `#840 `_, - `#844 `_, - `#846 `_, - `#849 `_, - `#858 `_, - `#862 `_, - `#871 `_, - `#872 `_, - `#881 `_, - `#888 `_, - `#899 `_, - `#928 `_, - `#931 `_, - `#944 `_, - `#950 `_, - `#952 `_, - `#962 `_, - `#965 `_, - `#970 `_, - `#978 `_, - `#979 `_, - `#986 `_, - `#1020 `_, - `#1027 `_, - `#1037 `_. - -* Testing improvements. - `#798 `_, - `#882 `_, - `#898 `_, - `#900 `_, - `#921 `_, - `#923 `_, - `#963 `_. - -v2.1.1 (April 7, 2017) ------------------------------------------------------ - -* Fixed minimum version requirement for MSVC 2015u3 - `#773 `_. - -v2.1.0 (March 22, 2017) ------------------------------------------------------ - -* pybind11 now performs function overload resolution in two phases. The first - phase only considers exact type matches, while the second allows for implicit - conversions to take place. A special ``noconvert()`` syntax can be used to - completely disable implicit conversions for specific arguments. - `#643 `_, - `#634 `_, - `#650 `_. - -* Fixed a regression where static properties no longer worked with classes - using multiple inheritance. The ``py::metaclass`` attribute is no longer - necessary (and deprecated as of this release) when binding classes with - static properties. - `#679 `_, - -* Classes bound using ``pybind11`` can now use custom metaclasses. - `#679 `_, - -* ``py::args`` and ``py::kwargs`` can now be mixed with other positional - arguments when binding functions using pybind11. - `#611 `_. - -* Improved support for C++11 unicode string and character types; added - extensive documentation regarding pybind11's string conversion behavior. - `#624 `_, - `#636 `_, - `#715 `_. - -* pybind11 can now avoid expensive copies when converting Eigen arrays to NumPy - arrays (and vice versa). `#610 `_. - -* The "fast path" in ``py::vectorize`` now works for any full-size group of C or - F-contiguous arrays. The non-fast path is also faster since it no longer performs - copies of the input arguments (except when type conversions are necessary). - `#610 `_. - -* Added fast, unchecked access to NumPy arrays via a proxy object. - `#746 `_. - -* Transparent support for class-specific ``operator new`` and - ``operator delete`` implementations. - `#755 `_. - -* Slimmer and more efficient STL-compatible iterator interface for sequence types. - `#662 `_. - -* Improved custom holder type support. - `#607 `_. - -* ``nullptr`` to ``None`` conversion fixed in various builtin type casters. - `#732 `_. - -* ``enum_`` now exposes its members via a special ``__members__`` attribute. - `#666 `_. - -* ``std::vector`` bindings created using ``stl_bind.h`` can now optionally - implement the buffer protocol. `#488 `_. - -* Automated C++ reference documentation using doxygen and breathe. - `#598 `_. - -* Added minimum compiler version assertions. - `#727 `_. - -* Improved compatibility with C++1z. - `#677 `_. - -* Improved ``py::capsule`` API. Can be used to implement cleanup - callbacks that are involved at module destruction time. - `#752 `_. - -* Various minor improvements and fixes. - `#595 `_, - `#588 `_, - `#589 `_, - `#603 `_, - `#619 `_, - `#648 `_, - `#695 `_, - `#720 `_, - `#723 `_, - `#729 `_, - `#724 `_, - `#742 `_, - `#753 `_. - -v2.0.1 (Jan 4, 2017) ------------------------------------------------------ - -* Fix pointer to reference error in type_caster on MSVC - `#583 `_. - -* Fixed a segmentation in the test suite due to a typo - `cd7eac `_. - -v2.0.0 (Jan 1, 2017) ------------------------------------------------------ - -* Fixed a reference counting regression affecting types with custom metaclasses - (introduced in v2.0.0-rc1). - `#571 `_. - -* Quenched a CMake policy warning. - `#570 `_. - -v2.0.0-rc1 (Dec 23, 2016) ------------------------------------------------------ - -The pybind11 developers are excited to issue a release candidate of pybind11 -with a subsequent v2.0.0 release planned in early January next year. - -An incredible amount of effort by went into pybind11 over the last ~5 months, -leading to a release that is jam-packed with exciting new features and numerous -usability improvements. The following list links PRs or individual commits -whenever applicable. - -Happy Christmas! - -* Support for binding C++ class hierarchies that make use of multiple - inheritance. `#410 `_. - -* PyPy support: pybind11 now supports nightly builds of PyPy and will - interoperate with the future 5.7 release. No code changes are necessary, - everything "just" works as usual. Note that we only target the Python 2.7 - branch for now; support for 3.x will be added once its ``cpyext`` extension - support catches up. A few minor features remain unsupported for the time - being (notably dynamic attributes in custom types). - `#527 `_. - -* Significant work on the documentation -- in particular, the monolithic - ``advanced.rst`` file was restructured into a easier to read hierarchical - organization. `#448 `_. - -* Many NumPy-related improvements: - - 1. Object-oriented API to access and modify NumPy ``ndarray`` instances, - replicating much of the corresponding NumPy C API functionality. - `#402 `_. - - 2. NumPy array ``dtype`` array descriptors are now first-class citizens and - are exposed via a new class ``py::dtype``. - - 3. Structured dtypes can be registered using the ``PYBIND11_NUMPY_DTYPE()`` - macro. Special ``array`` constructors accepting dtype objects were also - added. - - One potential caveat involving this change: format descriptor strings - should now be accessed via ``format_descriptor::format()`` (however, for - compatibility purposes, the old syntax ``format_descriptor::value`` will - still work for non-structured data types). `#308 - `_. - - 4. Further improvements to support structured dtypes throughout the system. - `#472 `_, - `#474 `_, - `#459 `_, - `#453 `_, - `#452 `_, and - `#505 `_. - - 5. Fast access operators. `#497 `_. - - 6. Constructors for arrays whose storage is owned by another object. - `#440 `_. - - 7. Added constructors for ``array`` and ``array_t`` explicitly accepting shape - and strides; if strides are not provided, they are deduced assuming - C-contiguity. Also added simplified constructors for 1-dimensional case. - - 8. Added buffer/NumPy support for ``char[N]`` and ``std::array`` types. - - 9. Added ``memoryview`` wrapper type which is constructible from ``buffer_info``. - -* Eigen: many additional conversions and support for non-contiguous - arrays/slices. - `#427 `_, - `#315 `_, - `#316 `_, - `#312 `_, and - `#267 `_ - -* Incompatible changes in ``class_<...>::class_()``: - - 1. Declarations of types that provide access via the buffer protocol must - now include the ``py::buffer_protocol()`` annotation as an argument to - the ``class_`` constructor. - - 2. Declarations of types that require a custom metaclass (i.e. all classes - which include static properties via commands such as - ``def_readwrite_static()``) must now include the ``py::metaclass()`` - annotation as an argument to the ``class_`` constructor. - - These two changes were necessary to make type definitions in pybind11 - future-proof, and to support PyPy via its cpyext mechanism. `#527 - `_. - - - 3. This version of pybind11 uses a redesigned mechanism for instantiating - trampoline classes that are used to override virtual methods from within - Python. This led to the following user-visible syntax change: instead of - - .. code-block:: cpp - - py::class_("MyClass") - .alias() - .... - - write - - .. code-block:: cpp - - py::class_("MyClass") - .... - - Importantly, both the original and the trampoline class are now - specified as an arguments (in arbitrary order) to the ``py::class_`` - template, and the ``alias<..>()`` call is gone. The new scheme has zero - overhead in cases when Python doesn't override any functions of the - underlying C++ class. `rev. 86d825 - `_. - -* Added ``eval`` and ``eval_file`` functions for evaluating expressions and - statements from a string or file. `rev. 0d3fc3 - `_. - -* pybind11 can now create types with a modifiable dictionary. - `#437 `_ and - `#444 `_. - -* Support for translation of arbitrary C++ exceptions to Python counterparts. - `#296 `_ and - `#273 `_. - -* Report full backtraces through mixed C++/Python code, better reporting for - import errors, fixed GIL management in exception processing. - `#537 `_, - `#494 `_, - `rev. e72d95 `_, and - `rev. 099d6e `_. - -* Support for bit-level operations, comparisons, and serialization of C++ - enumerations. `#503 `_, - `#508 `_, - `#380 `_, - `#309 `_. - `#311 `_. - -* The ``class_`` constructor now accepts its template arguments in any order. - `#385 `_. - -* Attribute and item accessors now have a more complete interface which makes - it possible to chain attributes as in - ``obj.attr("a")[key].attr("b").attr("method")(1, 2, 3)``. `#425 - `_. - -* Major redesign of the default and conversion constructors in ``pytypes.h``. - `#464 `_. - -* Added built-in support for ``std::shared_ptr`` holder type. It is no longer - necessary to to include a declaration of the form - ``PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr)`` (though continuing to - do so won't cause an error). - `#454 `_. - -* New ``py::overload_cast`` casting operator to select among multiple possible - overloads of a function. An example: - - .. code-block:: cpp - - py::class_(m, "Pet") - .def("set", py::overload_cast(&Pet::set), "Set the pet's age") - .def("set", py::overload_cast(&Pet::set), "Set the pet's name"); - - This feature only works on C++14-capable compilers. - `#541 `_. - -* C++ types are automatically cast to Python types, e.g. when assigning - them as an attribute. For instance, the following is now legal: - - .. code-block:: cpp - - py::module m = /* ... */ - m.attr("constant") = 123; - - (Previously, a ``py::cast`` call was necessary to avoid a compilation error.) - `#551 `_. - -* Redesigned ``pytest``-based test suite. `#321 `_. - -* Instance tracking to detect reference leaks in test suite. `#324 `_ - -* pybind11 can now distinguish between multiple different instances that are - located at the same memory address, but which have different types. - `#329 `_. - -* Improved logic in ``move`` return value policy. - `#510 `_, - `#297 `_. - -* Generalized unpacking API to permit calling Python functions from C++ using - notation such as ``foo(a1, a2, *args, "ka"_a=1, "kb"_a=2, **kwargs)``. `#372 `_. - -* ``py::print()`` function whose behavior matches that of the native Python - ``print()`` function. `#372 `_. - -* Added ``py::dict`` keyword constructor:``auto d = dict("number"_a=42, - "name"_a="World");``. `#372 `_. - -* Added ``py::str::format()`` method and ``_s`` literal: ``py::str s = "1 + 2 - = {}"_s.format(3);``. `#372 `_. - -* Added ``py::repr()`` function which is equivalent to Python's builtin - ``repr()``. `#333 `_. - -* Improved construction and destruction logic for holder types. It is now - possible to reference instances with smart pointer holder types without - constructing the holder if desired. The ``PYBIND11_DECLARE_HOLDER_TYPE`` - macro now accepts an optional second parameter to indicate whether the holder - type uses intrusive reference counting. - `#533 `_ and - `#561 `_. - -* Mapping a stateless C++ function to Python and back is now "for free" (i.e. - no extra indirections or argument conversion overheads). `rev. 954b79 - `_. - -* Bindings for ``std::valarray``. - `#545 `_. - -* Improved support for C++17 capable compilers. - `#562 `_. - -* Bindings for ``std::optional``. - `#475 `_, - `#476 `_, - `#479 `_, - `#499 `_, and - `#501 `_. - -* ``stl_bind.h``: general improvements and support for ``std::map`` and - ``std::unordered_map``. - `#490 `_, - `#282 `_, - `#235 `_. - -* The ``std::tuple``, ``std::pair``, ``std::list``, and ``std::vector`` type - casters now accept any Python sequence type as input. `rev. 107285 - `_. - -* Improved CMake Python detection on multi-architecture Linux. - `#532 `_. - -* Infrastructure to selectively disable or enable parts of the automatically - generated docstrings. `#486 `_. - -* ``reference`` and ``reference_internal`` are now the default return value - properties for static and non-static properties, respectively. `#473 - `_. (the previous defaults - were ``automatic``). `#473 `_. - -* Support for ``std::unique_ptr`` with non-default deleters or no deleter at - all (``py::nodelete``). `#384 `_. - -* Deprecated ``handle::call()`` method. The new syntax to call Python - functions is simply ``handle()``. It can also be invoked explicitly via - ``handle::operator()``, where ``X`` is an optional return value policy. - -* Print more informative error messages when ``make_tuple()`` or ``cast()`` - fail. `#262 `_. - -* Creation of holder types for classes deriving from - ``std::enable_shared_from_this<>`` now also works for ``const`` values. - `#260 `_. - -* ``make_iterator()`` improvements for better compatibility with various - types (now uses prefix increment operator); it now also accepts iterators - with different begin/end types as long as they are equality comparable. - `#247 `_. - -* ``arg()`` now accepts a wider range of argument types for default values. - `#244 `_. - -* Support ``keep_alive`` where the nurse object may be ``None``. `#341 - `_. - -* Added constructors for ``str`` and ``bytes`` from zero-terminated char - pointers, and from char pointers and length. Added constructors for ``str`` - from ``bytes`` and for ``bytes`` from ``str``, which will perform UTF-8 - decoding/encoding as required. - -* Many other improvements of library internals without user-visible changes - - -1.8.1 (July 12, 2016) ----------------------- -* Fixed a rare but potentially very severe issue when the garbage collector ran - during pybind11 type creation. - -1.8.0 (June 14, 2016) ----------------------- -* Redesigned CMake build system which exports a convenient - ``pybind11_add_module`` function to parent projects. -* ``std::vector<>`` type bindings analogous to Boost.Python's ``indexing_suite`` -* Transparent conversion of sparse and dense Eigen matrices and vectors (``eigen.h``) -* Added an ``ExtraFlags`` template argument to the NumPy ``array_t<>`` wrapper - to disable an enforced cast that may lose precision, e.g. to create overloads - for different precisions and complex vs real-valued matrices. -* Prevent implicit conversion of floating point values to integral types in - function arguments -* Fixed incorrect default return value policy for functions returning a shared - pointer -* Don't allow registering a type via ``class_`` twice -* Don't allow casting a ``None`` value into a C++ lvalue reference -* Fixed a crash in ``enum_::operator==`` that was triggered by the ``help()`` command -* Improved detection of whether or not custom C++ types can be copy/move-constructed -* Extended ``str`` type to also work with ``bytes`` instances -* Added a ``"name"_a`` user defined string literal that is equivalent to ``py::arg("name")``. -* When specifying function arguments via ``py::arg``, the test that verifies - the number of arguments now runs at compile time. -* Added ``[[noreturn]]`` attribute to ``pybind11_fail()`` to quench some - compiler warnings -* List function arguments in exception text when the dispatch code cannot find - a matching overload -* Added ``PYBIND11_OVERLOAD_NAME`` and ``PYBIND11_OVERLOAD_PURE_NAME`` macros which - can be used to override virtual methods whose name differs in C++ and Python - (e.g. ``__call__`` and ``operator()``) -* Various minor ``iterator`` and ``make_iterator()`` improvements -* Transparently support ``__bool__`` on Python 2.x and Python 3.x -* Fixed issue with destructor of unpickled object not being called -* Minor CMake build system improvements on Windows -* New ``pybind11::args`` and ``pybind11::kwargs`` types to create functions which - take an arbitrary number of arguments and keyword arguments -* New syntax to call a Python function from C++ using ``*args`` and ``*kwargs`` -* The functions ``def_property_*`` now correctly process docstring arguments (these - formerly caused a segmentation fault) -* Many ``mkdoc.py`` improvements (enumerations, template arguments, ``DOC()`` - macro accepts more arguments) -* Cygwin support -* Documentation improvements (pickling support, ``keep_alive``, macro usage) - -1.7 (April 30, 2016) ----------------------- -* Added a new ``move`` return value policy that triggers C++11 move semantics. - The automatic return value policy falls back to this case whenever a rvalue - reference is encountered -* Significantly more general GIL state routines that are used instead of - Python's troublesome ``PyGILState_Ensure`` and ``PyGILState_Release`` API -* Redesign of opaque types that drastically simplifies their usage -* Extended ability to pass values of type ``[const] void *`` -* ``keep_alive`` fix: don't fail when there is no patient -* ``functional.h``: acquire the GIL before calling a Python function -* Added Python RAII type wrappers ``none`` and ``iterable`` -* Added ``*args`` and ``*kwargs`` pass-through parameters to - ``pybind11.get_include()`` function -* Iterator improvements and fixes -* Documentation on return value policies and opaque types improved - -1.6 (April 30, 2016) ----------------------- -* Skipped due to upload to PyPI gone wrong and inability to recover - (https://github.com/pypa/packaging-problems/issues/74) - -1.5 (April 21, 2016) ----------------------- -* For polymorphic types, use RTTI to try to return the closest type registered with pybind11 -* Pickling support for serializing and unserializing C++ instances to a byte stream in Python -* Added a convenience routine ``make_iterator()`` which turns a range indicated - by a pair of C++ iterators into a iterable Python object -* Added ``len()`` and a variadic ``make_tuple()`` function -* Addressed a rare issue that could confuse the current virtual function - dispatcher and another that could lead to crashes in multi-threaded - applications -* Added a ``get_include()`` function to the Python module that returns the path - of the directory containing the installed pybind11 header files -* Documentation improvements: import issues, symbol visibility, pickling, limitations -* Added casting support for ``std::reference_wrapper<>`` - -1.4 (April 7, 2016) --------------------------- -* Transparent type conversion for ``std::wstring`` and ``wchar_t`` -* Allow passing ``nullptr``-valued strings -* Transparent passing of ``void *`` pointers using capsules -* Transparent support for returning values wrapped in ``std::unique_ptr<>`` -* Improved docstring generation for compatibility with Sphinx -* Nicer debug error message when default parameter construction fails -* Support for "opaque" types that bypass the transparent conversion layer for STL containers -* Redesigned type casting interface to avoid ambiguities that could occasionally cause compiler errors -* Redesigned property implementation; fixes crashes due to an unfortunate default return value policy -* Anaconda package generation support - -1.3 (March 8, 2016) --------------------------- - -* Added support for the Intel C++ compiler (v15+) -* Added support for the STL unordered set/map data structures -* Added support for the STL linked list data structure -* NumPy-style broadcasting support in ``pybind11::vectorize`` -* pybind11 now displays more verbose error messages when ``arg::operator=()`` fails -* pybind11 internal data structures now live in a version-dependent namespace to avoid ABI issues -* Many, many bugfixes involving corner cases and advanced usage - -1.2 (February 7, 2016) --------------------------- - -* Optional: efficient generation of function signatures at compile time using C++14 -* Switched to a simpler and more general way of dealing with function default - arguments. Unused keyword arguments in function calls are now detected and - cause errors as expected -* New ``keep_alive`` call policy analogous to Boost.Python's ``with_custodian_and_ward`` -* New ``pybind11::base<>`` attribute to indicate a subclass relationship -* Improved interface for RAII type wrappers in ``pytypes.h`` -* Use RAII type wrappers consistently within pybind11 itself. This - fixes various potential refcount leaks when exceptions occur -* Added new ``bytes`` RAII type wrapper (maps to ``string`` in Python 2.7) -* Made handle and related RAII classes const correct, using them more - consistently everywhere now -* Got rid of the ugly ``__pybind11__`` attributes on the Python side---they are - now stored in a C++ hash table that is not visible in Python -* Fixed refcount leaks involving NumPy arrays and bound functions -* Vastly improved handling of shared/smart pointers -* Removed an unnecessary copy operation in ``pybind11::vectorize`` -* Fixed naming clashes when both pybind11 and NumPy headers are included -* Added conversions for additional exception types -* Documentation improvements (using multiple extension modules, smart pointers, - other minor clarifications) -* unified infrastructure for parsing variadic arguments in ``class_`` and cpp_function -* Fixed license text (was: ZLIB, should have been: 3-clause BSD) -* Python 3.2 compatibility -* Fixed remaining issues when accessing types in another plugin module -* Added enum comparison and casting methods -* Improved SFINAE-based detection of whether types are copy-constructible -* Eliminated many warnings about unused variables and the use of ``offsetof()`` -* Support for ``std::array<>`` conversions - -1.1 (December 7, 2015) --------------------------- - -* Documentation improvements (GIL, wrapping functions, casting, fixed many typos) -* Generalized conversion of integer types -* Improved support for casting function objects -* Improved support for ``std::shared_ptr<>`` conversions -* Initial support for ``std::set<>`` conversions -* Fixed type resolution issue for types defined in a separate plugin module -* CMake build system improvements -* Factored out generic functionality to non-templated code (smaller code size) -* Added a code size / compile time benchmark vs Boost.Python -* Added an appveyor CI script - -1.0 (October 15, 2015) ------------------------- -* Initial release +.. _changelog: + +Changelog +######### + +Starting with version 1.8.0, pybind11 releases use a `semantic versioning +`_ policy. + +Changes will be added here periodically from the "Suggested changelog entry" +block in pull request descriptions. + + +IN DEVELOPMENT +-------------- + +Changes will be summarized here periodically. + +Version 2.12.0 (March 27, 2025) +------------------------------- + +New Features: + +* ``pybind11`` now supports compiling for + `NumPy 2 `_. Most + code shouldn't change (see :ref:`upgrade-guide-2.12` for details). However, + if you experience issues you can define ``PYBIND11_NUMPY_1_ONLY`` to disable + the new support for now, but this will be removed in the future. + `#5050 `_ + +* ``pybind11/gil_safe_call_once.h`` was added (it needs to be included + explicitly). The primary use case is GIL-safe initialization of C++ + ``static`` variables. + `#4877 `_ + +* Support move-only iterators in ``py::make_iterator``, + ``py::make_key_iterator``, ``py::make_value_iterator``. + `#4834 `_ + +* Two simple ``py::set_error()`` functions were added and the documentation was + updated accordingly. In particular, ``py::exception<>::operator()`` was + deprecated (use one of the new functions instead). The documentation for + ``py::exception<>`` was further updated to not suggest code that may result + in undefined behavior. + `#4772 `_ + +Bug fixes: + +* Removes potential for Undefined Behavior during process teardown. + `#4897 `_ + +* Improve compatibility with the nvcc compiler (especially CUDA 12.1/12.2). + `#4893 `_ + +* ``pybind11/numpy.h`` now imports NumPy's ``multiarray`` and ``_internal`` + submodules with paths depending on the installed version of NumPy (for + compatibility with NumPy 2). + `#4857 `_ + +* Builtins collections names in docstrings are now consistently rendered in + lowercase (list, set, dict, tuple), in accordance with PEP 585. + `#4833 `_ + +* Added ``py::typing::Iterator``, ``py::typing::Iterable``. + `#4832 `_ + +* Render ``py::function`` as ``Callable`` in docstring. + `#4829 `_ + +* Also bump ``PYBIND11_INTERNALS_VERSION`` for MSVC, which unlocks two new + features without creating additional incompatibilities. + `#4819 `_ + +* Guard against crashes/corruptions caused by modules built with different MSVC + versions. + `#4779 `_ + +* A long-standing bug in the handling of Python multiple inheritance was fixed. + See PR #4762 for the rather complex details. + `#4762 `_ + +* Fix ``bind_map`` with ``using`` declarations. + `#4952 `_ + +* Qualify ``py::detail::concat`` usage to avoid ADL selecting one from + somewhere else, such as modernjson's concat. + `#4955 `_ + +* Use new PyCode API on Python 3.12+. + `#4916 `_ + +* Minor cleanup from warnings reported by Clazy. + `#4988 `_ + +* Remove typing and duplicate ``class_`` for ``KeysView``/``ValuesView``/``ItemsView``. + `#4985 `_ + +* Use ``PyObject_VisitManagedDict()`` and ``PyObject_ClearManagedDict()`` on Python 3.13 and newer. + `#4973 `_ + +* Update ``make_static_property_type()`` to make it compatible with Python 3.13. + `#4971 `_ + +.. fix(types) + +* Render typed iterators for ``make_iterator``, ``make_key_iterator``, + ``make_value_iterator``. + `#4876 `_ + +* Add several missing type name specializations. + `#5073 `_ + +* Change docstring render for ``py::buffer``, ``py::sequence`` and + ``py::handle`` (to ``Buffer``, ``Sequence``, ``Any``). + `#4831 `_ + +* Fixed ``base_enum.__str__`` docstring. + `#4827 `_ + +* Enforce single line docstring signatures. + `#4735 `_ + +* Special 'typed' wrappers now available in ``typing.h`` to annotate tuple, dict, + list, set, and function. + `#4259 `_ + +* Create ``handle_type_name`` specialization to type-hint variable length tuples. + `#5051 `_ + +.. fix(build) + +* Setting ``PYBIND11_FINDPYTHON`` to OFF will force the old FindPythonLibs mechanism to be used. + `#5042 `_ + +* Skip empty ``PYBIND11_PYTHON_EXECUTABLE_LAST`` for the first cmake run. + `#4856 `_ + +* Fix FindPython mode exports & avoid ``pkg_resources`` if + ``importlib.metadata`` available. + `#4941 `_ + +* ``Python_ADDITIONAL_VERSIONS`` (classic search) now includes 3.12. + `#4909 `_ + +* ``pybind11.pc`` is now relocatable by default as long as install destinations + are not absolute paths. + `#4830 `_ + +* Correctly detect CMake FindPython removal when used as a subdirectory. + `#4806 `_ + +* Don't require the libs component on CMake 3.18+ when using + PYBIND11_FINDPYTHON (fixes manylinux builds). + `#4805 `_ + +* ``pybind11_strip`` is no longer automatically applied when + ``CMAKE_BUILD_TYPE`` is unset. + `#4780 `_ + +* Support ``DEBUG_POSFIX`` correctly for debug builds. + `#4761 `_ + +* Hardcode lto/thin lto for Emscripten cross-compiles. + `#4642 `_ + +* Upgrade maximum supported CMake version to 3.27 to fix CMP0148 warnings. + `#4786 `_ + +Documentation: + +* Small fix to grammar in ``functions.rst``. + `#4791 `_ + +* Remove upper bound in example pyproject.toml for setuptools. + `#4774 `_ + +CI: + +* CI: Update NVHPC to 23.5 and Ubuntu 20.04. + `#4764 `_ + +* Test on PyPy 3.10. + `#4714 `_ + +Other: + +* Use Ruff formatter instead of Black. + `#4912 `_ + +* An ``assert()`` was added to help Coverty avoid generating a false positive. + `#4817 `_ + + +Version 2.11.1 (July 17, 2023) +------------------------------ + +Changes: + +* ``PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF`` is now provided as an option + for disabling the default-on ``PyGILState_Check()``'s in + ``pybind11::handle``'s ``inc_ref()`` & ``dec_ref()``. + `#4753 `_ + +* ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`` was disabled for PyPy in general + (not just PyPy Windows). + `#4751 `_ + + +Version 2.11.0 (July 14, 2023) +------------------------------ + +New features: + +* The newly added ``pybind11::detail::is_move_constructible`` trait can be + specialized for cases in which ``std::is_move_constructible`` does not work + as needed. This is very similar to the long-established + ``pybind11::detail::is_copy_constructible``. + `#4631 `_ + +* Introduce ``recursive_container_traits``. + `#4623 `_ + +* ``pybind11/type_caster_pyobject_ptr.h`` was added to support automatic + wrapping of APIs that make use of ``PyObject *``. This header needs to + included explicitly (i.e. it is not included implicitly + with ``pybind/pybind11.h``). + `#4601 `_ + +* ``format_descriptor<>`` & ``npy_format_descriptor<>`` ``PyObject *`` + specializations were added. The latter enables ``py::array_t`` + to/from-python conversions. + `#4674 `_ + +* ``buffer_info`` gained an ``item_type_is_equivalent_to()`` member + function. + `#4674 `_ + +* The ``capsule`` API gained a user-friendly constructor + (``py::capsule(ptr, "name", dtor)``). + `#4720 `_ + +Changes: + +* ``PyGILState_Check()``'s in ``pybind11::handle``'s ``inc_ref()`` & + ``dec_ref()`` are now enabled by default again. + `#4246 `_ + +* ``py::initialize_interpreter()`` using ``PyConfig_InitPythonConfig()`` + instead of ``PyConfig_InitIsolatedConfig()``, to obtain complete + ``sys.path``. + `#4473 `_ + +* Cast errors now always include Python type information, even if + ``PYBIND11_DETAILED_ERROR_MESSAGES`` is not defined. This increases binary + sizes slightly (~1.5%) but the error messages are much more informative. + `#4463 `_ + +* The docstring generation for the ``std::array``-list caster was fixed. + Previously, signatures included the size of the list in a non-standard, + non-spec compliant way. The new format conforms to PEP 593. + **Tooling for processing the docstrings may need to be updated accordingly.** + `#4679 `_ + +* Setter return values (which are inaccessible for all practical purposes) are + no longer converted to Python (only to be discarded). + `#4621 `_ + +* Allow lambda specified to function definition to be ``noexcept(true)`` + in C++17. + `#4593 `_ + +* Get rid of recursive template instantiations for concatenating type + signatures on C++17 and higher. + `#4587 `_ + +* Compatibility with Python 3.12 (beta). Note that the minimum pybind11 + ABI version for Python 3.12 is version 5. (The default ABI version + for Python versions up to and including 3.11 is still version 4.). + `#4570 `_ + +* With ``PYBIND11_INTERNALS_VERSION 5`` (default for Python 3.12+), MSVC builds + use ``std::hash`` and ``std::equal_to`` + instead of string-based type comparisons. This resolves issues when binding + types defined in the unnamed namespace. + `#4319 `_ + +* Python exception ``__notes__`` (introduced with Python 3.11) are now added to + the ``error_already_set::what()`` output. + `#4678 `_ + +Build system improvements: + +* CMake 3.27 support was added, CMake 3.4 support was dropped. + FindPython will be used if ``FindPythonInterp`` is not present. + `#4719 `_ + +* Update clang-tidy to 15 in CI. + `#4387 `_ + +* Moved the linting framework over to Ruff. + `#4483 `_ + +* Skip ``lto`` checks and target generation when + ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is defined. + `#4643 `_ + +* No longer inject ``-stdlib=libc++``, not needed for modern Pythons + (macOS 10.9+). + `#4639 `_ + +* PyPy 3.10 support was added, PyPy 3.7 support was dropped. + `#4728 `_ + +* Testing with Python 3.12 beta releases was added. + `#4713 `_ + + +Version 2.10.4 (Mar 16, 2023) +----------------------------- + +Changes: + +* ``python3 -m pybind11`` gained a ``--version`` option (prints the version and + exits). + `#4526 `_ + +Bug Fixes: + +* Fix a warning when pydebug is enabled on Python 3.11. + `#4461 `_ + +* Ensure ``gil_scoped_release`` RAII is non-copyable. + `#4490 `_ + +* Ensure the tests dir does not show up with new versions of setuptools. + `#4510 `_ + +* Better stacklevel for a warning in setuptools helpers. + `#4516 `_ + +Version 2.10.3 (Jan 3, 2023) +---------------------------- + +Changes: + +* Temporarily made our GIL status assertions (added in 2.10.2) disabled by + default (re-enable manually by defining + ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF``, will be enabled in 2.11). + `#4432 `_ + +* Improved error messages when ``inc_ref``/``dec_ref`` are called with an + invalid GIL state. + `#4427 `_ + `#4436 `_ + +Bug Fixes: + +* Some minor touchups found by static analyzers. + `#4440 `_ + + +Version 2.10.2 (Dec 20, 2022) +----------------------------- + +Changes: + +* ``scoped_interpreter`` constructor taking ``PyConfig``. + `#4330 `_ + +* ``pybind11/eigen/tensor.h`` adds converters to and from ``Eigen::Tensor`` and + ``Eigen::TensorMap``. + `#4201 `_ + +* ``PyGILState_Check()``'s were integrated to ``pybind11::handle`` + ``inc_ref()`` & ``dec_ref()``. The added GIL checks are guarded by + ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF``, which is the default only if + ``NDEBUG`` is not defined. (Made non-default in 2.10.3, will be active in 2.11) + `#4246 `_ + +* Add option for enable/disable enum members in docstring. + `#2768 `_ + +* Fixed typing of ``KeysView``, ``ValuesView`` and ``ItemsView`` in ``bind_map``. + `#4353 `_ + +Bug fixes: + +* Bug fix affecting only Python 3.6 under very specific, uncommon conditions: + move ``PyEval_InitThreads()`` call to the correct location. + `#4350 `_ + +* Fix segfault bug when passing foreign native functions to functional.h. + `#4254 `_ + +Build system improvements: + +* Support setting PYTHON_LIBRARIES manually for Windows ARM cross-compilation + (classic mode). + `#4406 `_ + +* Extend IPO/LTO detection for ICX (a.k.a IntelLLVM) compiler. + `#4402 `_ + +* Allow calling ``find_package(pybind11 CONFIG)`` multiple times from separate + directories in the same CMake project and properly link Python (new mode). + `#4401 `_ + +* ``multiprocessing_set_spawn`` in pytest fixture for added safety. + `#4377 `_ + +* Fixed a bug in two pybind11/tools cmake scripts causing "Unknown arguments specified" errors. + `#4327 `_ + + + +Version 2.10.1 (Oct 31, 2022) +----------------------------- + +This is the first version to fully support embedding the newly released Python 3.11. + +Changes: + +* Allow ``pybind11::capsule`` constructor to take null destructor pointers. + `#4221 `_ + +* ``embed.h`` was changed so that ``PYTHONPATH`` is used also with Python 3.11 + (established behavior). + `#4119 `_ + +* A ``PYBIND11_SIMPLE_GIL_MANAGEMENT`` option was added (cmake, C++ define), + along with many additional tests in ``test_gil_scoped.py``. The option may be + useful to try when debugging GIL-related issues, to determine if the more + complex default implementation is or is not to blame. See #4216 for + background. WARNING: Please be careful to not create ODR violations when + using the option: everything that is linked together with mutual symbol + visibility needs to be rebuilt. + `#4216 `_ + +* ``PYBIND11_EXPORT_EXCEPTION`` was made non-empty only under macOS. This makes + Linux builds safer, and enables the removal of warning suppression pragmas for + Windows. + `#4298 `_ + +Bug fixes: + +* Fixed a bug where ``UnicodeDecodeError`` was not propagated from various + ``py::str`` ctors when decoding surrogate utf characters. + `#4294 `_ + +* Revert perfect forwarding for ``make_iterator``. This broke at least one + valid use case. May revisit later. + `#4234 `_ + +* Fix support for safe casts to ``void*`` (regression in 2.10.0). + `#4275 `_ + +* Fix ``char8_t`` support (regression in 2.9). + `#4278 `_ + +* Unicode surrogate character in Python exception message leads to process + termination in ``error_already_set::what()``. + `#4297 `_ + +* Fix MSVC 2019 v.1924 & C++14 mode error for ``overload_cast``. + `#4188 `_ + +* Make augmented assignment operators non-const for the object-api. Behavior + was previously broken for augmented assignment operators. + `#4065 `_ + +* Add proper error checking to C++ bindings for Python list append and insert. + `#4208 `_ + +* Work-around for Nvidia's CUDA nvcc compiler in versions 11.4.0 - 11.8.0. + `#4220 `_ + +* A workaround for PyPy was added in the ``py::error_already_set`` + implementation, related to PR `#1895 `_ + released with v2.10.0. + `#4079 `_ + +* Fixed compiler errors when C++23 ``std::forward_like`` is available. + `#4136 `_ + +* Properly raise exceptions in contains methods (like when an object in unhashable). + `#4209 `_ + +* Further improve another error in exception handling. + `#4232 `_ + +* ``get_local_internals()`` was made compatible with + ``finalize_interpreter()``, fixing potential freezes during interpreter + finalization. + `#4192 `_ + +Performance and style: + +* Reserve space in set and STL map casters if possible. This will prevent + unnecessary rehashing / resizing by knowing the number of keys ahead of time + for Python to C++ casting. This improvement will greatly speed up the casting + of large unordered maps and sets. + `#4194 `_ + +* GIL RAII scopes are non-copyable to avoid potential bugs. + `#4183 `_ + +* Explicitly default all relevant ctors for pytypes in the ``PYBIND11_OBJECT`` + macros and enforce the clang-tidy checks ``modernize-use-equals-default`` in + macros as well. + `#4017 `_ + +* Optimize iterator advancement in C++ bindings. + `#4237 `_ + +* Use the modern ``PyObject_GenericGetDict`` and ``PyObject_GenericSetDict`` + for handling dynamic attribute dictionaries. + `#4106 `_ + +* Document that users should use ``PYBIND11_NAMESPACE`` instead of using ``pybind11`` when + opening namespaces. Using namespace declarations and namespace qualification + remain the same as ``pybind11``. This is done to ensure consistent symbol + visibility. + `#4098 `_ + +* Mark ``detail::forward_like`` as constexpr. + `#4147 `_ + +* Optimize unpacking_collector when processing ``arg_v`` arguments. + `#4219 `_ + +* Optimize casting C++ object to ``None``. + `#4269 `_ + + +Build system improvements: + +* CMake: revert overwrite behavior, now opt-in with ``PYBIND11_PYTHONLIBS_OVERRWRITE OFF``. + `#4195 `_ + +* Include a pkg-config file when installing pybind11, such as in the Python + package. + `#4077 `_ + +* Avoid stripping debug symbols when ``CMAKE_BUILD_TYPE`` is set to ``DEBUG`` + instead of ``Debug``. + `#4078 `_ + +* Followup to `#3948 `_, fixing vcpkg again. + `#4123 `_ + +Version 2.10.0 (Jul 15, 2022) +----------------------------- + +Removed support for Python 2.7, Python 3.5, and MSVC 2015. Support for MSVC +2017 is limited due to availability of CI runners; we highly recommend MSVC +2019 or 2022 be used. Initial support added for Python 3.11. + +New features: + +* ``py::anyset`` & ``py::frozenset`` were added, with copying (cast) to + ``std::set`` (similar to ``set``). + `#3901 `_ + +* Support bytearray casting to string. + `#3707 `_ + +* ``type_caster`` was added. ``std::monostate`` is a tag type + that allows ``std::variant`` to act as an optional, or allows default + construction of a ``std::variant`` holding a non-default constructible type. + `#3818 `_ + +* ``pybind11::capsule::set_name`` added to mutate the name of the capsule instance. + `#3866 `_ + +* NumPy: dtype constructor from type number added, accessors corresponding to + Python API ``dtype.num``, ``dtype.byteorder``, ``dtype.flags`` and + ``dtype.alignment`` added. + `#3868 `_ + + +Changes: + +* Python 3.6 is now the minimum supported version. + `#3688 `_ + `#3719 `_ + +* The minimum version for MSVC is now 2017. + `#3722 `_ + +* Fix issues with CPython 3.11 betas and add to supported test matrix. + `#3923 `_ + +* ``error_already_set`` is now safer and more performant, especially for + exceptions with long tracebacks, by delaying computation. + `#1895 `_ + +* Improve exception handling in python ``str`` bindings. + `#3826 `_ + +* The bindings for capsules now have more consistent exception handling. + `#3825 `_ + +* ``PYBIND11_OBJECT_CVT`` and ``PYBIND11_OBJECT_CVT_DEFAULT`` macro can now be + used to define classes in namespaces other than pybind11. + `#3797 `_ + +* Error printing code now uses ``PYBIND11_DETAILED_ERROR_MESSAGES`` instead of + requiring ``NDEBUG``, allowing use with release builds if desired. + `#3913 `_ + +* Implicit conversion of the literal ``0`` to ``pybind11::handle`` is now disabled. + `#4008 `_ + + +Bug fixes: + +* Fix exception handling when ``pybind11::weakref()`` fails. + `#3739 `_ + +* ``module_::def_submodule`` was missing proper error handling. This is fixed now. + `#3973 `_ + +* The behavior or ``error_already_set`` was made safer and the highly opaque + "Unknown internal error occurred" message was replaced with a more helpful + message. + `#3982 `_ + +* ``error_already_set::what()`` now handles non-normalized exceptions correctly. + `#3971 `_ + +* Support older C++ compilers where filesystem is not yet part of the standard + library and is instead included in ``std::experimental::filesystem``. + `#3840 `_ + +* Fix ``-Wfree-nonheap-object`` warnings produced by GCC by avoiding returning + pointers to static objects with ``return_value_policy::take_ownership``. + `#3946 `_ + +* Fix cast from pytype rvalue to another pytype. + `#3949 `_ + +* Ensure proper behavior when garbage collecting classes with dynamic attributes in Python >=3.9. + `#4051 `_ + +* A couple long-standing ``PYBIND11_NAMESPACE`` + ``__attribute__((visibility("hidden")))`` inconsistencies are now fixed + (affects only unusual environments). + `#4043 `_ + +* ``pybind11::detail::get_internals()`` is now resilient to in-flight Python + exceptions. + `#3981 `_ + +* Arrays with a dimension of size 0 are now properly converted to dynamic Eigen + matrices (more common in NumPy 1.23). + `#4038 `_ + +* Avoid catching unrelated errors when importing NumPy. + `#3974 `_ + +Performance and style: + +* Added an accessor overload of ``(object &&key)`` to reference steal the + object when using python types as keys. This prevents unnecessary reference + count overhead for attr, dictionary, tuple, and sequence look ups. Added + additional regression tests. Fixed a performance bug the caused accessor + assignments to potentially perform unnecessary copies. + `#3970 `_ + +* Perfect forward all args of ``make_iterator``. + `#3980 `_ + +* Avoid potential bug in pycapsule destructor by adding an ``error_guard`` to + one of the dtors. + `#3958 `_ + +* Optimize dictionary access in ``strip_padding`` for numpy. + `#3994 `_ + +* ``stl_bind.h`` bindings now take slice args as a const-ref. + `#3852 `_ + +* Made slice constructor more consistent, and improve performance of some + casters by allowing reference stealing. + `#3845 `_ + +* Change numpy dtype from_args method to use const ref. + `#3878 `_ + +* Follow rule of three to ensure ``PyErr_Restore`` is called only once. + `#3872 `_ + +* Added missing perfect forwarding for ``make_iterator`` functions. + `#3860 `_ + +* Optimize c++ to python function casting by using the rvalue caster. + `#3966 `_ + +* Optimize Eigen sparse matrix casting by removing unnecessary temporary. + `#4064 `_ + +* Avoid potential implicit copy/assignment constructors causing double free in + ``strdup_gaurd``. + `#3905 `_ + +* Enable clang-tidy checks ``misc-definitions-in-headers``, + ``modernize-loop-convert``, and ``modernize-use-nullptr``. + `#3881 `_ + `#3988 `_ + + +Build system improvements: + +* CMake: Fix file extension on Windows with cp36 and cp37 using FindPython. + `#3919 `_ + +* CMake: Support multiple Python targets (such as on vcpkg). + `#3948 `_ + +* CMake: Fix issue with NVCC on Windows. + `#3947 `_ + +* CMake: Drop the bitness check on cross compiles (like targeting WebAssembly + via Emscripten). + `#3959 `_ + +* Add MSVC builds in debug mode to CI. + `#3784 `_ + +* MSVC 2022 C++20 coverage was added to GitHub Actions, including Eigen. + `#3732 `_, + `#3741 `_ + + +Backend and tidying up: + +* New theme for the documentation. + `#3109 `_ + +* Remove idioms in code comments. Use more inclusive language. + `#3809 `_ + +* ``#include `` was removed from the ``pybind11/stl.h`` header. Your + project may break if it has a transitive dependency on this include. The fix + is to "Include What You Use". + `#3928 `_ + +* Avoid ``setup.py `` usage in internal tests. + `#3734 `_ + + +Version 2.9.2 (Mar 29, 2022) +---------------------------- + +Changes: + +* Enum now has an ``__index__`` method on Python <3.8 too. + `#3700 `_ + +* Local internals are now cleared after finalizing the interpreter. + `#3744 `_ + +Bug fixes: + +* Better support for Python 3.11 alphas. + `#3694 `_ + +* ``PYBIND11_TYPE_CASTER`` now uses fully qualified symbols, so it can be used + outside of ``pybind11::detail``. + `#3758 `_ + +* Some fixes for PyPy 3.9. + `#3768 `_ + +* Fixed a potential memleak in PyPy in ``get_type_override``. + `#3774 `_ + +* Fix usage of ``VISIBILITY_INLINES_HIDDEN``. + `#3721 `_ + + +Build system improvements: + +* Uses ``sysconfig`` module to determine installation locations on Python >= + 3.10, instead of ``distutils`` which has been deprecated. + `#3764 `_ + +* Support Catch 2.13.5+ (supporting GLIBC 2.34+). + `#3679 `_ + +* Fix test failures with numpy 1.22 by ignoring whitespace when comparing + ``str()`` of dtypes. + `#3682 `_ + + +Backend and tidying up: + +* clang-tidy: added ``readability-qualified-auto``, + ``readability-braces-around-statements``, + ``cppcoreguidelines-prefer-member-initializer``, + ``clang-analyzer-optin.performance.Padding``, + ``cppcoreguidelines-pro-type-static-cast-downcast``, and + ``readability-inconsistent-declaration-parameter-name``. + `#3702 `_, + `#3699 `_, + `#3716 `_, + `#3709 `_ + +* clang-format was added to the pre-commit actions, and the entire code base + automatically reformatted (after several iterations preparing for this leap). + `#3713 `_ + + +Version 2.9.1 (Feb 2, 2022) +--------------------------- + +Changes: + +* If possible, attach Python exception with ``py::raise_from`` to ``TypeError`` + when casting from C++ to Python. This will give additional info if Python + exceptions occur in the caster. Adds a test case of trying to convert a set + from C++ to Python when the hash function is not defined in Python. + `#3605 `_ + +* Add a mapping of C++11 nested exceptions to their Python exception + equivalent using ``py::raise_from``. This attaches the nested exceptions in + Python using the ``__cause__`` field. + `#3608 `_ + +* Propagate Python exception traceback using ``raise_from`` if a pybind11 + function runs out of overloads. + `#3671 `_ + +* ``py::multiple_inheritance`` is now only needed when C++ bases are hidden + from pybind11. + `#3650 `_ and + `#3659 `_ + + +Bug fixes: + +* Remove a boolean cast in ``numpy.h`` that causes MSVC C4800 warnings when + compiling against Python 3.10 or newer. + `#3669 `_ + +* Render ``py::bool_`` and ``py::float_`` as ``bool`` and ``float`` + respectively. + `#3622 `_ + +Build system improvements: + +* Fix CMake extension suffix computation on Python 3.10+. + `#3663 `_ + +* Allow ``CMAKE_ARGS`` to override CMake args in pybind11's own ``setup.py``. + `#3577 `_ + +* Remove a few deprecated c-headers. + `#3610 `_ + +* More uniform handling of test targets. + `#3590 `_ + +* Add clang-tidy readability check to catch potentially swapped function args. + `#3611 `_ + + +Version 2.9.0 (Dec 28, 2021) +---------------------------- + +This is the last version to support Python 2.7 and 3.5. + +New Features: + +* Allow ``py::args`` to be followed by other arguments; the remaining arguments + are implicitly keyword-only, as if a ``py::kw_only{}`` annotation had been + used. + `#3402 `_ + +Changes: + +* Make str/bytes/memoryview more interoperable with ``std::string_view``. + `#3521 `_ + +* Replace ``_`` with ``const_name`` in internals, avoid defining ``pybind::_`` + if ``_`` defined as macro (common gettext usage) + `#3423 `_ + + +Bug fixes: + +* Fix a rare warning about extra copy in an Eigen constructor. + `#3486 `_ + +* Fix caching of the C++ overrides. + `#3465 `_ + +* Add missing ``std::forward`` calls to some ``cpp_function`` overloads. + `#3443 `_ + +* Support PyPy 7.3.7 and the PyPy3.8 beta. Test python-3.11 on PRs with the + ``python dev`` label. + `#3419 `_ + +* Replace usage of deprecated ``Eigen::MappedSparseMatrix`` with + ``Eigen::Map>`` for Eigen 3.3+. + `#3499 `_ + +* Tweaks to support Microsoft Visual Studio 2022. + `#3497 `_ + +Build system improvements: + +* Nicer CMake printout and IDE organisation for pybind11's own tests. + `#3479 `_ + +* CMake: report version type as part of the version string to avoid a spurious + space in the package status message. + `#3472 `_ + +* Flags starting with ``-g`` in ``$CFLAGS`` and ``$CPPFLAGS`` are no longer + overridden by ``.Pybind11Extension``. + `#3436 `_ + +* Ensure ThreadPool is closed in ``setup_helpers``. + `#3548 `_ + +* Avoid LTS on ``mips64`` and ``ppc64le`` (reported broken). + `#3557 `_ + + +v2.8.1 (Oct 27, 2021) +--------------------- + +Changes and additions: + +* The simple namespace creation shortcut added in 2.8.0 was deprecated due to + usage of CPython internal API, and will be removed soon. Use + ``py::module_::import("types").attr("SimpleNamespace")``. + `#3374 `_ + +* Add C++ Exception type to throw and catch ``AttributeError``. Useful for + defining custom ``__setattr__`` and ``__getattr__`` methods. + `#3387 `_ + +Fixes: + +* Fixed the potential for dangling references when using properties with + ``std::optional`` types. + `#3376 `_ + +* Modernize usage of ``PyCodeObject`` on Python 3.9+ (moving toward support for + Python 3.11a1) + `#3368 `_ + +* A long-standing bug in ``eigen.h`` was fixed (originally PR #3343). The bug + was unmasked by newly added ``static_assert``'s in the Eigen 3.4.0 release. + `#3352 `_ + +* Support multiple raw inclusion of CMake helper files (Conan.io does this for + multi-config generators). + `#3420 `_ + +* Fix harmless warning on upcoming CMake 3.22. + `#3368 `_ + +* Fix 2.8.0 regression with MSVC 2017 + C++17 mode + Python 3. + `#3407 `_ + +* Fix 2.8.0 regression that caused undefined behavior (typically + segfaults) in ``make_key_iterator``/``make_value_iterator`` if dereferencing + the iterator returned a temporary value instead of a reference. + `#3348 `_ + + +v2.8.0 (Oct 4, 2021) +-------------------- + +New features: + +* Added ``py::raise_from`` to enable chaining exceptions. + `#3215 `_ + +* Allow exception translators to be optionally registered local to a module + instead of applying globally across all pybind11 modules. Use + ``register_local_exception_translator(ExceptionTranslator&& translator)`` + instead of ``register_exception_translator(ExceptionTranslator&& + translator)`` to keep your exception remapping code local to the module. + `#2650 `_ + +* Add ``make_simple_namespace`` function for instantiating Python + ``SimpleNamespace`` objects. **Deprecated in 2.8.1.** + `#2840 `_ + +* ``pybind11::scoped_interpreter`` and ``initialize_interpreter`` have new + arguments to allow ``sys.argv`` initialization. + `#2341 `_ + +* Allow Python builtins to be used as callbacks in CPython. + `#1413 `_ + +* Added ``view`` to view arrays with a different datatype. + `#987 `_ + +* Implemented ``reshape`` on arrays. + `#984 `_ + +* Enable defining custom ``__new__`` methods on classes by fixing bug + preventing overriding methods if they have non-pybind11 siblings. + `#3265 `_ + +* Add ``make_value_iterator()``, and fix ``make_key_iterator()`` to return + references instead of copies. + `#3293 `_ + +* Improve the classes generated by ``bind_map``: `#3310 `_ + + * Change ``.items`` from an iterator to a dictionary view. + * Add ``.keys`` and ``.values`` (both dictionary views). + * Allow ``__contains__`` to take any object. + +* ``pybind11::custom_type_setup`` was added, for customizing the + ``PyHeapTypeObject`` corresponding to a class, which may be useful for + enabling garbage collection support, among other things. + `#3287 `_ + + +Changes: + +* Set ``__file__`` constant when running ``eval_file`` in an embedded interpreter. + `#3233 `_ + +* Python objects and (C++17) ``std::optional`` now accepted in ``py::slice`` + constructor. + `#1101 `_ + +* The pybind11 proxy types ``str``, ``bytes``, ``bytearray``, ``tuple``, + ``list`` now consistently support passing ``ssize_t`` values for sizes and + indexes. Previously, only ``size_t`` was accepted in several interfaces. + `#3219 `_ + +* Avoid evaluating ``PYBIND11_TLS_REPLACE_VALUE`` arguments more than once. + `#3290 `_ + +Fixes: + +* Bug fix: enum value's ``__int__`` returning non-int when underlying type is + bool or of char type. + `#1334 `_ + +* Fixes bug in setting error state in Capsule's pointer methods. + `#3261 `_ + +* A long-standing memory leak in ``py::cpp_function::initialize`` was fixed. + `#3229 `_ + +* Fixes thread safety for some ``pybind11::type_caster`` which require lifetime + extension, such as for ``std::string_view``. + `#3237 `_ + +* Restore compatibility with gcc 4.8.4 as distributed by ubuntu-trusty, linuxmint-17. + `#3270 `_ + + +Build system improvements: + +* Fix regression in CMake Python package config: improper use of absolute path. + `#3144 `_ + +* Cached Python version information could become stale when CMake was re-run + with a different Python version. The build system now detects this and + updates this information. + `#3299 `_ + +* Specified UTF8-encoding in setup.py calls of open(). + `#3137 `_ + +* Fix a harmless warning from CMake 3.21 with the classic Python discovery. + `#3220 `_ + +* Eigen repo and version can now be specified as cmake options. + `#3324 `_ + + +Backend and tidying up: + +* Reduced thread-local storage required for keeping alive temporary data for + type conversion to one key per ABI version, rather than one key per extension + module. This makes the total thread-local storage required by pybind11 2 + keys per ABI version. + `#3275 `_ + +* Optimize NumPy array construction with additional moves. + `#3183 `_ + +* Conversion to ``std::string`` and ``std::string_view`` now avoids making an + extra copy of the data on Python >= 3.3. + `#3257 `_ + +* Remove const modifier from certain C++ methods on Python collections + (``list``, ``set``, ``dict``) such as (``clear()``, ``append()``, + ``insert()``, etc...) and annotated them with ``py-non-const``. + +* Enable readability ``clang-tidy-const-return`` and remove useless consts. + `#3254 `_ + `#3194 `_ + +* The clang-tidy ``google-explicit-constructor`` option was enabled. + `#3250 `_ + +* Mark a pytype move constructor as noexcept (perf). + `#3236 `_ + +* Enable clang-tidy check to guard against inheritance slicing. + `#3210 `_ + +* Legacy warning suppression pragma were removed from eigen.h. On Unix + platforms, please use -isystem for Eigen include directories, to suppress + compiler warnings originating from Eigen headers. Note that CMake does this + by default. No adjustments are needed for Windows. + `#3198 `_ + +* Format pybind11 with isort consistent ordering of imports + `#3195 `_ + +* The warnings-suppression "pragma clamp" at the top/bottom of pybind11 was + removed, clearing the path to refactoring and IWYU cleanup. + `#3186 `_ + +* Enable most bugprone checks in clang-tidy and fix the found potential bugs + and poor coding styles. + `#3166 `_ + +* Add ``clang-tidy-readability`` rules to make boolean casts explicit improving + code readability. Also enabled other misc and readability clang-tidy checks. + `#3148 `_ + +* Move object in ``.pop()`` for list. + `#3116 `_ + + + + +v2.7.1 (Aug 3, 2021) +--------------------- + +Minor missing functionality added: + +* Allow Python builtins to be used as callbacks in CPython. + `#1413 `_ + +Bug fixes: + +* Fix regression in CMake Python package config: improper use of absolute path. + `#3144 `_ + +* Fix Mingw64 and add to the CI testing matrix. + `#3132 `_ + +* Specified UTF8-encoding in setup.py calls of open(). + `#3137 `_ + +* Add clang-tidy-readability rules to make boolean casts explicit improving + code readability. Also enabled other misc and readability clang-tidy checks. + `#3148 `_ + +* Move object in ``.pop()`` for list. + `#3116 `_ + +Backend and tidying up: + +* Removed and fixed warning suppressions. + `#3127 `_ + `#3129 `_ + `#3135 `_ + `#3141 `_ + `#3142 `_ + `#3150 `_ + `#3152 `_ + `#3160 `_ + `#3161 `_ + + +v2.7.0 (Jul 16, 2021) +--------------------- + +New features: + +* Enable ``py::implicitly_convertible`` for + ``py::class_``-wrapped types. + `#3059 `_ + +* Allow function pointer extraction from overloaded functions. + `#2944 `_ + +* NumPy: added ``.char_()`` to type which gives the NumPy public ``char`` + result, which also distinguishes types by bit length (unlike ``.kind()``). + `#2864 `_ + +* Add ``pybind11::bytearray`` to manipulate ``bytearray`` similar to ``bytes``. + `#2799 `_ + +* ``pybind11/stl/filesystem.h`` registers a type caster that, on C++17/Python + 3.6+, converts ``std::filesystem::path`` to ``pathlib.Path`` and any + ``os.PathLike`` to ``std::filesystem::path``. + `#2730 `_ + +* A ``PYBIND11_VERSION_HEX`` define was added, similar to ``PY_VERSION_HEX``. + `#3120 `_ + + + +Changes: + +* ``py::str`` changed to exclusively hold ``PyUnicodeObject``. Previously + ``py::str`` could also hold ``bytes``, which is probably surprising, was + never documented, and can mask bugs (e.g. accidental use of ``py::str`` + instead of ``py::bytes``). + `#2409 `_ + +* Add a safety guard to ensure that the Python GIL is held when C++ calls back + into Python via ``object_api<>::operator()`` (e.g. ``py::function`` + ``__call__``). (This feature is available for Python 3.6+ only.) + `#2919 `_ + +* Catch a missing ``self`` argument in calls to ``__init__()``. + `#2914 `_ + +* Use ``std::string_view`` if available to avoid a copy when passing an object + to a ``std::ostream``. + `#3042 `_ + +* An important warning about thread safety was added to the ``iostream.h`` + documentation; attempts to make ``py::scoped_ostream_redirect`` thread safe + have been removed, as it was only partially effective. + `#2995 `_ + + +Fixes: + +* Performance: avoid unnecessary strlen calls. + `#3058 `_ + +* Fix auto-generated documentation string when using ``const T`` in + ``pyarray_t``. + `#3020 `_ + +* Unify error messages thrown by ``simple_collector``/``unpacking_collector``. + `#3013 `_ + +* ``pybind11::builtin_exception`` is now explicitly exported, which means the + types included/defined in different modules are identical, and exceptions + raised in different modules can be caught correctly. The documentation was + updated to explain that custom exceptions that are used across module + boundaries need to be explicitly exported as well. + `#2999 `_ + +* Fixed exception when printing UTF-8 to a ``scoped_ostream_redirect``. + `#2982 `_ + +* Pickle support enhancement: ``setstate`` implementation will attempt to + ``setattr`` ``__dict__`` only if the unpickled ``dict`` object is not empty, + to not force use of ``py::dynamic_attr()`` unnecessarily. + `#2972 `_ + +* Allow negative timedelta values to roundtrip. + `#2870 `_ + +* Fix unchecked errors could potentially swallow signals/other exceptions. + `#2863 `_ + +* Add null pointer check with ``std::localtime``. + `#2846 `_ + +* Fix the ``weakref`` constructor from ``py::object`` to create a new + ``weakref`` on conversion. + `#2832 `_ + +* Avoid relying on exceptions in C++17 when getting a ``shared_ptr`` holder + from a ``shared_from_this`` class. + `#2819 `_ + +* Allow the codec's exception to be raised instead of :code:`RuntimeError` when + casting from :code:`py::str` to :code:`std::string`. + `#2903 `_ + + +Build system improvements: + +* In ``setup_helpers.py``, test for platforms that have some multiprocessing + features but lack semaphores, which ``ParallelCompile`` requires. + `#3043 `_ + +* Fix ``pybind11_INCLUDE_DIR`` in case ``CMAKE_INSTALL_INCLUDEDIR`` is + absolute. + `#3005 `_ + +* Fix bug not respecting ``WITH_SOABI`` or ``WITHOUT_SOABI`` to CMake. + `#2938 `_ + +* Fix the default ``Pybind11Extension`` compilation flags with a Mingw64 python. + `#2921 `_ + +* Clang on Windows: do not pass ``/MP`` (ignored flag). + `#2824 `_ + +* ``pybind11.setup_helpers.intree_extensions`` can be used to generate + ``Pybind11Extension`` instances from cpp files placed in the Python package + source tree. + `#2831 `_ + +Backend and tidying up: + +* Enable clang-tidy performance, readability, and modernization checks + throughout the codebase to enforce best coding practices. + `#3046 `_, + `#3049 `_, + `#3051 `_, + `#3052 `_, + `#3080 `_, and + `#3094 `_ + + +* Checks for common misspellings were added to the pre-commit hooks. + `#3076 `_ + +* Changed ``Werror`` to stricter ``Werror-all`` for Intel compiler and fixed + minor issues. + `#2948 `_ + +* Fixed compilation with GCC < 5 when the user defines ``_GLIBCXX_USE_CXX11_ABI``. + `#2956 `_ + +* Added nox support for easier local testing and linting of contributions. + `#3101 `_ and + `#3121 `_ + +* Avoid RTD style issue with docutils 0.17+. + `#3119 `_ + +* Support pipx run, such as ``pipx run pybind11 --include`` for a quick compile. + `#3117 `_ + + + +v2.6.2 (Jan 26, 2021) +--------------------- + +Minor missing functionality added: + +* enum: add missing Enum.value property. + `#2739 `_ + +* Allow thread termination to be avoided during shutdown for CPython 3.7+ via + ``.disarm`` for ``gil_scoped_acquire``/``gil_scoped_release``. + `#2657 `_ + +Fixed or improved behavior in a few special cases: + +* Fix bug where the constructor of ``object`` subclasses would not throw on + being passed a Python object of the wrong type. + `#2701 `_ + +* The ``type_caster`` for integers does not convert Python objects with + ``__int__`` anymore with ``noconvert`` or during the first round of trying + overloads. + `#2698 `_ + +* When casting to a C++ integer, ``__index__`` is always called and not + considered as conversion, consistent with Python 3.8+. + `#2801 `_ + +Build improvements: + +* Setup helpers: ``extra_compile_args`` and ``extra_link_args`` automatically set by + Pybind11Extension are now prepended, which allows them to be overridden + by user-set ``extra_compile_args`` and ``extra_link_args``. + `#2808 `_ + +* Setup helpers: Don't trigger unused parameter warning. + `#2735 `_ + +* CMake: Support running with ``--warn-uninitialized`` active. + `#2806 `_ + +* CMake: Avoid error if included from two submodule directories. + `#2804 `_ + +* CMake: Fix ``STATIC`` / ``SHARED`` being ignored in FindPython mode. + `#2796 `_ + +* CMake: Respect the setting for ``CMAKE_CXX_VISIBILITY_PRESET`` if defined. + `#2793 `_ + +* CMake: Fix issue with FindPython2/FindPython3 not working with ``pybind11::embed``. + `#2662 `_ + +* CMake: mixing local and installed pybind11's would prioritize the installed + one over the local one (regression in 2.6.0). + `#2716 `_ + + +Bug fixes: + +* Fixed segfault in multithreaded environments when using + ``scoped_ostream_redirect``. + `#2675 `_ + +* Leave docstring unset when all docstring-related options are disabled, rather + than set an empty string. + `#2745 `_ + +* The module key in builtins that pybind11 uses to store its internals changed + from std::string to a python str type (more natural on Python 2, no change on + Python 3). + `#2814 `_ + +* Fixed assertion error related to unhandled (later overwritten) exception in + CPython 3.8 and 3.9 debug builds. + `#2685 `_ + +* Fix ``py::gil_scoped_acquire`` assert with CPython 3.9 debug build. + `#2683 `_ + +* Fix issue with a test failing on pytest 6.2. + `#2741 `_ + +Warning fixes: + +* Fix warning modifying constructor parameter 'flag' that shadows a field of + 'set_flag' ``[-Wshadow-field-in-constructor-modified]``. + `#2780 `_ + +* Suppressed some deprecation warnings about old-style + ``__init__``/``__setstate__`` in the tests. + `#2759 `_ + +Valgrind work: + +* Fix invalid access when calling a pybind11 ``__init__`` on a non-pybind11 + class instance. + `#2755 `_ + +* Fixed various minor memory leaks in pybind11's test suite. + `#2758 `_ + +* Resolved memory leak in cpp_function initialization when exceptions occurred. + `#2756 `_ + +* Added a Valgrind build, checking for leaks and memory-related UB, to CI. + `#2746 `_ + +Compiler support: + +* Intel compiler was not activating C++14 support due to a broken define. + `#2679 `_ + +* Support ICC and NVIDIA HPC SDK in C++17 mode. + `#2729 `_ + +* Support Intel OneAPI compiler (ICC 20.2) and add to CI. + `#2573 `_ + + + +v2.6.1 (Nov 11, 2020) +--------------------- + +* ``py::exec``, ``py::eval``, and ``py::eval_file`` now add the builtins module + as ``"__builtins__"`` to their ``globals`` argument, better matching ``exec`` + and ``eval`` in pure Python. + `#2616 `_ + +* ``setup_helpers`` will no longer set a minimum macOS version higher than the + current version. + `#2622 `_ + +* Allow deleting static properties. + `#2629 `_ + +* Seal a leak in ``def_buffer``, cleaning up the ``capture`` object after the + ``class_`` object goes out of scope. + `#2634 `_ + +* ``pybind11_INCLUDE_DIRS`` was incorrect, potentially causing a regression if + it was expected to include ``PYTHON_INCLUDE_DIRS`` (please use targets + instead). + `#2636 `_ + +* Added parameter names to the ``py::enum_`` constructor and methods, avoiding + ``arg0`` in the generated docstrings. + `#2637 `_ + +* Added ``needs_recompile`` optional function to the ``ParallelCompiler`` + helper, to allow a recompile to be skipped based on a user-defined function. + `#2643 `_ + + +v2.6.0 (Oct 21, 2020) +--------------------- + +See :ref:`upgrade-guide-2.6` for help upgrading to the new version. + +New features: + +* Keyword-only arguments supported in Python 2 or 3 with ``py::kw_only()``. + `#2100 `_ + +* Positional-only arguments supported in Python 2 or 3 with ``py::pos_only()``. + `#2459 `_ + +* ``py::is_final()`` class modifier to block subclassing (CPython only). + `#2151 `_ + +* Added ``py::prepend()``, allowing a function to be placed at the beginning of + the overload chain. + `#1131 `_ + +* Access to the type object now provided with ``py::type::of()`` and + ``py::type::of(h)``. + `#2364 `_ + +* Perfect forwarding support for methods. + `#2048 `_ + +* Added ``py::error_already_set::discard_as_unraisable()``. + `#2372 `_ + +* ``py::hash`` is now public. + `#2217 `_ + +* ``py::class_`` is now supported. Note that writing to one data + member of the union and reading another (type punning) is UB in C++. Thus + pybind11-bound enums should never be used for such conversions. + `#2320 `_. + +* Classes now check local scope when registering members, allowing a subclass + to have a member with the same name as a parent (such as an enum). + `#2335 `_ + +Code correctness features: + +* Error now thrown when ``__init__`` is forgotten on subclasses. + `#2152 `_ + +* Throw error if conversion to a pybind11 type if the Python object isn't a + valid instance of that type, such as ``py::bytes(o)`` when ``py::object o`` + isn't a bytes instance. + `#2349 `_ + +* Throw if conversion to ``str`` fails. + `#2477 `_ + + +API changes: + +* ``py::module`` was renamed ``py::module_`` to avoid issues with C++20 when + used unqualified, but an alias ``py::module`` is provided for backward + compatibility. + `#2489 `_ + +* Public constructors for ``py::module_`` have been deprecated; please use + ``pybind11::module_::create_extension_module`` if you were using the public + constructor (fairly rare after ``PYBIND11_MODULE`` was introduced). + `#2552 `_ + +* ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function replaced by + correctly-named ``PYBIND11_OVERRIDE*`` and ``get_override``, fixing + inconsistencies in the presence of a closing ``;`` in these macros. + ``get_type_overload`` is deprecated. + `#2325 `_ + +Packaging / building improvements: + +* The Python package was reworked to be more powerful and useful. + `#2433 `_ + + * :ref:`build-setuptools` is easier thanks to a new + ``pybind11.setup_helpers`` module, which provides utilities to use + setuptools with pybind11. It can be used via PEP 518, ``setup_requires``, + or by directly importing or copying ``setup_helpers.py`` into your project. + + * CMake configuration files are now included in the Python package. Use + ``pybind11.get_cmake_dir()`` or ``python -m pybind11 --cmakedir`` to get + the directory with the CMake configuration files, or include the + site-packages location in your ``CMAKE_MODULE_PATH``. Or you can use the + new ``pybind11[global]`` extra when you install ``pybind11``, which + installs the CMake files and headers into your base environment in the + standard location. + + * ``pybind11-config`` is another way to write ``python -m pybind11`` if you + have your PATH set up. + + * Added external typing support to the helper module, code from + ``import pybind11`` can now be type checked. + `#2588 `_ + +* Minimum CMake required increased to 3.4. + `#2338 `_ and + `#2370 `_ + + * Full integration with CMake's C++ standard system and compile features + replaces ``PYBIND11_CPP_STANDARD``. + + * Generated config file is now portable to different Python/compiler/CMake + versions. + + * Virtual environments prioritized if ``PYTHON_EXECUTABLE`` is not set + (``venv``, ``virtualenv``, and ``conda``) (similar to the new FindPython + mode). + + * Other CMake features now natively supported, like + ``CMAKE_INTERPROCEDURAL_OPTIMIZATION``, ``set(CMAKE_CXX_VISIBILITY_PRESET + hidden)``. + + * ``CUDA`` as a language is now supported. + + * Helper functions ``pybind11_strip``, ``pybind11_extension``, + ``pybind11_find_import`` added, see :doc:`cmake/index`. + + * Optional :ref:`find-python-mode` and :ref:`nopython-mode` with CMake. + `#2370 `_ + +* Uninstall target added. + `#2265 `_ and + `#2346 `_ + +* ``pybind11_add_module()`` now accepts an optional ``OPT_SIZE`` flag that + switches the binding target to size-based optimization if the global build + type can not always be fixed to ``MinSizeRel`` (except in debug mode, where + optimizations remain disabled). ``MinSizeRel`` or this flag reduces binary + size quite substantially (~25% on some platforms). + `#2463 `_ + +Smaller or developer focused features and fixes: + +* Moved ``mkdoc.py`` to a new repo, `pybind11-mkdoc`_. There are no longer + submodules in the main repo. + +* ``py::memoryview`` segfault fix and update, with new + ``py::memoryview::from_memory`` in Python 3, and documentation. + `#2223 `_ + +* Fix for ``buffer_info`` on Python 2. + `#2503 `_ + +* If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to + ``None``. + `#2291 `_ + +* ``py::ellipsis`` now also works on Python 2. + `#2360 `_ + +* Pointer to ``std::tuple`` & ``std::pair`` supported in cast. + `#2334 `_ + +* Small fixes in NumPy support. ``py::array`` now uses ``py::ssize_t`` as first + argument type. + `#2293 `_ + +* Added missing signature for ``py::array``. + `#2363 `_ + +* ``unchecked_mutable_reference`` has access to operator ``()`` and ``[]`` when + const. + `#2514 `_ + +* ``py::vectorize`` is now supported on functions that return void. + `#1969 `_ + +* ``py::capsule`` supports ``get_pointer`` and ``set_pointer``. + `#1131 `_ + +* Fix crash when different instances share the same pointer of the same type. + `#2252 `_ + +* Fix for ``py::len`` not clearing Python's error state when it fails and throws. + `#2575 `_ + +* Bugfixes related to more extensive testing, new GitHub Actions CI. + `#2321 `_ + +* Bug in timezone issue in Eastern hemisphere midnight fixed. + `#2438 `_ + +* ``std::chrono::time_point`` now works when the resolution is not the same as + the system. + `#2481 `_ + +* Bug fixed where ``py::array_t`` could accept arrays that did not match the + requested ordering. + `#2484 `_ + +* Avoid a segfault on some compilers when types are removed in Python. + `#2564 `_ + +* ``py::arg::none()`` is now also respected when passing keyword arguments. + `#2611 `_ + +* PyPy fixes, PyPy 7.3.x now supported, including PyPy3. (Known issue with + PyPy2 and Windows `#2596 `_). + `#2146 `_ + +* CPython 3.9.0 workaround for undefined behavior (macOS segfault). + `#2576 `_ + +* CPython 3.9 warning fixes. + `#2253 `_ + +* Improved C++20 support, now tested in CI. + `#2489 `_ + `#2599 `_ + +* Improved but still incomplete debug Python interpreter support. + `#2025 `_ + +* NVCC (CUDA 11) now supported and tested in CI. + `#2461 `_ + +* NVIDIA PGI compilers now supported and tested in CI. + `#2475 `_ + +* At least Intel 18 now explicitly required when compiling with Intel. + `#2577 `_ + +* Extensive style checking in CI, with `pre-commit`_ support. Code + modernization, checked by clang-tidy. + +* Expanded docs, including new main page, new installing section, and CMake + helpers page, along with over a dozen new sections on existing pages. + +* In GitHub, new docs for contributing and new issue templates. + +.. _pre-commit: https://pre-commit.com + +.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc + +v2.5.0 (Mar 31, 2020) +----------------------------------------------------- + +* Use C++17 fold expressions in type casters, if available. This can + improve performance during overload resolution when functions have + multiple arguments. + `#2043 `_. + +* Changed include directory resolution in ``pybind11/__init__.py`` + and installation in ``setup.py``. This fixes a number of open issues + where pybind11 headers could not be found in certain environments. + `#1995 `_. + +* C++20 ``char8_t`` and ``u8string`` support. `#2026 + `_. + +* CMake: search for Python 3.9. `bb9c91 + `_. + +* Fixes for MSYS-based build environments. + `#2087 `_, + `#2053 `_. + +* STL bindings for ``std::vector<...>::clear``. `#2074 + `_. + +* Read-only flag for ``py::buffer``. `#1466 + `_. + +* Exception handling during module initialization. + `bf2b031 `_. + +* Support linking against a CPython debug build. + `#2025 `_. + +* Fixed issues involving the availability and use of aligned ``new`` and + ``delete``. `#1988 `_, + `759221 `_. + +* Fixed a resource leak upon interpreter shutdown. + `#2020 `_. + +* Fixed error handling in the boolean caster. + `#1976 `_. + +v2.4.3 (Oct 15, 2019) +----------------------------------------------------- + +* Adapt pybind11 to a C API convention change in Python 3.8. `#1950 + `_. + +v2.4.2 (Sep 21, 2019) +----------------------------------------------------- + +* Replaced usage of a C++14 only construct. `#1929 + `_. + +* Made an ifdef future-proof for Python >= 4. `f3109d + `_. + +v2.4.1 (Sep 20, 2019) +----------------------------------------------------- + +* Fixed a problem involving implicit conversion from enumerations to integers + on Python 3.8. `#1780 `_. + +v2.4.0 (Sep 19, 2019) +----------------------------------------------------- + +* Try harder to keep pybind11-internal data structures separate when there + are potential ABI incompatibilities. Fixes crashes that occurred when loading + multiple pybind11 extensions that were e.g. compiled by GCC (libstdc++) + and Clang (libc++). + `#1588 `_ and + `c9f5a `_. + +* Added support for ``__await__``, ``__aiter__``, and ``__anext__`` protocols. + `#1842 `_. + +* ``pybind11_add_module()``: don't strip symbols when compiling in + ``RelWithDebInfo`` mode. `#1980 + `_. + +* ``enum_``: Reproduce Python behavior when comparing against invalid values + (e.g. ``None``, strings, etc.). Add back support for ``__invert__()``. + `#1912 `_, + `#1907 `_. + +* List insertion operation for ``py::list``. + Added ``.empty()`` to all collection types. + Added ``py::set::contains()`` and ``py::dict::contains()``. + `#1887 `_, + `#1884 `_, + `#1888 `_. + +* ``py::details::overload_cast_impl`` is available in C++11 mode, can be used + like ``overload_cast`` with an additional set of parentheses. + `#1581 `_. + +* Fixed ``get_include()`` on Conda. + `#1877 `_. + +* ``stl_bind.h``: negative indexing support. + `#1882 `_. + +* Minor CMake fix to add MinGW compatibility. + `#1851 `_. + +* GIL-related fixes. + `#1836 `_, + `8b90b `_. + +* Other very minor/subtle fixes and improvements. + `#1329 `_, + `#1910 `_, + `#1863 `_, + `#1847 `_, + `#1890 `_, + `#1860 `_, + `#1848 `_, + `#1821 `_, + `#1837 `_, + `#1833 `_, + `#1748 `_, + `#1852 `_. + +v2.3.0 (June 11, 2019) +----------------------------------------------------- + +* Significantly reduced module binary size (10-20%) when compiled in C++11 mode + with GCC/Clang, or in any mode with MSVC. Function signatures are now always + precomputed at compile time (this was previously only available in C++14 mode + for non-MSVC compilers). + `#934 `_. + +* Add basic support for tag-based static polymorphism, where classes + provide a method to returns the desired type of an instance. + `#1326 `_. + +* Python type wrappers (``py::handle``, ``py::object``, etc.) + now support map Python's number protocol onto C++ arithmetic + operators such as ``operator+``, ``operator/=``, etc. + `#1511 `_. + +* A number of improvements related to enumerations: + + 1. The ``enum_`` implementation was rewritten from scratch to reduce + code bloat. Rather than instantiating a full implementation for each + enumeration, most code is now contained in a generic base class. + `#1511 `_. + + 2. The ``value()`` method of ``py::enum_`` now accepts an optional + docstring that will be shown in the documentation of the associated + enumeration. `#1160 `_. + + 3. check for already existing enum value and throw an error if present. + `#1453 `_. + +* Support for over-aligned type allocation via C++17's aligned ``new`` + statement. `#1582 `_. + +* Added ``py::ellipsis()`` method for slicing of multidimensional NumPy arrays + `#1502 `_. + +* Numerous Improvements to the ``mkdoc.py`` script for extracting documentation + from C++ header files. + `#1788 `_. + +* ``pybind11_add_module()``: allow including Python as a ``SYSTEM`` include path. + `#1416 `_. + +* ``pybind11/stl.h`` does not convert strings to ``vector`` anymore. + `#1258 `_. + +* Mark static methods as such to fix auto-generated Sphinx documentation. + `#1732 `_. + +* Re-throw forced unwind exceptions (e.g. during pthread termination). + `#1208 `_. + +* Added ``__contains__`` method to the bindings of maps (``std::map``, + ``std::unordered_map``). + `#1767 `_. + +* Improvements to ``gil_scoped_acquire``. + `#1211 `_. + +* Type caster support for ``std::deque``. + `#1609 `_. + +* Support for ``std::unique_ptr`` holders, whose deleters differ between a base and derived + class. `#1353 `_. + +* Construction of STL array/vector-like data structures from + iterators. Added an ``extend()`` operation. + `#1709 `_, + +* CMake build system improvements for projects that include non-C++ + files (e.g. plain C, CUDA) in ``pybind11_add_module`` et al. + `#1678 `_. + +* Fixed asynchronous invocation and deallocation of Python functions + wrapped in ``std::function``. + `#1595 `_. + +* Fixes regarding return value policy propagation in STL type casters. + `#1603 `_. + +* Fixed scoped enum comparisons. + `#1571 `_. + +* Fixed iostream redirection for code that releases the GIL. + `#1368 `_, + +* A number of CI-related fixes. + `#1757 `_, + `#1744 `_, + `#1670 `_. + +v2.2.4 (September 11, 2018) +----------------------------------------------------- + +* Use new Python 3.7 Thread Specific Storage (TSS) implementation if available. + `#1454 `_, + `#1517 `_. + +* Fixes for newer MSVC versions and C++17 mode. + `#1347 `_, + `#1462 `_. + +* Propagate return value policies to type-specific casters + when casting STL containers. + `#1455 `_. + +* Allow ostream-redirection of more than 1024 characters. + `#1479 `_. + +* Set ``Py_DEBUG`` define when compiling against a debug Python build. + `#1438 `_. + +* Untangle integer logic in number type caster to work for custom + types that may only be castable to a restricted set of builtin types. + `#1442 `_. + +* CMake build system: Remember Python version in cache file. + `#1434 `_. + +* Fix for custom smart pointers: use ``std::addressof`` to obtain holder + address instead of ``operator&``. + `#1435 `_. + +* Properly report exceptions thrown during module initialization. + `#1362 `_. + +* Fixed a segmentation fault when creating empty-shaped NumPy array. + `#1371 `_. + +* The version of Intel C++ compiler must be >= 2017, and this is now checked by + the header files. `#1363 `_. + +* A few minor typo fixes and improvements to the test suite, and + patches that silence compiler warnings. + +* Vectors now support construction from generators, as well as ``extend()`` from a + list or generator. + `#1496 `_. + + +v2.2.3 (April 29, 2018) +----------------------------------------------------- + +* The pybind11 header location detection was replaced by a new implementation + that no longer depends on ``pip`` internals (the recently released ``pip`` + 10 has restricted access to this API). + `#1190 `_. + +* Small adjustment to an implementation detail to work around a compiler segmentation fault in Clang 3.3/3.4. + `#1350 `_. + +* The minimal supported version of the Intel compiler was >= 17.0 since + pybind11 v2.1. This check is now explicit, and a compile-time error is raised + if the compiler meet the requirement. + `#1363 `_. + +* Fixed an endianness-related fault in the test suite. + `#1287 `_. + +v2.2.2 (February 7, 2018) +----------------------------------------------------- + +* Fixed a segfault when combining embedded interpreter + shutdown/reinitialization with external loaded pybind11 modules. + `#1092 `_. + +* Eigen support: fixed a bug where Nx1/1xN numpy inputs couldn't be passed as + arguments to Eigen vectors (which for Eigen are simply compile-time fixed + Nx1/1xN matrices). + `#1106 `_. + +* Clarified to license by moving the licensing of contributions from + ``LICENSE`` into ``CONTRIBUTING.md``: the licensing of contributions is not + actually part of the software license as distributed. This isn't meant to be + a substantial change in the licensing of the project, but addresses concerns + that the clause made the license non-standard. + `#1109 `_. + +* Fixed a regression introduced in 2.1 that broke binding functions with lvalue + character literal arguments. + `#1128 `_. + +* MSVC: fix for compilation failures under /permissive-, and added the flag to + the appveyor test suite. + `#1155 `_. + +* Fixed ``__qualname__`` generation, and in turn, fixes how class names + (especially nested class names) are shown in generated docstrings. + `#1171 `_. + +* Updated the FAQ with a suggested project citation reference. + `#1189 `_. + +* Added fixes for deprecation warnings when compiled under C++17 with + ``-Wdeprecated`` turned on, and add ``-Wdeprecated`` to the test suite + compilation flags. + `#1191 `_. + +* Fixed outdated PyPI URLs in ``setup.py``. + `#1213 `_. + +* Fixed a refcount leak for arguments that end up in a ``py::args`` argument + for functions with both fixed positional and ``py::args`` arguments. + `#1216 `_. + +* Fixed a potential segfault resulting from possible premature destruction of + ``py::args``/``py::kwargs`` arguments with overloaded functions. + `#1223 `_. + +* Fixed ``del map[item]`` for a ``stl_bind.h`` bound stl map. + `#1229 `_. + +* Fixed a regression from v2.1.x where the aggregate initialization could + unintentionally end up at a constructor taking a templated + ``std::initializer_list`` argument. + `#1249 `_. + +* Fixed an issue where calling a function with a keep_alive policy on the same + nurse/patient pair would cause the internal patient storage to needlessly + grow (unboundedly, if the nurse is long-lived). + `#1251 `_. + +* Various other minor fixes. + +v2.2.1 (September 14, 2017) +----------------------------------------------------- + +* Added ``py::module_::reload()`` member function for reloading a module. + `#1040 `_. + +* Fixed a reference leak in the number converter. + `#1078 `_. + +* Fixed compilation with Clang on host GCC < 5 (old libstdc++ which isn't fully + C++11 compliant). `#1062 `_. + +* Fixed a regression where the automatic ``std::vector`` caster would + fail to compile. The same fix also applies to any container which returns + element proxies instead of references. + `#1053 `_. + +* Fixed a regression where the ``py::keep_alive`` policy could not be applied + to constructors. `#1065 `_. + +* Fixed a nullptr dereference when loading a ``py::module_local`` type + that's only registered in an external module. + `#1058 `_. + +* Fixed implicit conversion of accessors to types derived from ``py::object``. + `#1076 `_. + +* The ``name`` in ``PYBIND11_MODULE(name, variable)`` can now be a macro. + `#1082 `_. + +* Relaxed overly strict ``py::pickle()`` check for matching get and set types. + `#1064 `_. + +* Conversion errors now try to be more informative when it's likely that + a missing header is the cause (e.g. forgetting ````). + `#1077 `_. + +v2.2.0 (August 31, 2017) +----------------------------------------------------- + +* Support for embedding the Python interpreter. See the + :doc:`documentation page ` for a + full overview of the new features. + `#774 `_, + `#889 `_, + `#892 `_, + `#920 `_. + + .. code-block:: cpp + + #include + namespace py = pybind11; + + int main() { + py::scoped_interpreter guard{}; // start the interpreter and keep it alive + + py::print("Hello, World!"); // use the Python API + } + +* Support for inheriting from multiple C++ bases in Python. + `#693 `_. + + .. code-block:: python + + from cpp_module import CppBase1, CppBase2 + + + class PyDerived(CppBase1, CppBase2): + def __init__(self): + CppBase1.__init__(self) # C++ bases must be initialized explicitly + CppBase2.__init__(self) + +* ``PYBIND11_MODULE`` is now the preferred way to create module entry points. + ``PYBIND11_PLUGIN`` is deprecated. See :ref:`macros` for details. + `#879 `_. + + .. code-block:: cpp + + // new + PYBIND11_MODULE(example, m) { + m.def("add", [](int a, int b) { return a + b; }); + } + + // old + PYBIND11_PLUGIN(example) { + py::module m("example"); + m.def("add", [](int a, int b) { return a + b; }); + return m.ptr(); + } + +* pybind11's headers and build system now more strictly enforce hidden symbol + visibility for extension modules. This should be seamless for most users, + but see the :doc:`upgrade` if you use a custom build system. + `#995 `_. + +* Support for ``py::module_local`` types which allow multiple modules to + export the same C++ types without conflicts. This is useful for opaque + types like ``std::vector``. ``py::bind_vector`` and ``py::bind_map`` + now default to ``py::module_local`` if their elements are builtins or + local types. See :ref:`module_local` for details. + `#949 `_, + `#981 `_, + `#995 `_, + `#997 `_. + +* Custom constructors can now be added very easily using lambdas or factory + functions which return a class instance by value, pointer or holder. This + supersedes the old placement-new ``__init__`` technique. + See :ref:`custom_constructors` for details. + `#805 `_, + `#1014 `_. + + .. code-block:: cpp + + struct Example { + Example(std::string); + }; + + py::class_(m, "Example") + .def(py::init()) // existing constructor + .def(py::init([](int n) { // custom constructor + return std::make_unique(std::to_string(n)); + })); + +* Similarly to custom constructors, pickling support functions are now bound + using the ``py::pickle()`` adaptor which improves type safety. See the + :doc:`upgrade` and :ref:`pickling` for details. + `#1038 `_. + +* Builtin support for converting C++17 standard library types and general + conversion improvements: + + 1. C++17 ``std::variant`` is supported right out of the box. C++11/14 + equivalents (e.g. ``boost::variant``) can also be added with a simple + user-defined specialization. See :ref:`cpp17_container_casters` for details. + `#811 `_, + `#845 `_, + `#989 `_. + + 2. Out-of-the-box support for C++17 ``std::string_view``. + `#906 `_. + + 3. Improved compatibility of the builtin ``optional`` converter. + `#874 `_. + + 4. The ``bool`` converter now accepts ``numpy.bool_`` and types which + define ``__bool__`` (Python 3.x) or ``__nonzero__`` (Python 2.7). + `#925 `_. + + 5. C++-to-Python casters are now more efficient and move elements out + of rvalue containers whenever possible. + `#851 `_, + `#936 `_, + `#938 `_. + + 6. Fixed ``bytes`` to ``std::string/char*`` conversion on Python 3. + `#817 `_. + + 7. Fixed lifetime of temporary C++ objects created in Python-to-C++ conversions. + `#924 `_. + +* Scope guard call policy for RAII types, e.g. ``py::call_guard()``, + ``py::call_guard()``. See :ref:`call_policies` for details. + `#740 `_. + +* Utility for redirecting C++ streams to Python (e.g. ``std::cout`` -> + ``sys.stdout``). Scope guard ``py::scoped_ostream_redirect`` in C++ and + a context manager in Python. See :ref:`ostream_redirect`. + `#1009 `_. + +* Improved handling of types and exceptions across module boundaries. + `#915 `_, + `#951 `_, + `#995 `_. + +* Fixed destruction order of ``py::keep_alive`` nurse/patient objects + in reference cycles. + `#856 `_. + +* NumPy and buffer protocol related improvements: + + 1. Support for negative strides in Python buffer objects/numpy arrays. This + required changing integers from unsigned to signed for the related C++ APIs. + Note: If you have compiler warnings enabled, you may notice some new conversion + warnings after upgrading. These can be resolved with ``static_cast``. + `#782 `_. + + 2. Support ``std::complex`` and arrays inside ``PYBIND11_NUMPY_DTYPE``. + `#831 `_, + `#832 `_. + + 3. Support for constructing ``py::buffer_info`` and ``py::arrays`` using + arbitrary containers or iterators instead of requiring a ``std::vector``. + `#788 `_, + `#822 `_, + `#860 `_. + + 4. Explicitly check numpy version and require >= 1.7.0. + `#819 `_. + +* Support for allowing/prohibiting ``None`` for specific arguments and improved + ``None`` overload resolution order. See :ref:`none_arguments` for details. + `#843 `_. + `#859 `_. + +* Added ``py::exec()`` as a shortcut for ``py::eval()`` + and support for C++11 raw string literals as input. See :ref:`eval`. + `#766 `_, + `#827 `_. + +* ``py::vectorize()`` ignores non-vectorizable arguments and supports + member functions. + `#762 `_. + +* Support for bound methods as callbacks (``pybind11/functional.h``). + `#815 `_. + +* Allow aliasing pybind11 methods: ``cls.attr("foo") = cls.attr("bar")``. + `#802 `_. + +* Don't allow mixed static/non-static overloads. + `#804 `_. + +* Fixed overriding static properties in derived classes. + `#784 `_. + +* Added support for write only properties. + `#1144 `_. + +* Improved deduction of member functions of a derived class when its bases + aren't registered with pybind11. + `#855 `_. + + .. code-block:: cpp + + struct Base { + int foo() { return 42; } + } + + struct Derived : Base {} + + // Now works, but previously required also binding `Base` + py::class_(m, "Derived") + .def("foo", &Derived::foo); // function is actually from `Base` + +* The implementation of ``py::init<>`` now uses C++11 brace initialization + syntax to construct instances, which permits binding implicit constructors of + aggregate types. `#1015 `_. + + .. code-block:: cpp + + struct Aggregate { + int a; + std::string b; + }; + + py::class_(m, "Aggregate") + .def(py::init()); + +* Fixed issues with multiple inheritance with offset base/derived pointers. + `#812 `_, + `#866 `_, + `#960 `_. + +* Fixed reference leak of type objects. + `#1030 `_. + +* Improved support for the ``/std:c++14`` and ``/std:c++latest`` modes + on MSVC 2017. + `#841 `_, + `#999 `_. + +* Fixed detection of private operator new on MSVC. + `#893 `_, + `#918 `_. + +* Intel C++ compiler compatibility fixes. + `#937 `_. + +* Fixed implicit conversion of ``py::enum_`` to integer types on Python 2.7. + `#821 `_. + +* Added ``py::hash`` to fetch the hash value of Python objects, and + ``.def(hash(py::self))`` to provide the C++ ``std::hash`` as the Python + ``__hash__`` method. + `#1034 `_. + +* Fixed ``__truediv__`` on Python 2 and ``__itruediv__`` on Python 3. + `#867 `_. + +* ``py::capsule`` objects now support the ``name`` attribute. This is useful + for interfacing with ``scipy.LowLevelCallable``. + `#902 `_. + +* Fixed ``py::make_iterator``'s ``__next__()`` for past-the-end calls. + `#897 `_. + +* Added ``error_already_set::matches()`` for checking Python exceptions. + `#772 `_. + +* Deprecated ``py::error_already_set::clear()``. It's no longer needed + following a simplification of the ``py::error_already_set`` class. + `#954 `_. + +* Deprecated ``py::handle::operator==()`` in favor of ``py::handle::is()`` + `#825 `_. + +* Deprecated ``py::object::borrowed``/``py::object::stolen``. + Use ``py::object::borrowed_t{}``/``py::object::stolen_t{}`` instead. + `#771 `_. + +* Changed internal data structure versioning to avoid conflicts between + modules compiled with different revisions of pybind11. + `#1012 `_. + +* Additional compile-time and run-time error checking and more informative messages. + `#786 `_, + `#794 `_, + `#803 `_. + +* Various minor improvements and fixes. + `#764 `_, + `#791 `_, + `#795 `_, + `#840 `_, + `#844 `_, + `#846 `_, + `#849 `_, + `#858 `_, + `#862 `_, + `#871 `_, + `#872 `_, + `#881 `_, + `#888 `_, + `#899 `_, + `#928 `_, + `#931 `_, + `#944 `_, + `#950 `_, + `#952 `_, + `#962 `_, + `#965 `_, + `#970 `_, + `#978 `_, + `#979 `_, + `#986 `_, + `#1020 `_, + `#1027 `_, + `#1037 `_. + +* Testing improvements. + `#798 `_, + `#882 `_, + `#898 `_, + `#900 `_, + `#921 `_, + `#923 `_, + `#963 `_. + +v2.1.1 (April 7, 2017) +----------------------------------------------------- + +* Fixed minimum version requirement for MSVC 2015u3 + `#773 `_. + +v2.1.0 (March 22, 2017) +----------------------------------------------------- + +* pybind11 now performs function overload resolution in two phases. The first + phase only considers exact type matches, while the second allows for implicit + conversions to take place. A special ``noconvert()`` syntax can be used to + completely disable implicit conversions for specific arguments. + `#643 `_, + `#634 `_, + `#650 `_. + +* Fixed a regression where static properties no longer worked with classes + using multiple inheritance. The ``py::metaclass`` attribute is no longer + necessary (and deprecated as of this release) when binding classes with + static properties. + `#679 `_, + +* Classes bound using ``pybind11`` can now use custom metaclasses. + `#679 `_, + +* ``py::args`` and ``py::kwargs`` can now be mixed with other positional + arguments when binding functions using pybind11. + `#611 `_. + +* Improved support for C++11 unicode string and character types; added + extensive documentation regarding pybind11's string conversion behavior. + `#624 `_, + `#636 `_, + `#715 `_. + +* pybind11 can now avoid expensive copies when converting Eigen arrays to NumPy + arrays (and vice versa). `#610 `_. + +* The "fast path" in ``py::vectorize`` now works for any full-size group of C or + F-contiguous arrays. The non-fast path is also faster since it no longer performs + copies of the input arguments (except when type conversions are necessary). + `#610 `_. + +* Added fast, unchecked access to NumPy arrays via a proxy object. + `#746 `_. + +* Transparent support for class-specific ``operator new`` and + ``operator delete`` implementations. + `#755 `_. + +* Slimmer and more efficient STL-compatible iterator interface for sequence types. + `#662 `_. + +* Improved custom holder type support. + `#607 `_. + +* ``nullptr`` to ``None`` conversion fixed in various builtin type casters. + `#732 `_. + +* ``enum_`` now exposes its members via a special ``__members__`` attribute. + `#666 `_. + +* ``std::vector`` bindings created using ``stl_bind.h`` can now optionally + implement the buffer protocol. `#488 `_. + +* Automated C++ reference documentation using doxygen and breathe. + `#598 `_. + +* Added minimum compiler version assertions. + `#727 `_. + +* Improved compatibility with C++1z. + `#677 `_. + +* Improved ``py::capsule`` API. Can be used to implement cleanup + callbacks that are involved at module destruction time. + `#752 `_. + +* Various minor improvements and fixes. + `#595 `_, + `#588 `_, + `#589 `_, + `#603 `_, + `#619 `_, + `#648 `_, + `#695 `_, + `#720 `_, + `#723 `_, + `#729 `_, + `#724 `_, + `#742 `_, + `#753 `_. + +v2.0.1 (Jan 4, 2017) +----------------------------------------------------- + +* Fix pointer to reference error in type_caster on MSVC + `#583 `_. + +* Fixed a segmentation in the test suite due to a typo + `cd7eac `_. + +v2.0.0 (Jan 1, 2017) +----------------------------------------------------- + +* Fixed a reference counting regression affecting types with custom metaclasses + (introduced in v2.0.0-rc1). + `#571 `_. + +* Quenched a CMake policy warning. + `#570 `_. + +v2.0.0-rc1 (Dec 23, 2016) +----------------------------------------------------- + +The pybind11 developers are excited to issue a release candidate of pybind11 +with a subsequent v2.0.0 release planned in early January next year. + +An incredible amount of effort by went into pybind11 over the last ~5 months, +leading to a release that is jam-packed with exciting new features and numerous +usability improvements. The following list links PRs or individual commits +whenever applicable. + +Happy Christmas! + +* Support for binding C++ class hierarchies that make use of multiple + inheritance. `#410 `_. + +* PyPy support: pybind11 now supports nightly builds of PyPy and will + interoperate with the future 5.7 release. No code changes are necessary, + everything "just" works as usual. Note that we only target the Python 2.7 + branch for now; support for 3.x will be added once its ``cpyext`` extension + support catches up. A few minor features remain unsupported for the time + being (notably dynamic attributes in custom types). + `#527 `_. + +* Significant work on the documentation -- in particular, the monolithic + ``advanced.rst`` file was restructured into a easier to read hierarchical + organization. `#448 `_. + +* Many NumPy-related improvements: + + 1. Object-oriented API to access and modify NumPy ``ndarray`` instances, + replicating much of the corresponding NumPy C API functionality. + `#402 `_. + + 2. NumPy array ``dtype`` array descriptors are now first-class citizens and + are exposed via a new class ``py::dtype``. + + 3. Structured dtypes can be registered using the ``PYBIND11_NUMPY_DTYPE()`` + macro. Special ``array`` constructors accepting dtype objects were also + added. + + One potential caveat involving this change: format descriptor strings + should now be accessed via ``format_descriptor::format()`` (however, for + compatibility purposes, the old syntax ``format_descriptor::value`` will + still work for non-structured data types). `#308 + `_. + + 4. Further improvements to support structured dtypes throughout the system. + `#472 `_, + `#474 `_, + `#459 `_, + `#453 `_, + `#452 `_, and + `#505 `_. + + 5. Fast access operators. `#497 `_. + + 6. Constructors for arrays whose storage is owned by another object. + `#440 `_. + + 7. Added constructors for ``array`` and ``array_t`` explicitly accepting shape + and strides; if strides are not provided, they are deduced assuming + C-contiguity. Also added simplified constructors for 1-dimensional case. + + 8. Added buffer/NumPy support for ``char[N]`` and ``std::array`` types. + + 9. Added ``memoryview`` wrapper type which is constructible from ``buffer_info``. + +* Eigen: many additional conversions and support for non-contiguous + arrays/slices. + `#427 `_, + `#315 `_, + `#316 `_, + `#312 `_, and + `#267 `_ + +* Incompatible changes in ``class_<...>::class_()``: + + 1. Declarations of types that provide access via the buffer protocol must + now include the ``py::buffer_protocol()`` annotation as an argument to + the ``class_`` constructor. + + 2. Declarations of types that require a custom metaclass (i.e. all classes + which include static properties via commands such as + ``def_readwrite_static()``) must now include the ``py::metaclass()`` + annotation as an argument to the ``class_`` constructor. + + These two changes were necessary to make type definitions in pybind11 + future-proof, and to support PyPy via its cpyext mechanism. `#527 + `_. + + + 3. This version of pybind11 uses a redesigned mechanism for instantiating + trampoline classes that are used to override virtual methods from within + Python. This led to the following user-visible syntax change: instead of + + .. code-block:: cpp + + py::class_("MyClass") + .alias() + .... + + write + + .. code-block:: cpp + + py::class_("MyClass") + .... + + Importantly, both the original and the trampoline class are now + specified as an arguments (in arbitrary order) to the ``py::class_`` + template, and the ``alias<..>()`` call is gone. The new scheme has zero + overhead in cases when Python doesn't override any functions of the + underlying C++ class. `rev. 86d825 + `_. + +* Added ``eval`` and ``eval_file`` functions for evaluating expressions and + statements from a string or file. `rev. 0d3fc3 + `_. + +* pybind11 can now create types with a modifiable dictionary. + `#437 `_ and + `#444 `_. + +* Support for translation of arbitrary C++ exceptions to Python counterparts. + `#296 `_ and + `#273 `_. + +* Report full backtraces through mixed C++/Python code, better reporting for + import errors, fixed GIL management in exception processing. + `#537 `_, + `#494 `_, + `rev. e72d95 `_, and + `rev. 099d6e `_. + +* Support for bit-level operations, comparisons, and serialization of C++ + enumerations. `#503 `_, + `#508 `_, + `#380 `_, + `#309 `_. + `#311 `_. + +* The ``class_`` constructor now accepts its template arguments in any order. + `#385 `_. + +* Attribute and item accessors now have a more complete interface which makes + it possible to chain attributes as in + ``obj.attr("a")[key].attr("b").attr("method")(1, 2, 3)``. `#425 + `_. + +* Major redesign of the default and conversion constructors in ``pytypes.h``. + `#464 `_. + +* Added built-in support for ``std::shared_ptr`` holder type. It is no longer + necessary to to include a declaration of the form + ``PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr)`` (though continuing to + do so won't cause an error). + `#454 `_. + +* New ``py::overload_cast`` casting operator to select among multiple possible + overloads of a function. An example: + + .. code-block:: cpp + + py::class_(m, "Pet") + .def("set", py::overload_cast(&Pet::set), "Set the pet's age") + .def("set", py::overload_cast(&Pet::set), "Set the pet's name"); + + This feature only works on C++14-capable compilers. + `#541 `_. + +* C++ types are automatically cast to Python types, e.g. when assigning + them as an attribute. For instance, the following is now legal: + + .. code-block:: cpp + + py::module m = /* ... */ + m.attr("constant") = 123; + + (Previously, a ``py::cast`` call was necessary to avoid a compilation error.) + `#551 `_. + +* Redesigned ``pytest``-based test suite. `#321 `_. + +* Instance tracking to detect reference leaks in test suite. `#324 `_ + +* pybind11 can now distinguish between multiple different instances that are + located at the same memory address, but which have different types. + `#329 `_. + +* Improved logic in ``move`` return value policy. + `#510 `_, + `#297 `_. + +* Generalized unpacking API to permit calling Python functions from C++ using + notation such as ``foo(a1, a2, *args, "ka"_a=1, "kb"_a=2, **kwargs)``. `#372 `_. + +* ``py::print()`` function whose behavior matches that of the native Python + ``print()`` function. `#372 `_. + +* Added ``py::dict`` keyword constructor:``auto d = dict("number"_a=42, + "name"_a="World");``. `#372 `_. + +* Added ``py::str::format()`` method and ``_s`` literal: ``py::str s = "1 + 2 + = {}"_s.format(3);``. `#372 `_. + +* Added ``py::repr()`` function which is equivalent to Python's builtin + ``repr()``. `#333 `_. + +* Improved construction and destruction logic for holder types. It is now + possible to reference instances with smart pointer holder types without + constructing the holder if desired. The ``PYBIND11_DECLARE_HOLDER_TYPE`` + macro now accepts an optional second parameter to indicate whether the holder + type uses intrusive reference counting. + `#533 `_ and + `#561 `_. + +* Mapping a stateless C++ function to Python and back is now "for free" (i.e. + no extra indirections or argument conversion overheads). `rev. 954b79 + `_. + +* Bindings for ``std::valarray``. + `#545 `_. + +* Improved support for C++17 capable compilers. + `#562 `_. + +* Bindings for ``std::optional``. + `#475 `_, + `#476 `_, + `#479 `_, + `#499 `_, and + `#501 `_. + +* ``stl_bind.h``: general improvements and support for ``std::map`` and + ``std::unordered_map``. + `#490 `_, + `#282 `_, + `#235 `_. + +* The ``std::tuple``, ``std::pair``, ``std::list``, and ``std::vector`` type + casters now accept any Python sequence type as input. `rev. 107285 + `_. + +* Improved CMake Python detection on multi-architecture Linux. + `#532 `_. + +* Infrastructure to selectively disable or enable parts of the automatically + generated docstrings. `#486 `_. + +* ``reference`` and ``reference_internal`` are now the default return value + properties for static and non-static properties, respectively. `#473 + `_. (the previous defaults + were ``automatic``). `#473 `_. + +* Support for ``std::unique_ptr`` with non-default deleters or no deleter at + all (``py::nodelete``). `#384 `_. + +* Deprecated ``handle::call()`` method. The new syntax to call Python + functions is simply ``handle()``. It can also be invoked explicitly via + ``handle::operator()``, where ``X`` is an optional return value policy. + +* Print more informative error messages when ``make_tuple()`` or ``cast()`` + fail. `#262 `_. + +* Creation of holder types for classes deriving from + ``std::enable_shared_from_this<>`` now also works for ``const`` values. + `#260 `_. + +* ``make_iterator()`` improvements for better compatibility with various + types (now uses prefix increment operator); it now also accepts iterators + with different begin/end types as long as they are equality comparable. + `#247 `_. + +* ``arg()`` now accepts a wider range of argument types for default values. + `#244 `_. + +* Support ``keep_alive`` where the nurse object may be ``None``. `#341 + `_. + +* Added constructors for ``str`` and ``bytes`` from zero-terminated char + pointers, and from char pointers and length. Added constructors for ``str`` + from ``bytes`` and for ``bytes`` from ``str``, which will perform UTF-8 + decoding/encoding as required. + +* Many other improvements of library internals without user-visible changes + + +1.8.1 (July 12, 2016) +---------------------- +* Fixed a rare but potentially very severe issue when the garbage collector ran + during pybind11 type creation. + +1.8.0 (June 14, 2016) +---------------------- +* Redesigned CMake build system which exports a convenient + ``pybind11_add_module`` function to parent projects. +* ``std::vector<>`` type bindings analogous to Boost.Python's ``indexing_suite`` +* Transparent conversion of sparse and dense Eigen matrices and vectors (``eigen.h``) +* Added an ``ExtraFlags`` template argument to the NumPy ``array_t<>`` wrapper + to disable an enforced cast that may lose precision, e.g. to create overloads + for different precisions and complex vs real-valued matrices. +* Prevent implicit conversion of floating point values to integral types in + function arguments +* Fixed incorrect default return value policy for functions returning a shared + pointer +* Don't allow registering a type via ``class_`` twice +* Don't allow casting a ``None`` value into a C++ lvalue reference +* Fixed a crash in ``enum_::operator==`` that was triggered by the ``help()`` command +* Improved detection of whether or not custom C++ types can be copy/move-constructed +* Extended ``str`` type to also work with ``bytes`` instances +* Added a ``"name"_a`` user defined string literal that is equivalent to ``py::arg("name")``. +* When specifying function arguments via ``py::arg``, the test that verifies + the number of arguments now runs at compile time. +* Added ``[[noreturn]]`` attribute to ``pybind11_fail()`` to quench some + compiler warnings +* List function arguments in exception text when the dispatch code cannot find + a matching overload +* Added ``PYBIND11_OVERLOAD_NAME`` and ``PYBIND11_OVERLOAD_PURE_NAME`` macros which + can be used to override virtual methods whose name differs in C++ and Python + (e.g. ``__call__`` and ``operator()``) +* Various minor ``iterator`` and ``make_iterator()`` improvements +* Transparently support ``__bool__`` on Python 2.x and Python 3.x +* Fixed issue with destructor of unpickled object not being called +* Minor CMake build system improvements on Windows +* New ``pybind11::args`` and ``pybind11::kwargs`` types to create functions which + take an arbitrary number of arguments and keyword arguments +* New syntax to call a Python function from C++ using ``*args`` and ``*kwargs`` +* The functions ``def_property_*`` now correctly process docstring arguments (these + formerly caused a segmentation fault) +* Many ``mkdoc.py`` improvements (enumerations, template arguments, ``DOC()`` + macro accepts more arguments) +* Cygwin support +* Documentation improvements (pickling support, ``keep_alive``, macro usage) + +1.7 (April 30, 2016) +---------------------- +* Added a new ``move`` return value policy that triggers C++11 move semantics. + The automatic return value policy falls back to this case whenever a rvalue + reference is encountered +* Significantly more general GIL state routines that are used instead of + Python's troublesome ``PyGILState_Ensure`` and ``PyGILState_Release`` API +* Redesign of opaque types that drastically simplifies their usage +* Extended ability to pass values of type ``[const] void *`` +* ``keep_alive`` fix: don't fail when there is no patient +* ``functional.h``: acquire the GIL before calling a Python function +* Added Python RAII type wrappers ``none`` and ``iterable`` +* Added ``*args`` and ``*kwargs`` pass-through parameters to + ``pybind11.get_include()`` function +* Iterator improvements and fixes +* Documentation on return value policies and opaque types improved + +1.6 (April 30, 2016) +---------------------- +* Skipped due to upload to PyPI gone wrong and inability to recover + (https://github.com/pypa/packaging-problems/issues/74) + +1.5 (April 21, 2016) +---------------------- +* For polymorphic types, use RTTI to try to return the closest type registered with pybind11 +* Pickling support for serializing and unserializing C++ instances to a byte stream in Python +* Added a convenience routine ``make_iterator()`` which turns a range indicated + by a pair of C++ iterators into a iterable Python object +* Added ``len()`` and a variadic ``make_tuple()`` function +* Addressed a rare issue that could confuse the current virtual function + dispatcher and another that could lead to crashes in multi-threaded + applications +* Added a ``get_include()`` function to the Python module that returns the path + of the directory containing the installed pybind11 header files +* Documentation improvements: import issues, symbol visibility, pickling, limitations +* Added casting support for ``std::reference_wrapper<>`` + +1.4 (April 7, 2016) +-------------------------- +* Transparent type conversion for ``std::wstring`` and ``wchar_t`` +* Allow passing ``nullptr``-valued strings +* Transparent passing of ``void *`` pointers using capsules +* Transparent support for returning values wrapped in ``std::unique_ptr<>`` +* Improved docstring generation for compatibility with Sphinx +* Nicer debug error message when default parameter construction fails +* Support for "opaque" types that bypass the transparent conversion layer for STL containers +* Redesigned type casting interface to avoid ambiguities that could occasionally cause compiler errors +* Redesigned property implementation; fixes crashes due to an unfortunate default return value policy +* Anaconda package generation support + +1.3 (March 8, 2016) +-------------------------- + +* Added support for the Intel C++ compiler (v15+) +* Added support for the STL unordered set/map data structures +* Added support for the STL linked list data structure +* NumPy-style broadcasting support in ``pybind11::vectorize`` +* pybind11 now displays more verbose error messages when ``arg::operator=()`` fails +* pybind11 internal data structures now live in a version-dependent namespace to avoid ABI issues +* Many, many bugfixes involving corner cases and advanced usage + +1.2 (February 7, 2016) +-------------------------- + +* Optional: efficient generation of function signatures at compile time using C++14 +* Switched to a simpler and more general way of dealing with function default + arguments. Unused keyword arguments in function calls are now detected and + cause errors as expected +* New ``keep_alive`` call policy analogous to Boost.Python's ``with_custodian_and_ward`` +* New ``pybind11::base<>`` attribute to indicate a subclass relationship +* Improved interface for RAII type wrappers in ``pytypes.h`` +* Use RAII type wrappers consistently within pybind11 itself. This + fixes various potential refcount leaks when exceptions occur +* Added new ``bytes`` RAII type wrapper (maps to ``string`` in Python 2.7) +* Made handle and related RAII classes const correct, using them more + consistently everywhere now +* Got rid of the ugly ``__pybind11__`` attributes on the Python side---they are + now stored in a C++ hash table that is not visible in Python +* Fixed refcount leaks involving NumPy arrays and bound functions +* Vastly improved handling of shared/smart pointers +* Removed an unnecessary copy operation in ``pybind11::vectorize`` +* Fixed naming clashes when both pybind11 and NumPy headers are included +* Added conversions for additional exception types +* Documentation improvements (using multiple extension modules, smart pointers, + other minor clarifications) +* unified infrastructure for parsing variadic arguments in ``class_`` and cpp_function +* Fixed license text (was: ZLIB, should have been: 3-clause BSD) +* Python 3.2 compatibility +* Fixed remaining issues when accessing types in another plugin module +* Added enum comparison and casting methods +* Improved SFINAE-based detection of whether types are copy-constructible +* Eliminated many warnings about unused variables and the use of ``offsetof()`` +* Support for ``std::array<>`` conversions + +1.1 (December 7, 2015) +-------------------------- + +* Documentation improvements (GIL, wrapping functions, casting, fixed many typos) +* Generalized conversion of integer types +* Improved support for casting function objects +* Improved support for ``std::shared_ptr<>`` conversions +* Initial support for ``std::set<>`` conversions +* Fixed type resolution issue for types defined in a separate plugin module +* CMake build system improvements +* Factored out generic functionality to non-templated code (smaller code size) +* Added a code size / compile time benchmark vs Boost.Python +* Added an appveyor CI script + +1.0 (October 15, 2015) +------------------------ +* Initial release diff --git a/third_party/CityFlow/extern/pybind11/docs/classes.rst b/third_party/CityFlow/extern/pybind11/docs/classes.rst index 4f2167dac1d73418f5f8222ed266d70b38d7e281..7943dd19d3e2f1c0d278533c53e245729b41eec2 100644 --- a/third_party/CityFlow/extern/pybind11/docs/classes.rst +++ b/third_party/CityFlow/extern/pybind11/docs/classes.rst @@ -1,555 +1,555 @@ -.. _classes: - -Object-oriented code -#################### - -Creating bindings for a custom type -=================================== - -Let's now look at a more complex example where we'll create bindings for a -custom C++ data structure named ``Pet``. Its definition is given below: - -.. code-block:: cpp - - struct Pet { - Pet(const std::string &name) : name(name) { } - void setName(const std::string &name_) { name = name_; } - const std::string &getName() const { return name; } - - std::string name; - }; - -The binding code for ``Pet`` looks as follows: - -.. code-block:: cpp - - #include - - namespace py = pybind11; - - PYBIND11_MODULE(example, m) { - py::class_(m, "Pet") - .def(py::init()) - .def("setName", &Pet::setName) - .def("getName", &Pet::getName); - } - -:class:`class_` creates bindings for a C++ *class* or *struct*-style data -structure. :func:`init` is a convenience function that takes the types of a -constructor's parameters as template arguments and wraps the corresponding -constructor (see the :ref:`custom_constructors` section for details). An -interactive Python session demonstrating this example is shown below: - -.. code-block:: pycon - - % python - >>> import example - >>> p = example.Pet("Molly") - >>> print(p) - - >>> p.getName() - 'Molly' - >>> p.setName("Charly") - >>> p.getName() - 'Charly' - -.. seealso:: - - Static member functions can be bound in the same way using - :func:`class_::def_static`. - -.. note:: - - Binding C++ types in unnamed namespaces (also known as anonymous namespaces) - works reliably on many platforms, but not all. The `XFAIL_CONDITION` in - tests/test_unnamed_namespace_a.py encodes the currently known conditions. - For background see `#4319 `_. - If portability is a concern, it is therefore not recommended to bind C++ - types in unnamed namespaces. It will be safest to manually pick unique - namespace names. - -Keyword and default arguments -============================= -It is possible to specify keyword and default arguments using the syntax -discussed in the previous chapter. Refer to the sections :ref:`keyword_args` -and :ref:`default_args` for details. - -Binding lambda functions -======================== - -Note how ``print(p)`` produced a rather useless summary of our data structure in the example above: - -.. code-block:: pycon - - >>> print(p) - - -To address this, we could bind a utility function that returns a human-readable -summary to the special method slot named ``__repr__``. Unfortunately, there is no -suitable functionality in the ``Pet`` data structure, and it would be nice if -we did not have to change it. This can easily be accomplished by binding a -Lambda function instead: - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init()) - .def("setName", &Pet::setName) - .def("getName", &Pet::getName) - .def("__repr__", - [](const Pet &a) { - return ""; - } - ); - -Both stateless [#f1]_ and stateful lambda closures are supported by pybind11. -With the above change, the same Python code now produces the following output: - -.. code-block:: pycon - - >>> print(p) - - -.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object. - -.. _properties: - -Instance and static fields -========================== - -We can also directly expose the ``name`` field using the -:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly` -method also exists for ``const`` fields. - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init()) - .def_readwrite("name", &Pet::name) - // ... remainder ... - -This makes it possible to write - -.. code-block:: pycon - - >>> p = example.Pet("Molly") - >>> p.name - 'Molly' - >>> p.name = "Charly" - >>> p.name - 'Charly' - -Now suppose that ``Pet::name`` was a private internal variable -that can only be accessed via setters and getters. - -.. code-block:: cpp - - class Pet { - public: - Pet(const std::string &name) : name(name) { } - void setName(const std::string &name_) { name = name_; } - const std::string &getName() const { return name; } - private: - std::string name; - }; - -In this case, the method :func:`class_::def_property` -(:func:`class_::def_property_readonly` for read-only data) can be used to -provide a field-like interface within Python that will transparently call -the setter and getter functions: - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init()) - .def_property("name", &Pet::getName, &Pet::setName) - // ... remainder ... - -Write only properties can be defined by passing ``nullptr`` as the -input for the read function. - -.. seealso:: - - Similar functions :func:`class_::def_readwrite_static`, - :func:`class_::def_readonly_static` :func:`class_::def_property_static`, - and :func:`class_::def_property_readonly_static` are provided for binding - static variables and properties. Please also see the section on - :ref:`static_properties` in the advanced part of the documentation. - -Dynamic attributes -================== - -Native Python classes can pick up new attributes dynamically: - -.. code-block:: pycon - - >>> class Pet: - ... name = "Molly" - ... - >>> p = Pet() - >>> p.name = "Charly" # overwrite existing - >>> p.age = 2 # dynamically add a new attribute - -By default, classes exported from C++ do not support this and the only writable -attributes are the ones explicitly defined using :func:`class_::def_readwrite` -or :func:`class_::def_property`. - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init<>()) - .def_readwrite("name", &Pet::name); - -Trying to set any other attribute results in an error: - -.. code-block:: pycon - - >>> p = example.Pet() - >>> p.name = "Charly" # OK, attribute defined in C++ - >>> p.age = 2 # fail - AttributeError: 'Pet' object has no attribute 'age' - -To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag -must be added to the :class:`py::class_` constructor: - -.. code-block:: cpp - - py::class_(m, "Pet", py::dynamic_attr()) - .def(py::init<>()) - .def_readwrite("name", &Pet::name); - -Now everything works as expected: - -.. code-block:: pycon - - >>> p = example.Pet() - >>> p.name = "Charly" # OK, overwrite value in C++ - >>> p.age = 2 # OK, dynamically add a new attribute - >>> p.__dict__ # just like a native Python class - {'age': 2} - -Note that there is a small runtime cost for a class with dynamic attributes. -Not only because of the addition of a ``__dict__``, but also because of more -expensive garbage collection tracking which must be activated to resolve -possible circular references. Native Python classes incur this same cost by -default, so this is not anything to worry about. By default, pybind11 classes -are more efficient than native Python classes. Enabling dynamic attributes -just brings them on par. - -.. _inheritance: - -Inheritance and automatic downcasting -===================================== - -Suppose now that the example consists of two data structures with an -inheritance relationship: - -.. code-block:: cpp - - struct Pet { - Pet(const std::string &name) : name(name) { } - std::string name; - }; - - struct Dog : Pet { - Dog(const std::string &name) : Pet(name) { } - std::string bark() const { return "woof!"; } - }; - -There are two different ways of indicating a hierarchical relationship to -pybind11: the first specifies the C++ base class as an extra template -parameter of the :class:`class_`: - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init()) - .def_readwrite("name", &Pet::name); - - // Method 1: template parameter: - py::class_(m, "Dog") - .def(py::init()) - .def("bark", &Dog::bark); - -Alternatively, we can also assign a name to the previously bound ``Pet`` -:class:`class_` object and reference it when binding the ``Dog`` class: - -.. code-block:: cpp - - py::class_ pet(m, "Pet"); - pet.def(py::init()) - .def_readwrite("name", &Pet::name); - - // Method 2: pass parent class_ object: - py::class_(m, "Dog", pet /* <- specify Python parent type */) - .def(py::init()) - .def("bark", &Dog::bark); - -Functionality-wise, both approaches are equivalent. Afterwards, instances will -expose fields and methods of both types: - -.. code-block:: pycon - - >>> p = example.Dog("Molly") - >>> p.name - 'Molly' - >>> p.bark() - 'woof!' - -The C++ classes defined above are regular non-polymorphic types with an -inheritance relationship. This is reflected in Python: - -.. code-block:: cpp - - // Return a base pointer to a derived instance - m.def("pet_store", []() { return std::unique_ptr(new Dog("Molly")); }); - -.. code-block:: pycon - - >>> p = example.pet_store() - >>> type(p) # `Dog` instance behind `Pet` pointer - Pet # no pointer downcasting for regular non-polymorphic types - >>> p.bark() - AttributeError: 'Pet' object has no attribute 'bark' - -The function returned a ``Dog`` instance, but because it's a non-polymorphic -type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only -considered polymorphic if it has at least one virtual function and pybind11 -will automatically recognize this: - -.. code-block:: cpp - - struct PolymorphicPet { - virtual ~PolymorphicPet() = default; - }; - - struct PolymorphicDog : PolymorphicPet { - std::string bark() const { return "woof!"; } - }; - - // Same binding code - py::class_(m, "PolymorphicPet"); - py::class_(m, "PolymorphicDog") - .def(py::init<>()) - .def("bark", &PolymorphicDog::bark); - - // Again, return a base pointer to a derived instance - m.def("pet_store2", []() { return std::unique_ptr(new PolymorphicDog); }); - -.. code-block:: pycon - - >>> p = example.pet_store2() - >>> type(p) - PolymorphicDog # automatically downcast - >>> p.bark() - 'woof!' - -Given a pointer to a polymorphic base, pybind11 performs automatic downcasting -to the actual derived type. Note that this goes beyond the usual situation in -C++: we don't just get access to the virtual functions of the base, we get the -concrete derived type including functions and attributes that the base type may -not even be aware of. - -.. seealso:: - - For more information about polymorphic behavior see :ref:`overriding_virtuals`. - - -Overloaded methods -================== - -Sometimes there are several overloaded C++ methods with the same name taking -different kinds of input arguments: - -.. code-block:: cpp - - struct Pet { - Pet(const std::string &name, int age) : name(name), age(age) { } - - void set(int age_) { age = age_; } - void set(const std::string &name_) { name = name_; } - - std::string name; - int age; - }; - -Attempting to bind ``Pet::set`` will cause an error since the compiler does not -know which method the user intended to select. We can disambiguate by casting -them to function pointers. Binding multiple functions to the same Python name -automatically creates a chain of function overloads that will be tried in -sequence. - -.. code-block:: cpp - - py::class_(m, "Pet") - .def(py::init()) - .def("set", static_cast(&Pet::set), "Set the pet's age") - .def("set", static_cast(&Pet::set), "Set the pet's name"); - -The overload signatures are also visible in the method's docstring: - -.. code-block:: pycon - - >>> help(example.Pet) - - class Pet(__builtin__.object) - | Methods defined here: - | - | __init__(...) - | Signature : (Pet, str, int) -> NoneType - | - | set(...) - | 1. Signature : (Pet, int) -> NoneType - | - | Set the pet's age - | - | 2. Signature : (Pet, str) -> NoneType - | - | Set the pet's name - -If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative -syntax to cast the overloaded function: - -.. code-block:: cpp - - py::class_(m, "Pet") - .def("set", py::overload_cast(&Pet::set), "Set the pet's age") - .def("set", py::overload_cast(&Pet::set), "Set the pet's name"); - -Here, ``py::overload_cast`` only requires the parameter types to be specified. -The return type and class are deduced. This avoids the additional noise of -``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based -on constness, the ``py::const_`` tag should be used: - -.. code-block:: cpp - - struct Widget { - int foo(int x, float y); - int foo(int x, float y) const; - }; - - py::class_(m, "Widget") - .def("foo_mutable", py::overload_cast(&Widget::foo)) - .def("foo_const", py::overload_cast(&Widget::foo, py::const_)); - -If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only, -you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses: - -.. code-block:: cpp - - template - using overload_cast_ = pybind11::detail::overload_cast_impl; - - py::class_(m, "Pet") - .def("set", overload_cast_()(&Pet::set), "Set the pet's age") - .def("set", overload_cast_()(&Pet::set), "Set the pet's name"); - -.. [#cpp14] A compiler which supports the ``-std=c++14`` flag. - -.. note:: - - To define multiple overloaded constructors, simply declare one after the - other using the ``.def(py::init<...>())`` syntax. The existing machinery - for specifying keyword and default arguments also works. - -Enumerations and internal types -=============================== - -Let's now suppose that the example class contains internal types like enumerations, e.g.: - -.. code-block:: cpp - - struct Pet { - enum Kind { - Dog = 0, - Cat - }; - - struct Attributes { - float age = 0; - }; - - Pet(const std::string &name, Kind type) : name(name), type(type) { } - - std::string name; - Kind type; - Attributes attr; - }; - -The binding code for this example looks as follows: - -.. code-block:: cpp - - py::class_ pet(m, "Pet"); - - pet.def(py::init()) - .def_readwrite("name", &Pet::name) - .def_readwrite("type", &Pet::type) - .def_readwrite("attr", &Pet::attr); - - py::enum_(pet, "Kind") - .value("Dog", Pet::Kind::Dog) - .value("Cat", Pet::Kind::Cat) - .export_values(); - - py::class_(pet, "Attributes") - .def(py::init<>()) - .def_readwrite("age", &Pet::Attributes::age); - - -To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the -``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_` -constructor. The :func:`enum_::export_values` function exports the enum entries -into the parent scope, which should be skipped for newer C++11-style strongly -typed enums. - -.. code-block:: pycon - - >>> p = Pet("Lucy", Pet.Cat) - >>> p.type - Kind.Cat - >>> int(p.type) - 1L - -The entries defined by the enumeration type are exposed in the ``__members__`` property: - -.. code-block:: pycon - - >>> Pet.Kind.__members__ - {'Dog': Kind.Dog, 'Cat': Kind.Cat} - -The ``name`` property returns the name of the enum value as a unicode string. - -.. note:: - - It is also possible to use ``str(enum)``, however these accomplish different - goals. The following shows how these two approaches differ. - - .. code-block:: pycon - - >>> p = Pet("Lucy", Pet.Cat) - >>> pet_type = p.type - >>> pet_type - Pet.Cat - >>> str(pet_type) - 'Pet.Cat' - >>> pet_type.name - 'Cat' - -.. note:: - - When the special tag ``py::arithmetic()`` is specified to the ``enum_`` - constructor, pybind11 creates an enumeration that also supports rudimentary - arithmetic and bit-level operations like comparisons, and, or, xor, negation, - etc. - - .. code-block:: cpp - - py::enum_(pet, "Kind", py::arithmetic()) - ... - - By default, these are omitted to conserve space. - -.. warning:: - - Contrary to Python customs, enum values from the wrappers should not be compared using ``is``, but with ``==`` (see `#1177 `_ for background). +.. _classes: + +Object-oriented code +#################### + +Creating bindings for a custom type +=================================== + +Let's now look at a more complex example where we'll create bindings for a +custom C++ data structure named ``Pet``. Its definition is given below: + +.. code-block:: cpp + + struct Pet { + Pet(const std::string &name) : name(name) { } + void setName(const std::string &name_) { name = name_; } + const std::string &getName() const { return name; } + + std::string name; + }; + +The binding code for ``Pet`` looks as follows: + +.. code-block:: cpp + + #include + + namespace py = pybind11; + + PYBIND11_MODULE(example, m) { + py::class_(m, "Pet") + .def(py::init()) + .def("setName", &Pet::setName) + .def("getName", &Pet::getName); + } + +:class:`class_` creates bindings for a C++ *class* or *struct*-style data +structure. :func:`init` is a convenience function that takes the types of a +constructor's parameters as template arguments and wraps the corresponding +constructor (see the :ref:`custom_constructors` section for details). An +interactive Python session demonstrating this example is shown below: + +.. code-block:: pycon + + % python + >>> import example + >>> p = example.Pet("Molly") + >>> print(p) + + >>> p.getName() + 'Molly' + >>> p.setName("Charly") + >>> p.getName() + 'Charly' + +.. seealso:: + + Static member functions can be bound in the same way using + :func:`class_::def_static`. + +.. note:: + + Binding C++ types in unnamed namespaces (also known as anonymous namespaces) + works reliably on many platforms, but not all. The `XFAIL_CONDITION` in + tests/test_unnamed_namespace_a.py encodes the currently known conditions. + For background see `#4319 `_. + If portability is a concern, it is therefore not recommended to bind C++ + types in unnamed namespaces. It will be safest to manually pick unique + namespace names. + +Keyword and default arguments +============================= +It is possible to specify keyword and default arguments using the syntax +discussed in the previous chapter. Refer to the sections :ref:`keyword_args` +and :ref:`default_args` for details. + +Binding lambda functions +======================== + +Note how ``print(p)`` produced a rather useless summary of our data structure in the example above: + +.. code-block:: pycon + + >>> print(p) + + +To address this, we could bind a utility function that returns a human-readable +summary to the special method slot named ``__repr__``. Unfortunately, there is no +suitable functionality in the ``Pet`` data structure, and it would be nice if +we did not have to change it. This can easily be accomplished by binding a +Lambda function instead: + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init()) + .def("setName", &Pet::setName) + .def("getName", &Pet::getName) + .def("__repr__", + [](const Pet &a) { + return ""; + } + ); + +Both stateless [#f1]_ and stateful lambda closures are supported by pybind11. +With the above change, the same Python code now produces the following output: + +.. code-block:: pycon + + >>> print(p) + + +.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object. + +.. _properties: + +Instance and static fields +========================== + +We can also directly expose the ``name`` field using the +:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly` +method also exists for ``const`` fields. + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init()) + .def_readwrite("name", &Pet::name) + // ... remainder ... + +This makes it possible to write + +.. code-block:: pycon + + >>> p = example.Pet("Molly") + >>> p.name + 'Molly' + >>> p.name = "Charly" + >>> p.name + 'Charly' + +Now suppose that ``Pet::name`` was a private internal variable +that can only be accessed via setters and getters. + +.. code-block:: cpp + + class Pet { + public: + Pet(const std::string &name) : name(name) { } + void setName(const std::string &name_) { name = name_; } + const std::string &getName() const { return name; } + private: + std::string name; + }; + +In this case, the method :func:`class_::def_property` +(:func:`class_::def_property_readonly` for read-only data) can be used to +provide a field-like interface within Python that will transparently call +the setter and getter functions: + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init()) + .def_property("name", &Pet::getName, &Pet::setName) + // ... remainder ... + +Write only properties can be defined by passing ``nullptr`` as the +input for the read function. + +.. seealso:: + + Similar functions :func:`class_::def_readwrite_static`, + :func:`class_::def_readonly_static` :func:`class_::def_property_static`, + and :func:`class_::def_property_readonly_static` are provided for binding + static variables and properties. Please also see the section on + :ref:`static_properties` in the advanced part of the documentation. + +Dynamic attributes +================== + +Native Python classes can pick up new attributes dynamically: + +.. code-block:: pycon + + >>> class Pet: + ... name = "Molly" + ... + >>> p = Pet() + >>> p.name = "Charly" # overwrite existing + >>> p.age = 2 # dynamically add a new attribute + +By default, classes exported from C++ do not support this and the only writable +attributes are the ones explicitly defined using :func:`class_::def_readwrite` +or :func:`class_::def_property`. + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init<>()) + .def_readwrite("name", &Pet::name); + +Trying to set any other attribute results in an error: + +.. code-block:: pycon + + >>> p = example.Pet() + >>> p.name = "Charly" # OK, attribute defined in C++ + >>> p.age = 2 # fail + AttributeError: 'Pet' object has no attribute 'age' + +To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag +must be added to the :class:`py::class_` constructor: + +.. code-block:: cpp + + py::class_(m, "Pet", py::dynamic_attr()) + .def(py::init<>()) + .def_readwrite("name", &Pet::name); + +Now everything works as expected: + +.. code-block:: pycon + + >>> p = example.Pet() + >>> p.name = "Charly" # OK, overwrite value in C++ + >>> p.age = 2 # OK, dynamically add a new attribute + >>> p.__dict__ # just like a native Python class + {'age': 2} + +Note that there is a small runtime cost for a class with dynamic attributes. +Not only because of the addition of a ``__dict__``, but also because of more +expensive garbage collection tracking which must be activated to resolve +possible circular references. Native Python classes incur this same cost by +default, so this is not anything to worry about. By default, pybind11 classes +are more efficient than native Python classes. Enabling dynamic attributes +just brings them on par. + +.. _inheritance: + +Inheritance and automatic downcasting +===================================== + +Suppose now that the example consists of two data structures with an +inheritance relationship: + +.. code-block:: cpp + + struct Pet { + Pet(const std::string &name) : name(name) { } + std::string name; + }; + + struct Dog : Pet { + Dog(const std::string &name) : Pet(name) { } + std::string bark() const { return "woof!"; } + }; + +There are two different ways of indicating a hierarchical relationship to +pybind11: the first specifies the C++ base class as an extra template +parameter of the :class:`class_`: + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init()) + .def_readwrite("name", &Pet::name); + + // Method 1: template parameter: + py::class_(m, "Dog") + .def(py::init()) + .def("bark", &Dog::bark); + +Alternatively, we can also assign a name to the previously bound ``Pet`` +:class:`class_` object and reference it when binding the ``Dog`` class: + +.. code-block:: cpp + + py::class_ pet(m, "Pet"); + pet.def(py::init()) + .def_readwrite("name", &Pet::name); + + // Method 2: pass parent class_ object: + py::class_(m, "Dog", pet /* <- specify Python parent type */) + .def(py::init()) + .def("bark", &Dog::bark); + +Functionality-wise, both approaches are equivalent. Afterwards, instances will +expose fields and methods of both types: + +.. code-block:: pycon + + >>> p = example.Dog("Molly") + >>> p.name + 'Molly' + >>> p.bark() + 'woof!' + +The C++ classes defined above are regular non-polymorphic types with an +inheritance relationship. This is reflected in Python: + +.. code-block:: cpp + + // Return a base pointer to a derived instance + m.def("pet_store", []() { return std::unique_ptr(new Dog("Molly")); }); + +.. code-block:: pycon + + >>> p = example.pet_store() + >>> type(p) # `Dog` instance behind `Pet` pointer + Pet # no pointer downcasting for regular non-polymorphic types + >>> p.bark() + AttributeError: 'Pet' object has no attribute 'bark' + +The function returned a ``Dog`` instance, but because it's a non-polymorphic +type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only +considered polymorphic if it has at least one virtual function and pybind11 +will automatically recognize this: + +.. code-block:: cpp + + struct PolymorphicPet { + virtual ~PolymorphicPet() = default; + }; + + struct PolymorphicDog : PolymorphicPet { + std::string bark() const { return "woof!"; } + }; + + // Same binding code + py::class_(m, "PolymorphicPet"); + py::class_(m, "PolymorphicDog") + .def(py::init<>()) + .def("bark", &PolymorphicDog::bark); + + // Again, return a base pointer to a derived instance + m.def("pet_store2", []() { return std::unique_ptr(new PolymorphicDog); }); + +.. code-block:: pycon + + >>> p = example.pet_store2() + >>> type(p) + PolymorphicDog # automatically downcast + >>> p.bark() + 'woof!' + +Given a pointer to a polymorphic base, pybind11 performs automatic downcasting +to the actual derived type. Note that this goes beyond the usual situation in +C++: we don't just get access to the virtual functions of the base, we get the +concrete derived type including functions and attributes that the base type may +not even be aware of. + +.. seealso:: + + For more information about polymorphic behavior see :ref:`overriding_virtuals`. + + +Overloaded methods +================== + +Sometimes there are several overloaded C++ methods with the same name taking +different kinds of input arguments: + +.. code-block:: cpp + + struct Pet { + Pet(const std::string &name, int age) : name(name), age(age) { } + + void set(int age_) { age = age_; } + void set(const std::string &name_) { name = name_; } + + std::string name; + int age; + }; + +Attempting to bind ``Pet::set`` will cause an error since the compiler does not +know which method the user intended to select. We can disambiguate by casting +them to function pointers. Binding multiple functions to the same Python name +automatically creates a chain of function overloads that will be tried in +sequence. + +.. code-block:: cpp + + py::class_(m, "Pet") + .def(py::init()) + .def("set", static_cast(&Pet::set), "Set the pet's age") + .def("set", static_cast(&Pet::set), "Set the pet's name"); + +The overload signatures are also visible in the method's docstring: + +.. code-block:: pycon + + >>> help(example.Pet) + + class Pet(__builtin__.object) + | Methods defined here: + | + | __init__(...) + | Signature : (Pet, str, int) -> NoneType + | + | set(...) + | 1. Signature : (Pet, int) -> NoneType + | + | Set the pet's age + | + | 2. Signature : (Pet, str) -> NoneType + | + | Set the pet's name + +If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative +syntax to cast the overloaded function: + +.. code-block:: cpp + + py::class_(m, "Pet") + .def("set", py::overload_cast(&Pet::set), "Set the pet's age") + .def("set", py::overload_cast(&Pet::set), "Set the pet's name"); + +Here, ``py::overload_cast`` only requires the parameter types to be specified. +The return type and class are deduced. This avoids the additional noise of +``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based +on constness, the ``py::const_`` tag should be used: + +.. code-block:: cpp + + struct Widget { + int foo(int x, float y); + int foo(int x, float y) const; + }; + + py::class_(m, "Widget") + .def("foo_mutable", py::overload_cast(&Widget::foo)) + .def("foo_const", py::overload_cast(&Widget::foo, py::const_)); + +If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only, +you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses: + +.. code-block:: cpp + + template + using overload_cast_ = pybind11::detail::overload_cast_impl; + + py::class_(m, "Pet") + .def("set", overload_cast_()(&Pet::set), "Set the pet's age") + .def("set", overload_cast_()(&Pet::set), "Set the pet's name"); + +.. [#cpp14] A compiler which supports the ``-std=c++14`` flag. + +.. note:: + + To define multiple overloaded constructors, simply declare one after the + other using the ``.def(py::init<...>())`` syntax. The existing machinery + for specifying keyword and default arguments also works. + +Enumerations and internal types +=============================== + +Let's now suppose that the example class contains internal types like enumerations, e.g.: + +.. code-block:: cpp + + struct Pet { + enum Kind { + Dog = 0, + Cat + }; + + struct Attributes { + float age = 0; + }; + + Pet(const std::string &name, Kind type) : name(name), type(type) { } + + std::string name; + Kind type; + Attributes attr; + }; + +The binding code for this example looks as follows: + +.. code-block:: cpp + + py::class_ pet(m, "Pet"); + + pet.def(py::init()) + .def_readwrite("name", &Pet::name) + .def_readwrite("type", &Pet::type) + .def_readwrite("attr", &Pet::attr); + + py::enum_(pet, "Kind") + .value("Dog", Pet::Kind::Dog) + .value("Cat", Pet::Kind::Cat) + .export_values(); + + py::class_(pet, "Attributes") + .def(py::init<>()) + .def_readwrite("age", &Pet::Attributes::age); + + +To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the +``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_` +constructor. The :func:`enum_::export_values` function exports the enum entries +into the parent scope, which should be skipped for newer C++11-style strongly +typed enums. + +.. code-block:: pycon + + >>> p = Pet("Lucy", Pet.Cat) + >>> p.type + Kind.Cat + >>> int(p.type) + 1L + +The entries defined by the enumeration type are exposed in the ``__members__`` property: + +.. code-block:: pycon + + >>> Pet.Kind.__members__ + {'Dog': Kind.Dog, 'Cat': Kind.Cat} + +The ``name`` property returns the name of the enum value as a unicode string. + +.. note:: + + It is also possible to use ``str(enum)``, however these accomplish different + goals. The following shows how these two approaches differ. + + .. code-block:: pycon + + >>> p = Pet("Lucy", Pet.Cat) + >>> pet_type = p.type + >>> pet_type + Pet.Cat + >>> str(pet_type) + 'Pet.Cat' + >>> pet_type.name + 'Cat' + +.. note:: + + When the special tag ``py::arithmetic()`` is specified to the ``enum_`` + constructor, pybind11 creates an enumeration that also supports rudimentary + arithmetic and bit-level operations like comparisons, and, or, xor, negation, + etc. + + .. code-block:: cpp + + py::enum_(pet, "Kind", py::arithmetic()) + ... + + By default, these are omitted to conserve space. + +.. warning:: + + Contrary to Python customs, enum values from the wrappers should not be compared using ``is``, but with ``==`` (see `#1177 `_ for background). diff --git a/third_party/CityFlow/extern/pybind11/docs/compiling.rst b/third_party/CityFlow/extern/pybind11/docs/compiling.rst index 3be84ba7d85c7efbe29ec412dc361c72fdc909e1..d63c23a446552315e746a96b655e448acebe2c10 100644 --- a/third_party/CityFlow/extern/pybind11/docs/compiling.rst +++ b/third_party/CityFlow/extern/pybind11/docs/compiling.rst @@ -1,649 +1,649 @@ -.. _compiling: - -Build systems -############# - -.. _build-setuptools: - -Building with setuptools -======================== - -For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay -has kindly provided an example project which shows how to set up everything, -including automatic generation of documentation using Sphinx. Please refer to -the [python_example]_ repository. - -.. [python_example] https://github.com/pybind/python_example - -A helper file is provided with pybind11 that can simplify usage with setuptools. - -To use pybind11 inside your ``setup.py``, you have to have some system to -ensure that ``pybind11`` is installed when you build your package. There are -four possible ways to do this, and pybind11 supports all four: You can ask all -users to install pybind11 beforehand (bad), you can use -:ref:`setup_helpers-pep518` (good, but very new and requires Pip 10), -:ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that -PEP 518 is available, but it still works everywhere), or you can -:ref:`setup_helpers-copy-manually` (always works but you have to manually sync -your copy to get updates). - -An example of a ``setup.py`` using pybind11's helpers: - -.. code-block:: python - - from glob import glob - from setuptools import setup - from pybind11.setup_helpers import Pybind11Extension - - ext_modules = [ - Pybind11Extension( - "python_example", - sorted(glob("src/*.cpp")), # Sort source files for reproducibility - ), - ] - - setup(..., ext_modules=ext_modules) - -If you want to do an automatic search for the highest supported C++ standard, -that is supported via a ``build_ext`` command override; it will only affect -``Pybind11Extensions``: - -.. code-block:: python - - from glob import glob - from setuptools import setup - from pybind11.setup_helpers import Pybind11Extension, build_ext - - ext_modules = [ - Pybind11Extension( - "python_example", - sorted(glob("src/*.cpp")), - ), - ] - - setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules) - -If you have single-file extension modules that are directly stored in the -Python source tree (``foo.cpp`` in the same directory as where a ``foo.py`` -would be located), you can also generate ``Pybind11Extensions`` using -``setup_helpers.intree_extensions``: ``intree_extensions(["path/to/foo.cpp", -...])`` returns a list of ``Pybind11Extensions`` which can be passed to -``ext_modules``, possibly after further customizing their attributes -(``libraries``, ``include_dirs``, etc.). By doing so, a ``foo.*.so`` extension -module will be generated and made available upon installation. - -``intree_extension`` will automatically detect if you are using a ``src``-style -layout (as long as no namespace packages are involved), but you can also -explicitly pass ``package_dir`` to it (as in ``setuptools.setup``). - -Since pybind11 does not require NumPy when building, a light-weight replacement -for NumPy's parallel compilation distutils tool is included. Use it like this: - -.. code-block:: python - - from pybind11.setup_helpers import ParallelCompile - - # Optional multithreaded build - ParallelCompile("NPY_NUM_BUILD_JOBS").install() - - setup(...) - -The argument is the name of an environment variable to control the number of -threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set -something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice -a user might expect. You can also pass ``default=N`` to set the default number -of threads (0 will take the number of threads available) and ``max=N``, the -maximum number of threads; if you have a large extension you may want set this -to a memory dependent number. - -If you are developing rapidly and have a lot of C++ files, you may want to -avoid rebuilding files that have not changed. For simple cases were you are -using ``pip install -e .`` and do not have local headers, you can skip the -rebuild if an object file is newer than its source (headers are not checked!) -with the following: - -.. code-block:: python - - from pybind11.setup_helpers import ParallelCompile, naive_recompile - - ParallelCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install() - - -If you have a more complex build, you can implement a smarter function and pass -it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++" -pip install -e .`` would be the way to use it with GCC, for example. Unlike the -simple solution, this even works even when not compiling in editable mode, but -it does require Ccache to be installed. - -Keep in mind that Pip will not even attempt to rebuild if it thinks it has -already built a copy of your code, which it deduces from the version number. -One way to avoid this is to use [setuptools_scm]_, which will generate a -version number that includes the number of commits since your last tag and a -hash for a dirty directory. Another way to force a rebuild is purge your cache -or use Pip's ``--no-cache-dir`` option. - -.. [Ccache] https://ccache.dev - -.. [setuptools_scm] https://github.com/pypa/setuptools_scm - -.. _setup_helpers-pep518: - -PEP 518 requirements (Pip 10+ required) ---------------------------------------- - -If you use `PEP 518's `_ -``pyproject.toml`` file, you can ensure that ``pybind11`` is available during -the compilation of your project. When this file exists, Pip will make a new -virtual environment, download just the packages listed here in ``requires=``, -and build a wheel (binary Python package). It will then throw away the -environment, and install your wheel. - -Your ``pyproject.toml`` file will likely look something like this: - -.. code-block:: toml - - [build-system] - requires = ["setuptools>=42", "pybind11>=2.6.1"] - build-backend = "setuptools.build_meta" - -.. note:: - - The main drawback to this method is that a `PEP 517`_ compliant build tool, - such as Pip 10+, is required for this approach to work; older versions of - Pip completely ignore this file. If you distribute binaries (called wheels - in Python) using something like `cibuildwheel`_, remember that ``setup.py`` - and ``pyproject.toml`` are not even contained in the wheel, so this high - Pip requirement is only for source builds, and will not affect users of - your binary wheels. If you are building SDists and wheels, then - `pypa-build`_ is the recommended official tool. - -.. _PEP 517: https://www.python.org/dev/peps/pep-0517/ -.. _cibuildwheel: https://cibuildwheel.readthedocs.io -.. _pypa-build: https://pypa-build.readthedocs.io/en/latest/ - -.. _setup_helpers-setup_requires: - -Classic ``setup_requires`` --------------------------- - -If you want to support old versions of Pip with the classic -``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a -two-phase ``setup.py`` run, then you will need to use something like this to -ensure the first pass works (which has not yet installed the ``setup_requires`` -packages, since it can't install something it does not know about): - -.. code-block:: python - - try: - from pybind11.setup_helpers import Pybind11Extension - except ImportError: - from setuptools import Extension as Pybind11Extension - - -It doesn't matter that the Extension class is not the enhanced subclass for the -first pass run; and the second pass will have the ``setup_requires`` -requirements. - -This is obviously more of a hack than the PEP 518 method, but it supports -ancient versions of Pip. - -.. _setup_helpers-copy-manually: - -Copy manually -------------- - -You can also copy ``setup_helpers.py`` directly to your project; it was -designed to be usable standalone, like the old example ``setup.py``. You can -set ``include_pybind11=False`` to skip including the pybind11 package headers, -so you can use it with git submodules and a specific git version. If you use -this, you will need to import from a local file in ``setup.py`` and ensure the -helper file is part of your MANIFEST. - - -Closely related, if you include pybind11 as a subproject, you can run the -``setup_helpers.py`` inplace. If loaded correctly, this should even pick up -the correct include for pybind11, though you can turn it off as shown above if -you want to input it manually. - -Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``: - -.. code-block:: python - - DIR = os.path.abspath(os.path.dirname(__file__)) - - sys.path.append(os.path.join(DIR, "extern", "pybind11")) - from pybind11.setup_helpers import Pybind11Extension # noqa: E402 - - del sys.path[-1] - - -.. versionchanged:: 2.6 - - Added ``setup_helpers`` file. - -Building with cppimport -======================== - -[cppimport]_ is a small Python import hook that determines whether there is a C++ -source file whose name matches the requested module. If there is, the file is -compiled as a Python extension using pybind11 and placed in the same folder as -the C++ source file. Python is then able to find the module and load it. - -.. [cppimport] https://github.com/tbenthompson/cppimport - -.. _cmake: - -Building with CMake -=================== - -For C++ codebases that have an existing CMake-based build system, a Python -extension module can be created with just a few lines of code: - -.. code-block:: cmake - - cmake_minimum_required(VERSION 3.5...3.27) - project(example LANGUAGES CXX) - - add_subdirectory(pybind11) - pybind11_add_module(example example.cpp) - -This assumes that the pybind11 repository is located in a subdirectory named -:file:`pybind11` and that the code is located in a file named :file:`example.cpp`. -The CMake command ``add_subdirectory`` will import the pybind11 project which -provides the ``pybind11_add_module`` function. It will take care of all the -details needed to build a Python extension module on any platform. - -A working sample project, including a way to invoke CMake from :file:`setup.py` for -PyPI integration, can be found in the [cmake_example]_ repository. - -.. [cmake_example] https://github.com/pybind/cmake_example - -.. versionchanged:: 2.6 - CMake 3.4+ is required. - -.. versionchanged:: 2.11 - CMake 3.5+ is required. - -Further information can be found at :doc:`cmake/index`. - -pybind11_add_module -------------------- - -To ease the creation of Python extension modules, pybind11 provides a CMake -function with the following signature: - -.. code-block:: cmake - - pybind11_add_module( [MODULE | SHARED] [EXCLUDE_FROM_ALL] - [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...]) - -This function behaves very much like CMake's builtin ``add_library`` (in fact, -it's a wrapper function around that command). It will add a library target -called ```` to be built from the listed source files. In addition, it -will take care of all the Python-specific compiler and linker flags as well -as the OS- and Python-version-specific file extension. The produced target -```` can be further manipulated with regular CMake commands. - -``MODULE`` or ``SHARED`` may be given to specify the type of library. If no -type is given, ``MODULE`` is used by default which ensures the creation of a -Python-exclusive module. Specifying ``SHARED`` will create a more traditional -dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL`` -removes this target from the default build (see CMake docs for details). - -Since pybind11 is a template library, ``pybind11_add_module`` adds compiler -flags to ensure high quality code generation without bloat arising from long -symbol names and duplication of code in different translation units. It -sets default visibility to *hidden*, which is required for some pybind11 -features and functionality when attempting to load multiple pybind11 modules -compiled under different pybind11 versions. It also adds additional flags -enabling LTO (Link Time Optimization) and strip unneeded symbols. See the -:ref:`FAQ entry ` for a more detailed explanation. These -latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is -given, they will always be disabled, even in ``Release`` mode. However, this -will result in code bloat and is generally not recommended. - -As stated above, LTO is enabled by default. Some newer compilers also support -different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause -the function to prefer this flavor if available. The function falls back to -regular LTO if ``-flto=thin`` is not available. If -``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then -that will be respected instead of the built-in flag search. - -.. note:: - - If you want to set the property form on targets or the - ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_`` versions of this, you should - still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a - no-op) to disable pybind11's ipo flags. - -The ``OPT_SIZE`` flag enables size-based optimization equivalent to the -standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type, -which avoid optimizations that that can substantially increase the size of the -resulting binary. This flag is particularly useful in projects that are split -into performance-critical parts and associated bindings. In this case, we can -compile the project in release mode (and hence, optimize performance globally), -and specify ``OPT_SIZE`` for the binding target, where size might be the main -concern as performance is often less critical here. A ~25% size reduction has -been observed in practice. This flag only changes the optimization behavior at -a per-target level and takes precedence over the global CMake build type -(``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where -optimizations remain disabled. - -.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html - -Configuration variables ------------------------ - -By default, pybind11 will compile modules with the compiler default or the -minimum standard required by pybind11, whichever is higher. You can set the -standard explicitly with -`CMAKE_CXX_STANDARD `_: - -.. code-block:: cmake - - set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20 - set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported - set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensions off - -The variables can also be set when calling CMake from the command line using -the ``-D=`` flag. You can also manually set ``CXX_STANDARD`` -on a target or use ``target_compile_features`` on your targets - anything that -CMake supports. - -Classic Python support: The target Python version can be selected by setting -``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified -with ``PYTHON_EXECUTABLE``. For example: - -.. code-block:: bash - - cmake -DPYBIND11_PYTHON_VERSION=3.6 .. - - # Another method: - cmake -DPYTHON_EXECUTABLE=/path/to/python .. - - # This often is a good way to get the current Python, works in environments: - cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") .. - - -find_package vs. add_subdirectory ---------------------------------- - -For CMake-based projects that don't include the pybind11 repository internally, -an external installation can be detected through ``find_package(pybind11)``. -See the `Config file`_ docstring for details of relevant CMake variables. - -.. code-block:: cmake - - cmake_minimum_required(VERSION 3.4...3.18) - project(example LANGUAGES CXX) - - find_package(pybind11 REQUIRED) - pybind11_add_module(example example.cpp) - -Note that ``find_package(pybind11)`` will only work correctly if pybind11 -has been correctly installed on the system, e. g. after downloading or cloning -the pybind11 repository : - -.. code-block:: bash - - # Classic CMake - cd pybind11 - mkdir build - cd build - cmake .. - make install - - # CMake 3.15+ - cd pybind11 - cmake -S . -B build - cmake --build build -j 2 # Build on 2 cores - cmake --install build - -Once detected, the aforementioned ``pybind11_add_module`` can be employed as -before. The function usage and configuration variables are identical no matter -if pybind11 is added as a subdirectory or found as an installed package. You -can refer to the same [cmake_example]_ repository for a full sample project --- just swap out ``add_subdirectory`` for ``find_package``. - -.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in - - -.. _find-python-mode: - -FindPython mode ---------------- - -CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called -FindPython that had a highly improved search algorithm and modern targets -and tools. If you use FindPython, pybind11 will detect this and use the -existing targets instead: - -.. code-block:: cmake - - cmake_minimum_required(VERSION 3.15...3.22) - project(example LANGUAGES CXX) - - find_package(Python 3.6 COMPONENTS Interpreter Development REQUIRED) - find_package(pybind11 CONFIG REQUIRED) - # or add_subdirectory(pybind11) - - pybind11_add_module(example example.cpp) - -You can also use the targets (as listed below) with FindPython. If you define -``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you -(mostly useful when building pybind11's own tests, or as a way to change search -algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``. - -.. warning:: - - If you use FindPython to multi-target Python versions, use the individual - targets listed below, and avoid targets that directly include Python parts. - -There are `many ways to hint or force a discovery of a specific Python -installation `_), -setting ``Python_ROOT_DIR`` may be the most common one (though with -virtualenv/venv support, and Conda support, this tends to find the correct -Python version more often than the old system did). - -.. warning:: - - When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so`` - on Unix) are not available, as is the case on a manylinux image, the - ``Development`` component will not be resolved by ``FindPython``. When not - using the embedding functionality, CMake 3.18+ allows you to specify - ``Development.Module`` instead of ``Development`` to resolve this issue. - -.. versionadded:: 2.6 - -Advanced: interface library targets ------------------------------------ - -Pybind11 supports modern CMake usage patterns with a set of interface targets, -available in all modes. The targets provided are: - - ``pybind11::headers`` - Just the pybind11 headers and minimum compile requirements - - ``pybind11::pybind11`` - Python headers + ``pybind11::headers`` - - ``pybind11::python_link_helper`` - Just the "linking" part of pybind11:module - - ``pybind11::module`` - Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper`` - - ``pybind11::embed`` - Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs - - ``pybind11::lto`` / ``pybind11::thin_lto`` - An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization. - - ``pybind11::windows_extras`` - ``/bigobj`` and ``/mp`` for MSVC. - - ``pybind11::opt_size`` - ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds. - -Two helper functions are also provided: - - ``pybind11_strip(target)`` - Strips a target (uses ``CMAKE_STRIP`` after the target is built) - - ``pybind11_extension(target)`` - Sets the correct extension (with SOABI) for a target. - -You can use these targets to build complex applications. For example, the -``add_python_module`` function is identical to: - -.. code-block:: cmake - - cmake_minimum_required(VERSION 3.5...3.27) - project(example LANGUAGES CXX) - - find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) - - add_library(example MODULE main.cpp) - - target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras) - - pybind11_extension(example) - if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo) - # Strip unnecessary sections of the binary on Linux/macOS - pybind11_strip(example) - endif() - - set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden" - CUDA_VISIBILITY_PRESET "hidden") - -Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly. - -.. warning:: - - Since pybind11 is a metatemplate library, it is crucial that certain - compiler flags are provided to ensure high quality code generation. In - contrast to the ``pybind11_add_module()`` command, the CMake interface - provides a *composable* set of targets to ensure that you retain flexibility. - It can be especially important to provide or set these properties; the - :ref:`FAQ ` contains an explanation on why these are needed. - -.. versionadded:: 2.6 - -.. _nopython-mode: - -Advanced: NOPYTHON mode ------------------------ - -If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely -disable Python integration (this also happens if you run ``FindPython2`` and -``FindPython3`` without running ``FindPython``). This gives you complete -freedom to integrate into an existing system (like `Scikit-Build's -`_ ``PythonExtensions``). -``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the -targets will be missing any Python specific behavior. - -.. versionadded:: 2.6 - -Embedding the Python interpreter --------------------------------- - -In addition to extension modules, pybind11 also supports embedding Python into -a C++ executable or library. In CMake, simply link with the ``pybind11::embed`` -target. It provides everything needed to get the interpreter running. The Python -headers and libraries are attached to the target. Unlike ``pybind11::module``, -there is no need to manually set any additional properties here. For more -information about usage in C++, see :doc:`/advanced/embedding`. - -.. code-block:: cmake - - cmake_minimum_required(VERSION 3.5...3.27) - project(example LANGUAGES CXX) - - find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) - - add_executable(example main.cpp) - target_link_libraries(example PRIVATE pybind11::embed) - -.. _building_manually: - -Building manually -================= - -pybind11 is a header-only library, hence it is not necessary to link against -any special libraries and there are no intermediate (magic) translation steps. - -On Linux, you can compile an example such as the one given in -:ref:`simple_example` using the following command: - -.. code-block:: bash - - $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) - -The ``python3 -m pybind11 --includes`` command fetches the include paths for -both pybind11 and Python headers. This assumes that pybind11 has been installed -using ``pip`` or ``conda``. If it hasn't, you can also manually specify -``-I /include`` together with the Python includes path -``python3-config --includes``. - -On macOS: the build command is almost the same but it also requires passing -the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when -building the module: - -.. code-block:: bash - - $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) - -In general, it is advisable to include several additional build parameters -that can considerably reduce the size of the created binary. Refer to section -:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based -build system that works on all platforms including Windows. - -.. note:: - - On Linux and macOS, it's better to (intentionally) not link against - ``libpython``. The symbols will be resolved when the extension library - is loaded into a Python binary. This is preferable because you might - have several different installations of a given Python version (e.g. the - system-provided Python, and one that ships with a piece of commercial - software). In this way, the plugin will work with both versions, instead - of possibly importing a second Python library into a process that already - contains one (which will lead to a segfault). - - -Building with Bazel -=================== - -You can build with the Bazel build system using the `pybind11_bazel -`_ repository. - -Generating binding code automatically -===================================== - -The ``Binder`` project is a tool for automatic generation of pybind11 binding -code by introspecting existing C++ codebases using LLVM/Clang. See the -[binder]_ documentation for details. - -.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html - -[AutoWIG]_ is a Python library that wraps automatically compiled libraries into -high-level languages. It parses C++ code using LLVM/Clang technologies and -generates the wrappers using the Mako templating engine. The approach is automatic, -extensible, and applies to very complex C++ libraries, composed of thousands of -classes or incorporating modern meta-programming constructs. - -.. [AutoWIG] https://github.com/StatisKit/AutoWIG - -[robotpy-build]_ is a is a pure python, cross platform build tool that aims to -simplify creation of python wheels for pybind11 projects, and provide -cross-project dependency management. Additionally, it is able to autogenerate -customizable pybind11-based wrappers by parsing C++ header files. - -.. [robotpy-build] https://robotpy-build.readthedocs.io - -[litgen]_ is an automatic python bindings generator with a focus on generating -documented and discoverable bindings: bindings will nicely reproduce the documentation -found in headers. It is is based on srcML (srcml.org), a highly scalable, multi-language -parsing tool with a developer centric approach. The API that you want to expose to python -must be C++14 compatible (but your implementation can use more modern constructs). - -.. [litgen] https://pthom.github.io/litgen +.. _compiling: + +Build systems +############# + +.. _build-setuptools: + +Building with setuptools +======================== + +For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay +has kindly provided an example project which shows how to set up everything, +including automatic generation of documentation using Sphinx. Please refer to +the [python_example]_ repository. + +.. [python_example] https://github.com/pybind/python_example + +A helper file is provided with pybind11 that can simplify usage with setuptools. + +To use pybind11 inside your ``setup.py``, you have to have some system to +ensure that ``pybind11`` is installed when you build your package. There are +four possible ways to do this, and pybind11 supports all four: You can ask all +users to install pybind11 beforehand (bad), you can use +:ref:`setup_helpers-pep518` (good, but very new and requires Pip 10), +:ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that +PEP 518 is available, but it still works everywhere), or you can +:ref:`setup_helpers-copy-manually` (always works but you have to manually sync +your copy to get updates). + +An example of a ``setup.py`` using pybind11's helpers: + +.. code-block:: python + + from glob import glob + from setuptools import setup + from pybind11.setup_helpers import Pybind11Extension + + ext_modules = [ + Pybind11Extension( + "python_example", + sorted(glob("src/*.cpp")), # Sort source files for reproducibility + ), + ] + + setup(..., ext_modules=ext_modules) + +If you want to do an automatic search for the highest supported C++ standard, +that is supported via a ``build_ext`` command override; it will only affect +``Pybind11Extensions``: + +.. code-block:: python + + from glob import glob + from setuptools import setup + from pybind11.setup_helpers import Pybind11Extension, build_ext + + ext_modules = [ + Pybind11Extension( + "python_example", + sorted(glob("src/*.cpp")), + ), + ] + + setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules) + +If you have single-file extension modules that are directly stored in the +Python source tree (``foo.cpp`` in the same directory as where a ``foo.py`` +would be located), you can also generate ``Pybind11Extensions`` using +``setup_helpers.intree_extensions``: ``intree_extensions(["path/to/foo.cpp", +...])`` returns a list of ``Pybind11Extensions`` which can be passed to +``ext_modules``, possibly after further customizing their attributes +(``libraries``, ``include_dirs``, etc.). By doing so, a ``foo.*.so`` extension +module will be generated and made available upon installation. + +``intree_extension`` will automatically detect if you are using a ``src``-style +layout (as long as no namespace packages are involved), but you can also +explicitly pass ``package_dir`` to it (as in ``setuptools.setup``). + +Since pybind11 does not require NumPy when building, a light-weight replacement +for NumPy's parallel compilation distutils tool is included. Use it like this: + +.. code-block:: python + + from pybind11.setup_helpers import ParallelCompile + + # Optional multithreaded build + ParallelCompile("NPY_NUM_BUILD_JOBS").install() + + setup(...) + +The argument is the name of an environment variable to control the number of +threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set +something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice +a user might expect. You can also pass ``default=N`` to set the default number +of threads (0 will take the number of threads available) and ``max=N``, the +maximum number of threads; if you have a large extension you may want set this +to a memory dependent number. + +If you are developing rapidly and have a lot of C++ files, you may want to +avoid rebuilding files that have not changed. For simple cases were you are +using ``pip install -e .`` and do not have local headers, you can skip the +rebuild if an object file is newer than its source (headers are not checked!) +with the following: + +.. code-block:: python + + from pybind11.setup_helpers import ParallelCompile, naive_recompile + + ParallelCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install() + + +If you have a more complex build, you can implement a smarter function and pass +it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++" +pip install -e .`` would be the way to use it with GCC, for example. Unlike the +simple solution, this even works even when not compiling in editable mode, but +it does require Ccache to be installed. + +Keep in mind that Pip will not even attempt to rebuild if it thinks it has +already built a copy of your code, which it deduces from the version number. +One way to avoid this is to use [setuptools_scm]_, which will generate a +version number that includes the number of commits since your last tag and a +hash for a dirty directory. Another way to force a rebuild is purge your cache +or use Pip's ``--no-cache-dir`` option. + +.. [Ccache] https://ccache.dev + +.. [setuptools_scm] https://github.com/pypa/setuptools_scm + +.. _setup_helpers-pep518: + +PEP 518 requirements (Pip 10+ required) +--------------------------------------- + +If you use `PEP 518's `_ +``pyproject.toml`` file, you can ensure that ``pybind11`` is available during +the compilation of your project. When this file exists, Pip will make a new +virtual environment, download just the packages listed here in ``requires=``, +and build a wheel (binary Python package). It will then throw away the +environment, and install your wheel. + +Your ``pyproject.toml`` file will likely look something like this: + +.. code-block:: toml + + [build-system] + requires = ["setuptools>=42", "pybind11>=2.6.1"] + build-backend = "setuptools.build_meta" + +.. note:: + + The main drawback to this method is that a `PEP 517`_ compliant build tool, + such as Pip 10+, is required for this approach to work; older versions of + Pip completely ignore this file. If you distribute binaries (called wheels + in Python) using something like `cibuildwheel`_, remember that ``setup.py`` + and ``pyproject.toml`` are not even contained in the wheel, so this high + Pip requirement is only for source builds, and will not affect users of + your binary wheels. If you are building SDists and wheels, then + `pypa-build`_ is the recommended official tool. + +.. _PEP 517: https://www.python.org/dev/peps/pep-0517/ +.. _cibuildwheel: https://cibuildwheel.readthedocs.io +.. _pypa-build: https://pypa-build.readthedocs.io/en/latest/ + +.. _setup_helpers-setup_requires: + +Classic ``setup_requires`` +-------------------------- + +If you want to support old versions of Pip with the classic +``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a +two-phase ``setup.py`` run, then you will need to use something like this to +ensure the first pass works (which has not yet installed the ``setup_requires`` +packages, since it can't install something it does not know about): + +.. code-block:: python + + try: + from pybind11.setup_helpers import Pybind11Extension + except ImportError: + from setuptools import Extension as Pybind11Extension + + +It doesn't matter that the Extension class is not the enhanced subclass for the +first pass run; and the second pass will have the ``setup_requires`` +requirements. + +This is obviously more of a hack than the PEP 518 method, but it supports +ancient versions of Pip. + +.. _setup_helpers-copy-manually: + +Copy manually +------------- + +You can also copy ``setup_helpers.py`` directly to your project; it was +designed to be usable standalone, like the old example ``setup.py``. You can +set ``include_pybind11=False`` to skip including the pybind11 package headers, +so you can use it with git submodules and a specific git version. If you use +this, you will need to import from a local file in ``setup.py`` and ensure the +helper file is part of your MANIFEST. + + +Closely related, if you include pybind11 as a subproject, you can run the +``setup_helpers.py`` inplace. If loaded correctly, this should even pick up +the correct include for pybind11, though you can turn it off as shown above if +you want to input it manually. + +Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``: + +.. code-block:: python + + DIR = os.path.abspath(os.path.dirname(__file__)) + + sys.path.append(os.path.join(DIR, "extern", "pybind11")) + from pybind11.setup_helpers import Pybind11Extension # noqa: E402 + + del sys.path[-1] + + +.. versionchanged:: 2.6 + + Added ``setup_helpers`` file. + +Building with cppimport +======================== + +[cppimport]_ is a small Python import hook that determines whether there is a C++ +source file whose name matches the requested module. If there is, the file is +compiled as a Python extension using pybind11 and placed in the same folder as +the C++ source file. Python is then able to find the module and load it. + +.. [cppimport] https://github.com/tbenthompson/cppimport + +.. _cmake: + +Building with CMake +=================== + +For C++ codebases that have an existing CMake-based build system, a Python +extension module can be created with just a few lines of code: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.5...3.27) + project(example LANGUAGES CXX) + + add_subdirectory(pybind11) + pybind11_add_module(example example.cpp) + +This assumes that the pybind11 repository is located in a subdirectory named +:file:`pybind11` and that the code is located in a file named :file:`example.cpp`. +The CMake command ``add_subdirectory`` will import the pybind11 project which +provides the ``pybind11_add_module`` function. It will take care of all the +details needed to build a Python extension module on any platform. + +A working sample project, including a way to invoke CMake from :file:`setup.py` for +PyPI integration, can be found in the [cmake_example]_ repository. + +.. [cmake_example] https://github.com/pybind/cmake_example + +.. versionchanged:: 2.6 + CMake 3.4+ is required. + +.. versionchanged:: 2.11 + CMake 3.5+ is required. + +Further information can be found at :doc:`cmake/index`. + +pybind11_add_module +------------------- + +To ease the creation of Python extension modules, pybind11 provides a CMake +function with the following signature: + +.. code-block:: cmake + + pybind11_add_module( [MODULE | SHARED] [EXCLUDE_FROM_ALL] + [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...]) + +This function behaves very much like CMake's builtin ``add_library`` (in fact, +it's a wrapper function around that command). It will add a library target +called ```` to be built from the listed source files. In addition, it +will take care of all the Python-specific compiler and linker flags as well +as the OS- and Python-version-specific file extension. The produced target +```` can be further manipulated with regular CMake commands. + +``MODULE`` or ``SHARED`` may be given to specify the type of library. If no +type is given, ``MODULE`` is used by default which ensures the creation of a +Python-exclusive module. Specifying ``SHARED`` will create a more traditional +dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL`` +removes this target from the default build (see CMake docs for details). + +Since pybind11 is a template library, ``pybind11_add_module`` adds compiler +flags to ensure high quality code generation without bloat arising from long +symbol names and duplication of code in different translation units. It +sets default visibility to *hidden*, which is required for some pybind11 +features and functionality when attempting to load multiple pybind11 modules +compiled under different pybind11 versions. It also adds additional flags +enabling LTO (Link Time Optimization) and strip unneeded symbols. See the +:ref:`FAQ entry ` for a more detailed explanation. These +latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is +given, they will always be disabled, even in ``Release`` mode. However, this +will result in code bloat and is generally not recommended. + +As stated above, LTO is enabled by default. Some newer compilers also support +different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause +the function to prefer this flavor if available. The function falls back to +regular LTO if ``-flto=thin`` is not available. If +``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then +that will be respected instead of the built-in flag search. + +.. note:: + + If you want to set the property form on targets or the + ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_`` versions of this, you should + still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a + no-op) to disable pybind11's ipo flags. + +The ``OPT_SIZE`` flag enables size-based optimization equivalent to the +standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type, +which avoid optimizations that that can substantially increase the size of the +resulting binary. This flag is particularly useful in projects that are split +into performance-critical parts and associated bindings. In this case, we can +compile the project in release mode (and hence, optimize performance globally), +and specify ``OPT_SIZE`` for the binding target, where size might be the main +concern as performance is often less critical here. A ~25% size reduction has +been observed in practice. This flag only changes the optimization behavior at +a per-target level and takes precedence over the global CMake build type +(``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where +optimizations remain disabled. + +.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html + +Configuration variables +----------------------- + +By default, pybind11 will compile modules with the compiler default or the +minimum standard required by pybind11, whichever is higher. You can set the +standard explicitly with +`CMAKE_CXX_STANDARD `_: + +.. code-block:: cmake + + set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20 + set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported + set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensions off + +The variables can also be set when calling CMake from the command line using +the ``-D=`` flag. You can also manually set ``CXX_STANDARD`` +on a target or use ``target_compile_features`` on your targets - anything that +CMake supports. + +Classic Python support: The target Python version can be selected by setting +``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified +with ``PYTHON_EXECUTABLE``. For example: + +.. code-block:: bash + + cmake -DPYBIND11_PYTHON_VERSION=3.6 .. + + # Another method: + cmake -DPYTHON_EXECUTABLE=/path/to/python .. + + # This often is a good way to get the current Python, works in environments: + cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") .. + + +find_package vs. add_subdirectory +--------------------------------- + +For CMake-based projects that don't include the pybind11 repository internally, +an external installation can be detected through ``find_package(pybind11)``. +See the `Config file`_ docstring for details of relevant CMake variables. + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.4...3.18) + project(example LANGUAGES CXX) + + find_package(pybind11 REQUIRED) + pybind11_add_module(example example.cpp) + +Note that ``find_package(pybind11)`` will only work correctly if pybind11 +has been correctly installed on the system, e. g. after downloading or cloning +the pybind11 repository : + +.. code-block:: bash + + # Classic CMake + cd pybind11 + mkdir build + cd build + cmake .. + make install + + # CMake 3.15+ + cd pybind11 + cmake -S . -B build + cmake --build build -j 2 # Build on 2 cores + cmake --install build + +Once detected, the aforementioned ``pybind11_add_module`` can be employed as +before. The function usage and configuration variables are identical no matter +if pybind11 is added as a subdirectory or found as an installed package. You +can refer to the same [cmake_example]_ repository for a full sample project +-- just swap out ``add_subdirectory`` for ``find_package``. + +.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in + + +.. _find-python-mode: + +FindPython mode +--------------- + +CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called +FindPython that had a highly improved search algorithm and modern targets +and tools. If you use FindPython, pybind11 will detect this and use the +existing targets instead: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.15...3.22) + project(example LANGUAGES CXX) + + find_package(Python 3.6 COMPONENTS Interpreter Development REQUIRED) + find_package(pybind11 CONFIG REQUIRED) + # or add_subdirectory(pybind11) + + pybind11_add_module(example example.cpp) + +You can also use the targets (as listed below) with FindPython. If you define +``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you +(mostly useful when building pybind11's own tests, or as a way to change search +algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``. + +.. warning:: + + If you use FindPython to multi-target Python versions, use the individual + targets listed below, and avoid targets that directly include Python parts. + +There are `many ways to hint or force a discovery of a specific Python +installation `_), +setting ``Python_ROOT_DIR`` may be the most common one (though with +virtualenv/venv support, and Conda support, this tends to find the correct +Python version more often than the old system did). + +.. warning:: + + When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so`` + on Unix) are not available, as is the case on a manylinux image, the + ``Development`` component will not be resolved by ``FindPython``. When not + using the embedding functionality, CMake 3.18+ allows you to specify + ``Development.Module`` instead of ``Development`` to resolve this issue. + +.. versionadded:: 2.6 + +Advanced: interface library targets +----------------------------------- + +Pybind11 supports modern CMake usage patterns with a set of interface targets, +available in all modes. The targets provided are: + + ``pybind11::headers`` + Just the pybind11 headers and minimum compile requirements + + ``pybind11::pybind11`` + Python headers + ``pybind11::headers`` + + ``pybind11::python_link_helper`` + Just the "linking" part of pybind11:module + + ``pybind11::module`` + Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper`` + + ``pybind11::embed`` + Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs + + ``pybind11::lto`` / ``pybind11::thin_lto`` + An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization. + + ``pybind11::windows_extras`` + ``/bigobj`` and ``/mp`` for MSVC. + + ``pybind11::opt_size`` + ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds. + +Two helper functions are also provided: + + ``pybind11_strip(target)`` + Strips a target (uses ``CMAKE_STRIP`` after the target is built) + + ``pybind11_extension(target)`` + Sets the correct extension (with SOABI) for a target. + +You can use these targets to build complex applications. For example, the +``add_python_module`` function is identical to: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.5...3.27) + project(example LANGUAGES CXX) + + find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) + + add_library(example MODULE main.cpp) + + target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras) + + pybind11_extension(example) + if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo) + # Strip unnecessary sections of the binary on Linux/macOS + pybind11_strip(example) + endif() + + set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden" + CUDA_VISIBILITY_PRESET "hidden") + +Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly. + +.. warning:: + + Since pybind11 is a metatemplate library, it is crucial that certain + compiler flags are provided to ensure high quality code generation. In + contrast to the ``pybind11_add_module()`` command, the CMake interface + provides a *composable* set of targets to ensure that you retain flexibility. + It can be especially important to provide or set these properties; the + :ref:`FAQ ` contains an explanation on why these are needed. + +.. versionadded:: 2.6 + +.. _nopython-mode: + +Advanced: NOPYTHON mode +----------------------- + +If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely +disable Python integration (this also happens if you run ``FindPython2`` and +``FindPython3`` without running ``FindPython``). This gives you complete +freedom to integrate into an existing system (like `Scikit-Build's +`_ ``PythonExtensions``). +``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the +targets will be missing any Python specific behavior. + +.. versionadded:: 2.6 + +Embedding the Python interpreter +-------------------------------- + +In addition to extension modules, pybind11 also supports embedding Python into +a C++ executable or library. In CMake, simply link with the ``pybind11::embed`` +target. It provides everything needed to get the interpreter running. The Python +headers and libraries are attached to the target. Unlike ``pybind11::module``, +there is no need to manually set any additional properties here. For more +information about usage in C++, see :doc:`/advanced/embedding`. + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.5...3.27) + project(example LANGUAGES CXX) + + find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) + + add_executable(example main.cpp) + target_link_libraries(example PRIVATE pybind11::embed) + +.. _building_manually: + +Building manually +================= + +pybind11 is a header-only library, hence it is not necessary to link against +any special libraries and there are no intermediate (magic) translation steps. + +On Linux, you can compile an example such as the one given in +:ref:`simple_example` using the following command: + +.. code-block:: bash + + $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) + +The ``python3 -m pybind11 --includes`` command fetches the include paths for +both pybind11 and Python headers. This assumes that pybind11 has been installed +using ``pip`` or ``conda``. If it hasn't, you can also manually specify +``-I /include`` together with the Python includes path +``python3-config --includes``. + +On macOS: the build command is almost the same but it also requires passing +the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when +building the module: + +.. code-block:: bash + + $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) + +In general, it is advisable to include several additional build parameters +that can considerably reduce the size of the created binary. Refer to section +:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based +build system that works on all platforms including Windows. + +.. note:: + + On Linux and macOS, it's better to (intentionally) not link against + ``libpython``. The symbols will be resolved when the extension library + is loaded into a Python binary. This is preferable because you might + have several different installations of a given Python version (e.g. the + system-provided Python, and one that ships with a piece of commercial + software). In this way, the plugin will work with both versions, instead + of possibly importing a second Python library into a process that already + contains one (which will lead to a segfault). + + +Building with Bazel +=================== + +You can build with the Bazel build system using the `pybind11_bazel +`_ repository. + +Generating binding code automatically +===================================== + +The ``Binder`` project is a tool for automatic generation of pybind11 binding +code by introspecting existing C++ codebases using LLVM/Clang. See the +[binder]_ documentation for details. + +.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html + +[AutoWIG]_ is a Python library that wraps automatically compiled libraries into +high-level languages. It parses C++ code using LLVM/Clang technologies and +generates the wrappers using the Mako templating engine. The approach is automatic, +extensible, and applies to very complex C++ libraries, composed of thousands of +classes or incorporating modern meta-programming constructs. + +.. [AutoWIG] https://github.com/StatisKit/AutoWIG + +[robotpy-build]_ is a is a pure python, cross platform build tool that aims to +simplify creation of python wheels for pybind11 projects, and provide +cross-project dependency management. Additionally, it is able to autogenerate +customizable pybind11-based wrappers by parsing C++ header files. + +.. [robotpy-build] https://robotpy-build.readthedocs.io + +[litgen]_ is an automatic python bindings generator with a focus on generating +documented and discoverable bindings: bindings will nicely reproduce the documentation +found in headers. It is is based on srcML (srcml.org), a highly scalable, multi-language +parsing tool with a developer centric approach. The API that you want to expose to python +must be C++14 compatible (but your implementation can use more modern constructs). + +.. [litgen] https://pthom.github.io/litgen diff --git a/third_party/CityFlow/extern/pybind11/docs/conf.py b/third_party/CityFlow/extern/pybind11/docs/conf.py index 6e24751e9ee830b43bed01f99e4fabd11ce586c4..b5fbd7606545043b929020eca93f3c77af183256 100644 --- a/third_party/CityFlow/extern/pybind11/docs/conf.py +++ b/third_party/CityFlow/extern/pybind11/docs/conf.py @@ -1,368 +1,368 @@ -#!/usr/bin/env python3 -# -# pybind11 documentation build configuration file, created by -# sphinx-quickstart on Sun Oct 11 19:23:48 2015. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import os -import re -import subprocess -import sys -from pathlib import Path - -DIR = Path(__file__).parent.resolve() - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "breathe", - "sphinx_copybutton", - "sphinxcontrib.rsvgconverter", - "sphinxcontrib.moderncmakedomain", -] - -breathe_projects = {"pybind11": ".build/doxygenxml/"} -breathe_default_project = "pybind11" -breathe_domain_by_extension = {"h": "cpp"} - -# Add any paths that contain templates here, relative to this directory. -templates_path = [".templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = ".rst" - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = "pybind11" -copyright = "2017, Wenzel Jakob" -author = "Wenzel Jakob" - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. - -# Read the listed version -with open("../pybind11/_version.py") as f: - code = compile(f.read(), "../pybind11/_version.py", "exec") -loc = {} -exec(code, loc) - -# The full version, including alpha/beta/rc tags. -version = loc["__version__"] - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [".build", "release.rst"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -default_role = "any" - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -# pygments_style = 'monokai' - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. - -html_theme = "furo" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -html_css_files = [ - "css/custom.css", -] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "pybind11doc" - -# -- Options for LaTeX output --------------------------------------------- - -latex_engine = "pdflatex" - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # - # Additional stuff for the LaTeX preamble. - # remove blank pages (between the title page and the TOC, etc.) - "classoptions": ",openany,oneside", - "preamble": r""" -\usepackage{fontawesome} -\usepackage{textgreek} -\DeclareUnicodeCharacter{00A0}{} -\DeclareUnicodeCharacter{2194}{\faArrowsH} -\DeclareUnicodeCharacter{1F382}{\faBirthdayCake} -\DeclareUnicodeCharacter{1F355}{\faAdjust} -\DeclareUnicodeCharacter{0301}{'} -\DeclareUnicodeCharacter{03C0}{\textpi} - -""", - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, "pybind11.tex", "pybind11 Documentation", "Wenzel Jakob", "manual"), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = 'pybind11-logo.png' - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [(master_doc, "pybind11", "pybind11 Documentation", [author], 1)] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "pybind11", - "pybind11 Documentation", - author, - "pybind11", - "One line description of project.", - "Miscellaneous", - ), -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - -primary_domain = "cpp" -highlight_language = "cpp" - - -def generate_doxygen_xml(app): - build_dir = os.path.join(app.confdir, ".build") - if not os.path.exists(build_dir): - os.mkdir(build_dir) - - try: - subprocess.call(["doxygen", "--version"]) - retcode = subprocess.call(["doxygen"], cwd=app.confdir) - if retcode < 0: - sys.stderr.write(f"doxygen error code: {-retcode}\n") - except OSError as e: - sys.stderr.write(f"doxygen execution failed: {e}\n") - - -def prepare(app): - with open(DIR.parent / "README.rst") as f: - contents = f.read() - - if app.builder.name == "latex": - # Remove badges and stuff from start - contents = contents[contents.find(r".. start") :] - - # Filter out section titles for index.rst for LaTeX - contents = re.sub(r"^(.*)\n[-~]{3,}$", r"**\1**", contents, flags=re.MULTILINE) - - with open(DIR / "readme.rst", "w") as f: - f.write(contents) - - -def clean_up(app, exception): # noqa: ARG001 - (DIR / "readme.rst").unlink() - - -def setup(app): - # Add hook for building doxygen xml when needed - app.connect("builder-inited", generate_doxygen_xml) - - # Copy the readme in - app.connect("builder-inited", prepare) - - # Clean up the generated readme - app.connect("build-finished", clean_up) +#!/usr/bin/env python3 +# +# pybind11 documentation build configuration file, created by +# sphinx-quickstart on Sun Oct 11 19:23:48 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import re +import subprocess +import sys +from pathlib import Path + +DIR = Path(__file__).parent.resolve() + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "breathe", + "sphinx_copybutton", + "sphinxcontrib.rsvgconverter", + "sphinxcontrib.moderncmakedomain", +] + +breathe_projects = {"pybind11": ".build/doxygenxml/"} +breathe_default_project = "pybind11" +breathe_domain_by_extension = {"h": "cpp"} + +# Add any paths that contain templates here, relative to this directory. +templates_path = [".templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = "pybind11" +copyright = "2017, Wenzel Jakob" +author = "Wenzel Jakob" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. + +# Read the listed version +with open("../pybind11/_version.py") as f: + code = compile(f.read(), "../pybind11/_version.py", "exec") +loc = {} +exec(code, loc) + +# The full version, including alpha/beta/rc tags. +version = loc["__version__"] + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [".build", "release.rst"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +default_role = "any" + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +# pygments_style = 'monokai' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. + +html_theme = "furo" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +html_css_files = [ + "css/custom.css", +] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "pybind11doc" + +# -- Options for LaTeX output --------------------------------------------- + +latex_engine = "pdflatex" + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # + # Additional stuff for the LaTeX preamble. + # remove blank pages (between the title page and the TOC, etc.) + "classoptions": ",openany,oneside", + "preamble": r""" +\usepackage{fontawesome} +\usepackage{textgreek} +\DeclareUnicodeCharacter{00A0}{} +\DeclareUnicodeCharacter{2194}{\faArrowsH} +\DeclareUnicodeCharacter{1F382}{\faBirthdayCake} +\DeclareUnicodeCharacter{1F355}{\faAdjust} +\DeclareUnicodeCharacter{0301}{'} +\DeclareUnicodeCharacter{03C0}{\textpi} + +""", + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, "pybind11.tex", "pybind11 Documentation", "Wenzel Jakob", "manual"), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = 'pybind11-logo.png' + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [(master_doc, "pybind11", "pybind11 Documentation", [author], 1)] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "pybind11", + "pybind11 Documentation", + author, + "pybind11", + "One line description of project.", + "Miscellaneous", + ), +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + +primary_domain = "cpp" +highlight_language = "cpp" + + +def generate_doxygen_xml(app): + build_dir = os.path.join(app.confdir, ".build") + if not os.path.exists(build_dir): + os.mkdir(build_dir) + + try: + subprocess.call(["doxygen", "--version"]) + retcode = subprocess.call(["doxygen"], cwd=app.confdir) + if retcode < 0: + sys.stderr.write(f"doxygen error code: {-retcode}\n") + except OSError as e: + sys.stderr.write(f"doxygen execution failed: {e}\n") + + +def prepare(app): + with open(DIR.parent / "README.rst") as f: + contents = f.read() + + if app.builder.name == "latex": + # Remove badges and stuff from start + contents = contents[contents.find(r".. start") :] + + # Filter out section titles for index.rst for LaTeX + contents = re.sub(r"^(.*)\n[-~]{3,}$", r"**\1**", contents, flags=re.MULTILINE) + + with open(DIR / "readme.rst", "w") as f: + f.write(contents) + + +def clean_up(app, exception): # noqa: ARG001 + (DIR / "readme.rst").unlink() + + +def setup(app): + # Add hook for building doxygen xml when needed + app.connect("builder-inited", generate_doxygen_xml) + + # Copy the readme in + app.connect("builder-inited", prepare) + + # Clean up the generated readme + app.connect("build-finished", clean_up) diff --git a/third_party/CityFlow/extern/pybind11/docs/faq.rst b/third_party/CityFlow/extern/pybind11/docs/faq.rst index 1eb00efada9e986b5fefaac67da12018ca5a3df0..e44934063ccce8ea8670bb139e685d25ba41b232 100644 --- a/third_party/CityFlow/extern/pybind11/docs/faq.rst +++ b/third_party/CityFlow/extern/pybind11/docs/faq.rst @@ -1,308 +1,308 @@ -Frequently asked questions -########################## - -"ImportError: dynamic module does not define init function" -=========================================================== - -1. Make sure that the name specified in PYBIND11_MODULE is identical to the -filename of the extension library (without suffixes such as ``.so``). - -2. If the above did not fix the issue, you are likely using an incompatible -version of Python that does not match what you compiled with. - -"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``" -======================================================================== - -See the first answer. - -"SystemError: dynamic module not initialized properly" -====================================================== - -See the first answer. - -The Python interpreter immediately crashes when importing my module -=================================================================== - -See the first answer. - -.. _faq_reference_arguments: - -Limitations involving reference arguments -========================================= - -In C++, it's fairly common to pass arguments using mutable references or -mutable pointers, which allows both read and write access to the value -supplied by the caller. This is sometimes done for efficiency reasons, or to -realize functions that have multiple return values. Here are two very basic -examples: - -.. code-block:: cpp - - void increment(int &i) { i++; } - void increment_ptr(int *i) { (*i)++; } - -In Python, all arguments are passed by reference, so there is no general -issue in binding such code from Python. - -However, certain basic Python types (like ``str``, ``int``, ``bool``, -``float``, etc.) are **immutable**. This means that the following attempt -to port the function to Python doesn't have the same effect on the value -provided by the caller -- in fact, it does nothing at all. - -.. code-block:: python - - def increment(i): - i += 1 # nope.. - -pybind11 is also affected by such language-level conventions, which means that -binding ``increment`` or ``increment_ptr`` will also create Python functions -that don't modify their arguments. - -Although inconvenient, one workaround is to encapsulate the immutable types in -a custom type that does allow modifications. - -An other alternative involves binding a small wrapper lambda function that -returns a tuple with all output arguments (see the remainder of the -documentation for examples on binding lambda functions). An example: - -.. code-block:: cpp - - int foo(int &i) { i++; return 123; } - -and the binding code - -.. code-block:: cpp - - m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); }); - - -How can I reduce the build time? -================================ - -It's good practice to split binding code over multiple files, as in the -following example: - -:file:`example.cpp`: - -.. code-block:: cpp - - void init_ex1(py::module_ &); - void init_ex2(py::module_ &); - /* ... */ - - PYBIND11_MODULE(example, m) { - init_ex1(m); - init_ex2(m); - /* ... */ - } - -:file:`ex1.cpp`: - -.. code-block:: cpp - - void init_ex1(py::module_ &m) { - m.def("add", [](int a, int b) { return a + b; }); - } - -:file:`ex2.cpp`: - -.. code-block:: cpp - - void init_ex2(py::module_ &m) { - m.def("sub", [](int a, int b) { return a - b; }); - } - -:command:`python`: - -.. code-block:: pycon - - >>> import example - >>> example.add(1, 2) - 3 - >>> example.sub(1, 1) - 0 - -As shown above, the various ``init_ex`` functions should be contained in -separate files that can be compiled independently from one another, and then -linked together into the same final shared object. Following this approach -will: - -1. reduce memory requirements per compilation unit. - -2. enable parallel builds (if desired). - -3. allow for faster incremental builds. For instance, when a single class - definition is changed, only a subset of the binding code will generally need - to be recompiled. - -"recursive template instantiation exceeded maximum depth of 256" -================================================================ - -If you receive an error about excessive recursive template evaluation, try -specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The -culprit is generally the generation of function signatures at compile time -using C++14 template metaprogramming. - -.. _`faq:hidden_visibility`: - -"'SomeClass' declared with greater visibility than the type of its field 'SomeClass::member' [-Wattributes]" -============================================================================================================ - -This error typically indicates that you are compiling without the required -``-fvisibility`` flag. pybind11 code internally forces hidden visibility on -all internal code, but if non-hidden (and thus *exported*) code attempts to -include a pybind type (for example, ``py::object`` or ``py::list``) you can run -into this warning. - -To avoid it, make sure you are specifying ``-fvisibility=hidden`` when -compiling pybind code. - -As to why ``-fvisibility=hidden`` is necessary, because pybind modules could -have been compiled under different versions of pybind itself, it is also -important that the symbols defined in one module do not clash with the -potentially-incompatible symbols defined in another. While Python extension -modules are usually loaded with localized symbols (under POSIX systems -typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default -can be changed, but even if it isn't it is not always enough to guarantee -complete independence of the symbols involved when not using -``-fvisibility=hidden``. - -Additionally, ``-fvisibility=hidden`` can deliver considerably binary size -savings. (See the following section for more details.) - - -.. _`faq:symhidden`: - -How can I create smaller binaries? -================================== - -To do its job, pybind11 extensively relies on a programming technique known as -*template metaprogramming*, which is a way of performing computation at compile -time using type information. Template metaprogramming usually instantiates code -involving significant numbers of deeply nested types that are either completely -removed or reduced to just a few instructions during the compiler's optimization -phase. However, due to the nested nature of these types, the resulting symbol -names in the compiled extension library can be extremely long. For instance, -the included test suite contains the following symbol: - -.. only:: html - - .. code-block:: none - - _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_ - -.. only:: not html - - .. code-block:: cpp - - __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_ - -which is the mangled form of the following function type: - -.. code-block:: cpp - - pybind11::cpp_function::cpp_function, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28]) - -The memory needed to store just the mangled name of this function (196 bytes) -is larger than the actual piece of code (111 bytes) it represents! On the other -hand, it's silly to even give this function a name -- after all, it's just a -tiny cog in a bigger piece of machinery that is not exposed to the outside -world. So we'll generally only want to export symbols for those functions which -are actually called from the outside. - -This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC -and Clang, which sets the default symbol visibility to *hidden*, which has a -tremendous impact on the final binary size of the resulting extension library. -(On Visual Studio, symbols are already hidden by default, so nothing needs to -be done there.) - -In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids -potential serious issues when loading multiple modules and is required for -proper pybind operation. See the previous FAQ entry for more details. - -How can I properly handle Ctrl-C in long-running functions? -=========================================================== - -Ctrl-C is received by the Python interpreter, and holds it until the GIL -is released, so a long-running function won't be interrupted. - -To interrupt from inside your function, you can use the ``PyErr_CheckSignals()`` -function, that will tell if a signal has been raised on the Python side. This -function merely checks a flag, so its impact is negligible. When a signal has -been received, you must either explicitly interrupt execution by throwing -``py::error_already_set`` (which will propagate the existing -``KeyboardInterrupt``), or clear the error (which you usually will not want): - -.. code-block:: cpp - - PYBIND11_MODULE(example, m) - { - m.def("long running_func", []() - { - for (;;) { - if (PyErr_CheckSignals() != 0) - throw py::error_already_set(); - // Long running iteration - } - }); - } - -CMake doesn't detect the right Python version -============================================= - -The CMake-based build system will try to automatically detect the installed -version of Python and link against that. When this fails, or when there are -multiple versions of Python and it finds the wrong one, delete -``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your -CMake configure line. (Replace ``$(which python)`` with a path to python if -your prefer.) - -You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the -new CMake FindPython support instead of pybind11's custom search. Requires -CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your -``CMakeLists.txt`` before adding or finding pybind11, as well. - -Inconsistent detection of Python version in CMake and pybind11 -============================================================== - -The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` -provided by CMake for Python version detection are modified by pybind11 due to -unreliability and limitations that make them unsuitable for pybind11's needs. -Instead pybind11 provides its own, more reliable Python detection CMake code. -Conflicts can arise, however, when using pybind11 in a project that *also* uses -the CMake Python detection in a system with several Python versions installed. - -This difference may cause inconsistencies and errors if *both* mechanisms are -used in the same project. - -There are three possible solutions: - -1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` - from CMake and rely on pybind11 in detecting Python version. If this is not - possible, the CMake machinery should be called *before* including pybind11. -2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python - COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better, - 3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead - of the old, deprecated search tools, and these modules are much better at - finding the correct Python. If FindPythonLibs/Interp are not available - (CMake 3.27+), then this will be ignored and FindPython will be used. -3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python. - However, you will have to use the target-based system, and do more setup - yourself, because it does not know about or include things that depend on - Python, like ``pybind11_add_module``. This might be ideal for integrating - into an existing system, like scikit-build's Python helpers. - -How to cite this project? -========================= - -We suggest the following BibTeX template to cite pybind11 in scientific -discourse: - -.. code-block:: bash - - @misc{pybind11, - author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan}, - year = {2017}, - note = {https://github.com/pybind/pybind11}, - title = {pybind11 -- Seamless operability between C++11 and Python} - } +Frequently asked questions +########################## + +"ImportError: dynamic module does not define init function" +=========================================================== + +1. Make sure that the name specified in PYBIND11_MODULE is identical to the +filename of the extension library (without suffixes such as ``.so``). + +2. If the above did not fix the issue, you are likely using an incompatible +version of Python that does not match what you compiled with. + +"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``" +======================================================================== + +See the first answer. + +"SystemError: dynamic module not initialized properly" +====================================================== + +See the first answer. + +The Python interpreter immediately crashes when importing my module +=================================================================== + +See the first answer. + +.. _faq_reference_arguments: + +Limitations involving reference arguments +========================================= + +In C++, it's fairly common to pass arguments using mutable references or +mutable pointers, which allows both read and write access to the value +supplied by the caller. This is sometimes done for efficiency reasons, or to +realize functions that have multiple return values. Here are two very basic +examples: + +.. code-block:: cpp + + void increment(int &i) { i++; } + void increment_ptr(int *i) { (*i)++; } + +In Python, all arguments are passed by reference, so there is no general +issue in binding such code from Python. + +However, certain basic Python types (like ``str``, ``int``, ``bool``, +``float``, etc.) are **immutable**. This means that the following attempt +to port the function to Python doesn't have the same effect on the value +provided by the caller -- in fact, it does nothing at all. + +.. code-block:: python + + def increment(i): + i += 1 # nope.. + +pybind11 is also affected by such language-level conventions, which means that +binding ``increment`` or ``increment_ptr`` will also create Python functions +that don't modify their arguments. + +Although inconvenient, one workaround is to encapsulate the immutable types in +a custom type that does allow modifications. + +An other alternative involves binding a small wrapper lambda function that +returns a tuple with all output arguments (see the remainder of the +documentation for examples on binding lambda functions). An example: + +.. code-block:: cpp + + int foo(int &i) { i++; return 123; } + +and the binding code + +.. code-block:: cpp + + m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); }); + + +How can I reduce the build time? +================================ + +It's good practice to split binding code over multiple files, as in the +following example: + +:file:`example.cpp`: + +.. code-block:: cpp + + void init_ex1(py::module_ &); + void init_ex2(py::module_ &); + /* ... */ + + PYBIND11_MODULE(example, m) { + init_ex1(m); + init_ex2(m); + /* ... */ + } + +:file:`ex1.cpp`: + +.. code-block:: cpp + + void init_ex1(py::module_ &m) { + m.def("add", [](int a, int b) { return a + b; }); + } + +:file:`ex2.cpp`: + +.. code-block:: cpp + + void init_ex2(py::module_ &m) { + m.def("sub", [](int a, int b) { return a - b; }); + } + +:command:`python`: + +.. code-block:: pycon + + >>> import example + >>> example.add(1, 2) + 3 + >>> example.sub(1, 1) + 0 + +As shown above, the various ``init_ex`` functions should be contained in +separate files that can be compiled independently from one another, and then +linked together into the same final shared object. Following this approach +will: + +1. reduce memory requirements per compilation unit. + +2. enable parallel builds (if desired). + +3. allow for faster incremental builds. For instance, when a single class + definition is changed, only a subset of the binding code will generally need + to be recompiled. + +"recursive template instantiation exceeded maximum depth of 256" +================================================================ + +If you receive an error about excessive recursive template evaluation, try +specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The +culprit is generally the generation of function signatures at compile time +using C++14 template metaprogramming. + +.. _`faq:hidden_visibility`: + +"'SomeClass' declared with greater visibility than the type of its field 'SomeClass::member' [-Wattributes]" +============================================================================================================ + +This error typically indicates that you are compiling without the required +``-fvisibility`` flag. pybind11 code internally forces hidden visibility on +all internal code, but if non-hidden (and thus *exported*) code attempts to +include a pybind type (for example, ``py::object`` or ``py::list``) you can run +into this warning. + +To avoid it, make sure you are specifying ``-fvisibility=hidden`` when +compiling pybind code. + +As to why ``-fvisibility=hidden`` is necessary, because pybind modules could +have been compiled under different versions of pybind itself, it is also +important that the symbols defined in one module do not clash with the +potentially-incompatible symbols defined in another. While Python extension +modules are usually loaded with localized symbols (under POSIX systems +typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default +can be changed, but even if it isn't it is not always enough to guarantee +complete independence of the symbols involved when not using +``-fvisibility=hidden``. + +Additionally, ``-fvisibility=hidden`` can deliver considerably binary size +savings. (See the following section for more details.) + + +.. _`faq:symhidden`: + +How can I create smaller binaries? +================================== + +To do its job, pybind11 extensively relies on a programming technique known as +*template metaprogramming*, which is a way of performing computation at compile +time using type information. Template metaprogramming usually instantiates code +involving significant numbers of deeply nested types that are either completely +removed or reduced to just a few instructions during the compiler's optimization +phase. However, due to the nested nature of these types, the resulting symbol +names in the compiled extension library can be extremely long. For instance, +the included test suite contains the following symbol: + +.. only:: html + + .. code-block:: none + + _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_ + +.. only:: not html + + .. code-block:: cpp + + __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_ + +which is the mangled form of the following function type: + +.. code-block:: cpp + + pybind11::cpp_function::cpp_function, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28]) + +The memory needed to store just the mangled name of this function (196 bytes) +is larger than the actual piece of code (111 bytes) it represents! On the other +hand, it's silly to even give this function a name -- after all, it's just a +tiny cog in a bigger piece of machinery that is not exposed to the outside +world. So we'll generally only want to export symbols for those functions which +are actually called from the outside. + +This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC +and Clang, which sets the default symbol visibility to *hidden*, which has a +tremendous impact on the final binary size of the resulting extension library. +(On Visual Studio, symbols are already hidden by default, so nothing needs to +be done there.) + +In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids +potential serious issues when loading multiple modules and is required for +proper pybind operation. See the previous FAQ entry for more details. + +How can I properly handle Ctrl-C in long-running functions? +=========================================================== + +Ctrl-C is received by the Python interpreter, and holds it until the GIL +is released, so a long-running function won't be interrupted. + +To interrupt from inside your function, you can use the ``PyErr_CheckSignals()`` +function, that will tell if a signal has been raised on the Python side. This +function merely checks a flag, so its impact is negligible. When a signal has +been received, you must either explicitly interrupt execution by throwing +``py::error_already_set`` (which will propagate the existing +``KeyboardInterrupt``), or clear the error (which you usually will not want): + +.. code-block:: cpp + + PYBIND11_MODULE(example, m) + { + m.def("long running_func", []() + { + for (;;) { + if (PyErr_CheckSignals() != 0) + throw py::error_already_set(); + // Long running iteration + } + }); + } + +CMake doesn't detect the right Python version +============================================= + +The CMake-based build system will try to automatically detect the installed +version of Python and link against that. When this fails, or when there are +multiple versions of Python and it finds the wrong one, delete +``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your +CMake configure line. (Replace ``$(which python)`` with a path to python if +your prefer.) + +You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the +new CMake FindPython support instead of pybind11's custom search. Requires +CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your +``CMakeLists.txt`` before adding or finding pybind11, as well. + +Inconsistent detection of Python version in CMake and pybind11 +============================================================== + +The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` +provided by CMake for Python version detection are modified by pybind11 due to +unreliability and limitations that make them unsuitable for pybind11's needs. +Instead pybind11 provides its own, more reliable Python detection CMake code. +Conflicts can arise, however, when using pybind11 in a project that *also* uses +the CMake Python detection in a system with several Python versions installed. + +This difference may cause inconsistencies and errors if *both* mechanisms are +used in the same project. + +There are three possible solutions: + +1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` + from CMake and rely on pybind11 in detecting Python version. If this is not + possible, the CMake machinery should be called *before* including pybind11. +2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python + COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better, + 3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead + of the old, deprecated search tools, and these modules are much better at + finding the correct Python. If FindPythonLibs/Interp are not available + (CMake 3.27+), then this will be ignored and FindPython will be used. +3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python. + However, you will have to use the target-based system, and do more setup + yourself, because it does not know about or include things that depend on + Python, like ``pybind11_add_module``. This might be ideal for integrating + into an existing system, like scikit-build's Python helpers. + +How to cite this project? +========================= + +We suggest the following BibTeX template to cite pybind11 in scientific +discourse: + +.. code-block:: bash + + @misc{pybind11, + author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan}, + year = {2017}, + note = {https://github.com/pybind/pybind11}, + title = {pybind11 -- Seamless operability between C++11 and Python} + } diff --git a/third_party/CityFlow/extern/pybind11/docs/index.rst b/third_party/CityFlow/extern/pybind11/docs/index.rst index 4e2e8ca3a04a072d9adfdfa4bb98f5c221be10ea..dbb2ad6b67f177dd7ef96e8d7fa7ef18e44bd213 100644 --- a/third_party/CityFlow/extern/pybind11/docs/index.rst +++ b/third_party/CityFlow/extern/pybind11/docs/index.rst @@ -1,48 +1,48 @@ -.. only:: latex - - Intro - ===== - -.. include:: readme.rst - -.. only:: not latex - - Contents: - -.. toctree:: - :maxdepth: 1 - - changelog - upgrade - -.. toctree:: - :caption: The Basics - :maxdepth: 2 - - installing - basics - classes - compiling - -.. toctree:: - :caption: Advanced Topics - :maxdepth: 2 - - advanced/functions - advanced/classes - advanced/exceptions - advanced/smart_ptrs - advanced/cast/index - advanced/pycpp/index - advanced/embedding - advanced/misc - -.. toctree:: - :caption: Extra Information - :maxdepth: 1 - - faq - benchmark - limitations - reference - cmake/index +.. only:: latex + + Intro + ===== + +.. include:: readme.rst + +.. only:: not latex + + Contents: + +.. toctree:: + :maxdepth: 1 + + changelog + upgrade + +.. toctree:: + :caption: The Basics + :maxdepth: 2 + + installing + basics + classes + compiling + +.. toctree:: + :caption: Advanced Topics + :maxdepth: 2 + + advanced/functions + advanced/classes + advanced/exceptions + advanced/smart_ptrs + advanced/cast/index + advanced/pycpp/index + advanced/embedding + advanced/misc + +.. toctree:: + :caption: Extra Information + :maxdepth: 1 + + faq + benchmark + limitations + reference + cmake/index diff --git a/third_party/CityFlow/extern/pybind11/docs/installing.rst b/third_party/CityFlow/extern/pybind11/docs/installing.rst index 30b9f1853d7edf9b90f88ff347be63648056f99f..0fb4602ccfebfca833c29b94bef26a17f4bf1569 100644 --- a/third_party/CityFlow/extern/pybind11/docs/installing.rst +++ b/third_party/CityFlow/extern/pybind11/docs/installing.rst @@ -1,105 +1,105 @@ -.. _installing: - -Installing the library -###################### - -There are several ways to get the pybind11 source, which lives at -`pybind/pybind11 on GitHub `_. The pybind11 -developers recommend one of the first three ways listed here, submodule, PyPI, -or conda-forge, for obtaining pybind11. - -.. _include_as_a_submodule: - -Include as a submodule -====================== - -When you are working on a project in Git, you can use the pybind11 repository -as a submodule. From your git repository, use: - -.. code-block:: bash - - git submodule add -b stable ../../pybind/pybind11 extern/pybind11 - git submodule update --init - -This assumes you are placing your dependencies in ``extern/``, and that you are -using GitHub; if you are not using GitHub, use the full https or ssh URL -instead of the relative URL ``../../pybind/pybind11`` above. Some other servers -also require the ``.git`` extension (GitHub does not). - -From here, you can now include ``extern/pybind11/include``, or you can use -the various integration tools (see :ref:`compiling`) pybind11 provides directly -from the local folder. - -Include with PyPI -================= - -You can download the sources and CMake files as a Python package from PyPI -using Pip. Just use: - -.. code-block:: bash - - pip install pybind11 - -This will provide pybind11 in a standard Python package format. If you want -pybind11 available directly in your environment root, you can use: - -.. code-block:: bash - - pip install "pybind11[global]" - -This is not recommended if you are installing with your system Python, as it -will add files to ``/usr/local/include/pybind11`` and -``/usr/local/share/cmake/pybind11``, so unless that is what you want, it is -recommended only for use in virtual environments or your ``pyproject.toml`` -file (see :ref:`compiling`). - -Include with conda-forge -======================== - -You can use pybind11 with conda packaging via `conda-forge -`_: - -.. code-block:: bash - - conda install -c conda-forge pybind11 - - -Include with vcpkg -================== -You can download and install pybind11 using the Microsoft `vcpkg -`_ dependency manager: - -.. code-block:: bash - - git clone https://github.com/Microsoft/vcpkg.git - cd vcpkg - ./bootstrap-vcpkg.sh - ./vcpkg integrate install - vcpkg install pybind11 - -The pybind11 port in vcpkg is kept up to date by Microsoft team members and -community contributors. If the version is out of date, please `create an issue -or pull request `_ on the vcpkg -repository. - -Global install with brew -======================== - -The brew package manager (Homebrew on macOS, or Linuxbrew on Linux) has a -`pybind11 package -`_. -To install: - -.. code-block:: bash - - brew install pybind11 - -.. We should list Conan, and possibly a few other C++ package managers (hunter, -.. perhaps). Conan has a very clean CMake integration that would be good to show. - -Other options -============= - -Other locations you can find pybind11 are `listed here -`_; these are maintained -by various packagers and the community. +.. _installing: + +Installing the library +###################### + +There are several ways to get the pybind11 source, which lives at +`pybind/pybind11 on GitHub `_. The pybind11 +developers recommend one of the first three ways listed here, submodule, PyPI, +or conda-forge, for obtaining pybind11. + +.. _include_as_a_submodule: + +Include as a submodule +====================== + +When you are working on a project in Git, you can use the pybind11 repository +as a submodule. From your git repository, use: + +.. code-block:: bash + + git submodule add -b stable ../../pybind/pybind11 extern/pybind11 + git submodule update --init + +This assumes you are placing your dependencies in ``extern/``, and that you are +using GitHub; if you are not using GitHub, use the full https or ssh URL +instead of the relative URL ``../../pybind/pybind11`` above. Some other servers +also require the ``.git`` extension (GitHub does not). + +From here, you can now include ``extern/pybind11/include``, or you can use +the various integration tools (see :ref:`compiling`) pybind11 provides directly +from the local folder. + +Include with PyPI +================= + +You can download the sources and CMake files as a Python package from PyPI +using Pip. Just use: + +.. code-block:: bash + + pip install pybind11 + +This will provide pybind11 in a standard Python package format. If you want +pybind11 available directly in your environment root, you can use: + +.. code-block:: bash + + pip install "pybind11[global]" + +This is not recommended if you are installing with your system Python, as it +will add files to ``/usr/local/include/pybind11`` and +``/usr/local/share/cmake/pybind11``, so unless that is what you want, it is +recommended only for use in virtual environments or your ``pyproject.toml`` +file (see :ref:`compiling`). + +Include with conda-forge +======================== + +You can use pybind11 with conda packaging via `conda-forge +`_: + +.. code-block:: bash + + conda install -c conda-forge pybind11 + + +Include with vcpkg +================== +You can download and install pybind11 using the Microsoft `vcpkg +`_ dependency manager: + +.. code-block:: bash + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + vcpkg install pybind11 + +The pybind11 port in vcpkg is kept up to date by Microsoft team members and +community contributors. If the version is out of date, please `create an issue +or pull request `_ on the vcpkg +repository. + +Global install with brew +======================== + +The brew package manager (Homebrew on macOS, or Linuxbrew on Linux) has a +`pybind11 package +`_. +To install: + +.. code-block:: bash + + brew install pybind11 + +.. We should list Conan, and possibly a few other C++ package managers (hunter, +.. perhaps). Conan has a very clean CMake integration that would be good to show. + +Other options +============= + +Other locations you can find pybind11 are `listed here +`_; these are maintained +by various packagers and the community. diff --git a/third_party/CityFlow/extern/pybind11/docs/limitations.rst b/third_party/CityFlow/extern/pybind11/docs/limitations.rst index def5ad659c98c6d7b04dc5af49f084e90dc65a76..645ea06001c010c7e96c7454e1d517861f211e55 100644 --- a/third_party/CityFlow/extern/pybind11/docs/limitations.rst +++ b/third_party/CityFlow/extern/pybind11/docs/limitations.rst @@ -1,72 +1,72 @@ -Limitations -########### - -Design choices -^^^^^^^^^^^^^^ - -pybind11 strives to be a general solution to binding generation, but it also has -certain limitations: - -- pybind11 casts away ``const``-ness in function arguments and return values. - This is in line with the Python language, which has no concept of ``const`` - values. This means that some additional care is needed to avoid bugs that - would be caught by the type checker in a traditional C++ program. - -- The NumPy interface ``pybind11::array`` greatly simplifies accessing - numerical data from C++ (and vice versa), but it's not a full-blown array - class like ``Eigen::Array`` or ``boost.multi_array``. ``Eigen`` objects are - directly supported, however, with ``pybind11/eigen.h``. - -Large but useful features could be implemented in pybind11 but would lead to a -significant increase in complexity. Pybind11 strives to be simple and compact. -Users who require large new features are encouraged to write an extension to -pybind11; see `pybind11_json `_ for an -example. - - -Known bugs -^^^^^^^^^^ - -These are issues that hopefully will one day be fixed, but currently are -unsolved. If you know how to help with one of these issues, contributions -are welcome! - -- Intel 20.2 is currently having an issue with the test suite. - `#2573 `_ - -- Debug mode Python does not support 1-5 tests in the test suite currently. - `#2422 `_ - -- PyPy3 7.3.1 and 7.3.2 have issues with several tests on 32-bit Windows. - -Known limitations -^^^^^^^^^^^^^^^^^ - -These are issues that are probably solvable, but have not been fixed yet. A -clean, well written patch would likely be accepted to solve them. - -- Type casters are not kept alive recursively. - `#2527 `_ - One consequence is that containers of ``char *`` are currently not supported. - `#2245 `_ - -- The ``cpptest`` does not run on Windows with Python 3.8 or newer, due to DLL - loader changes. User code that is correctly installed should not be affected. - `#2560 `_ - -Python 3.9.0 warning -^^^^^^^^^^^^^^^^^^^^ - -Combining older versions of pybind11 (< 2.6.0) with Python on exactly 3.9.0 -will trigger undefined behavior that typically manifests as crashes during -interpreter shutdown (but could also destroy your data. **You have been -warned**). - -This issue was `fixed in Python `_. -As a mitigation for this bug, pybind11 2.6.0 or newer includes a workaround -specifically when Python 3.9.0 is detected at runtime, leaking about 50 bytes -of memory when a callback function is garbage collected. For reference, the -pybind11 test suite has about 2,000 such callbacks, but only 49 are garbage -collected before the end-of-process. Wheels (even if built with Python 3.9.0) -will correctly avoid the leak when run in Python 3.9.1, and this does not -affect other 3.X versions. +Limitations +########### + +Design choices +^^^^^^^^^^^^^^ + +pybind11 strives to be a general solution to binding generation, but it also has +certain limitations: + +- pybind11 casts away ``const``-ness in function arguments and return values. + This is in line with the Python language, which has no concept of ``const`` + values. This means that some additional care is needed to avoid bugs that + would be caught by the type checker in a traditional C++ program. + +- The NumPy interface ``pybind11::array`` greatly simplifies accessing + numerical data from C++ (and vice versa), but it's not a full-blown array + class like ``Eigen::Array`` or ``boost.multi_array``. ``Eigen`` objects are + directly supported, however, with ``pybind11/eigen.h``. + +Large but useful features could be implemented in pybind11 but would lead to a +significant increase in complexity. Pybind11 strives to be simple and compact. +Users who require large new features are encouraged to write an extension to +pybind11; see `pybind11_json `_ for an +example. + + +Known bugs +^^^^^^^^^^ + +These are issues that hopefully will one day be fixed, but currently are +unsolved. If you know how to help with one of these issues, contributions +are welcome! + +- Intel 20.2 is currently having an issue with the test suite. + `#2573 `_ + +- Debug mode Python does not support 1-5 tests in the test suite currently. + `#2422 `_ + +- PyPy3 7.3.1 and 7.3.2 have issues with several tests on 32-bit Windows. + +Known limitations +^^^^^^^^^^^^^^^^^ + +These are issues that are probably solvable, but have not been fixed yet. A +clean, well written patch would likely be accepted to solve them. + +- Type casters are not kept alive recursively. + `#2527 `_ + One consequence is that containers of ``char *`` are currently not supported. + `#2245 `_ + +- The ``cpptest`` does not run on Windows with Python 3.8 or newer, due to DLL + loader changes. User code that is correctly installed should not be affected. + `#2560 `_ + +Python 3.9.0 warning +^^^^^^^^^^^^^^^^^^^^ + +Combining older versions of pybind11 (< 2.6.0) with Python on exactly 3.9.0 +will trigger undefined behavior that typically manifests as crashes during +interpreter shutdown (but could also destroy your data. **You have been +warned**). + +This issue was `fixed in Python `_. +As a mitigation for this bug, pybind11 2.6.0 or newer includes a workaround +specifically when Python 3.9.0 is detected at runtime, leaking about 50 bytes +of memory when a callback function is garbage collected. For reference, the +pybind11 test suite has about 2,000 such callbacks, but only 49 are garbage +collected before the end-of-process. Wheels (even if built with Python 3.9.0) +will correctly avoid the leak when run in Python 3.9.1, and this does not +affect other 3.X versions. diff --git a/third_party/CityFlow/extern/pybind11/docs/reference.rst b/third_party/CityFlow/extern/pybind11/docs/reference.rst index e64a03519da2461e5cea7109b569b72fbcd2bfac..a2803f2d7cdf1cf7f48358e654b1ef0a204e869e 100644 --- a/third_party/CityFlow/extern/pybind11/docs/reference.rst +++ b/third_party/CityFlow/extern/pybind11/docs/reference.rst @@ -1,130 +1,130 @@ -.. _reference: - -.. warning:: - - Please be advised that the reference documentation discussing pybind11 - internals is currently incomplete. Please refer to the previous sections - and the pybind11 header files for the nitty gritty details. - -Reference -######### - -.. _macros: - -Macros -====== - -.. doxygendefine:: PYBIND11_MODULE - -.. _core_types: - -Convenience classes for arbitrary Python types -============================================== - -Common member functions ------------------------ - -.. doxygenclass:: object_api - :members: - -Without reference counting --------------------------- - -.. doxygenclass:: handle - :members: - -With reference counting ------------------------ - -.. doxygenclass:: object - :members: - -.. doxygenfunction:: reinterpret_borrow - -.. doxygenfunction:: reinterpret_steal - -Convenience classes for specific Python types -============================================= - -.. doxygenclass:: module_ - :members: - -.. doxygengroup:: pytypes - :members: - -Convenience functions converting to Python types -================================================ - -.. doxygenfunction:: make_tuple(Args&&...) - -.. doxygenfunction:: make_iterator(Iterator, Sentinel, Extra &&...) -.. doxygenfunction:: make_iterator(Type &, Extra&&...) - -.. doxygenfunction:: make_key_iterator(Iterator, Sentinel, Extra &&...) -.. doxygenfunction:: make_key_iterator(Type &, Extra&&...) - -.. doxygenfunction:: make_value_iterator(Iterator, Sentinel, Extra &&...) -.. doxygenfunction:: make_value_iterator(Type &, Extra&&...) - -.. _extras: - -Passing extra arguments to ``def`` or ``class_`` -================================================ - -.. doxygengroup:: annotations - :members: - -Embedding the interpreter -========================= - -.. doxygendefine:: PYBIND11_EMBEDDED_MODULE - -.. doxygenfunction:: initialize_interpreter - -.. doxygenfunction:: finalize_interpreter - -.. doxygenclass:: scoped_interpreter - -Redirecting C++ streams -======================= - -.. doxygenclass:: scoped_ostream_redirect - -.. doxygenclass:: scoped_estream_redirect - -.. doxygenfunction:: add_ostream_redirect - -Python built-in functions -========================= - -.. doxygengroup:: python_builtins - :members: - -Inheritance -=========== - -See :doc:`/classes` and :doc:`/advanced/classes` for more detail. - -.. doxygendefine:: PYBIND11_OVERRIDE - -.. doxygendefine:: PYBIND11_OVERRIDE_PURE - -.. doxygendefine:: PYBIND11_OVERRIDE_NAME - -.. doxygendefine:: PYBIND11_OVERRIDE_PURE_NAME - -.. doxygenfunction:: get_override - -Exceptions -========== - -.. doxygenclass:: error_already_set - :members: - -.. doxygenclass:: builtin_exception - :members: - -Literals -======== - -.. doxygennamespace:: literals +.. _reference: + +.. warning:: + + Please be advised that the reference documentation discussing pybind11 + internals is currently incomplete. Please refer to the previous sections + and the pybind11 header files for the nitty gritty details. + +Reference +######### + +.. _macros: + +Macros +====== + +.. doxygendefine:: PYBIND11_MODULE + +.. _core_types: + +Convenience classes for arbitrary Python types +============================================== + +Common member functions +----------------------- + +.. doxygenclass:: object_api + :members: + +Without reference counting +-------------------------- + +.. doxygenclass:: handle + :members: + +With reference counting +----------------------- + +.. doxygenclass:: object + :members: + +.. doxygenfunction:: reinterpret_borrow + +.. doxygenfunction:: reinterpret_steal + +Convenience classes for specific Python types +============================================= + +.. doxygenclass:: module_ + :members: + +.. doxygengroup:: pytypes + :members: + +Convenience functions converting to Python types +================================================ + +.. doxygenfunction:: make_tuple(Args&&...) + +.. doxygenfunction:: make_iterator(Iterator, Sentinel, Extra &&...) +.. doxygenfunction:: make_iterator(Type &, Extra&&...) + +.. doxygenfunction:: make_key_iterator(Iterator, Sentinel, Extra &&...) +.. doxygenfunction:: make_key_iterator(Type &, Extra&&...) + +.. doxygenfunction:: make_value_iterator(Iterator, Sentinel, Extra &&...) +.. doxygenfunction:: make_value_iterator(Type &, Extra&&...) + +.. _extras: + +Passing extra arguments to ``def`` or ``class_`` +================================================ + +.. doxygengroup:: annotations + :members: + +Embedding the interpreter +========================= + +.. doxygendefine:: PYBIND11_EMBEDDED_MODULE + +.. doxygenfunction:: initialize_interpreter + +.. doxygenfunction:: finalize_interpreter + +.. doxygenclass:: scoped_interpreter + +Redirecting C++ streams +======================= + +.. doxygenclass:: scoped_ostream_redirect + +.. doxygenclass:: scoped_estream_redirect + +.. doxygenfunction:: add_ostream_redirect + +Python built-in functions +========================= + +.. doxygengroup:: python_builtins + :members: + +Inheritance +=========== + +See :doc:`/classes` and :doc:`/advanced/classes` for more detail. + +.. doxygendefine:: PYBIND11_OVERRIDE + +.. doxygendefine:: PYBIND11_OVERRIDE_PURE + +.. doxygendefine:: PYBIND11_OVERRIDE_NAME + +.. doxygendefine:: PYBIND11_OVERRIDE_PURE_NAME + +.. doxygenfunction:: get_override + +Exceptions +========== + +.. doxygenclass:: error_already_set + :members: + +.. doxygenclass:: builtin_exception + :members: + +Literals +======== + +.. doxygennamespace:: literals diff --git a/third_party/CityFlow/extern/pybind11/docs/release.rst b/third_party/CityFlow/extern/pybind11/docs/release.rst index 47b5717cad7c05aee1d2f0bbf83aa133c2ff3190..4f3c6b0138c1f99a42db1d7152377e66b5c66847 100644 --- a/third_party/CityFlow/extern/pybind11/docs/release.rst +++ b/third_party/CityFlow/extern/pybind11/docs/release.rst @@ -1,143 +1,143 @@ -On version numbers -^^^^^^^^^^^^^^^^^^ - -The two version numbers (C++ and Python) must match when combined (checked when -you build the PyPI package), and must be a valid `PEP 440 -`_ version when combined. - -For example: - -.. code-block:: C++ - - #define PYBIND11_VERSION_MAJOR X - #define PYBIND11_VERSION_MINOR Y - #define PYBIND11_VERSION_PATCH Z.dev1 - -For beta, ``PYBIND11_VERSION_PATCH`` should be ``Z.b1``. RC's can be ``Z.rc1``. -Always include the dot (even though PEP 440 allows it to be dropped). For a -final release, this must be a simple integer. There is also -``PYBIND11_VERSION_HEX`` just below that needs to be updated. - - -To release a new version of pybind11: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If you don't have nox, you should either use ``pipx run nox`` instead, or use -``pipx install nox`` or ``brew install nox`` (Unix). - -- Update the version number - - - Update ``PYBIND11_VERSION_MAJOR`` etc. in - ``include/pybind11/detail/common.h``. PATCH should be a simple integer. - - - Update ``PYBIND11_VERSION_HEX`` just below as well. - - - Update ``pybind11/_version.py`` (match above). - - - Run ``nox -s tests_packaging`` to ensure this was done correctly. - -- Ensure that all the information in ``setup.cfg`` is up-to-date, like - supported Python versions. - -- Add release date in ``docs/changelog.rst`` and integrate the output of - ``nox -s make_changelog``. - - - Note that the ``nox -s make_changelog`` command inspects - `needs changelog `_. - - - Manually clear the ``needs changelog`` labels using the GitHub web - interface (very easy: start by clicking the link above). - -- ``git add`` and ``git commit``, ``git push``. **Ensure CI passes**. (If it - fails due to a known flake issue, either ignore or restart CI.) - -- Add a release branch if this is a new MINOR version, or update the existing - release branch if it is a patch version - - - New branch: ``git checkout -b vX.Y``, ``git push -u origin vX.Y`` - - - Update branch: ``git checkout vX.Y``, ``git merge ``, ``git push`` - -- Update tags (optional; if you skip this, the GitHub release makes a - non-annotated tag for you) - - - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'`` - - - ``grep ^__version__ pybind11/_version.py`` - - - Last-minute consistency check: same as tag? - - - ``git push --tags`` - -- Update stable - - - ``git checkout stable`` - - - ``git merge -X theirs vX.Y.Z`` - - - ``git diff vX.Y.Z`` - - - Carefully review and reconcile any diffs. There should be none. - - - ``git push`` - -- Make a GitHub release (this shows up in the UI, sends new release - notifications to users watching releases, and also uploads PyPI packages). - (Note: if you do not use an existing tag, this creates a new lightweight tag - for you, so you could skip the above step.) - - - GUI method: Under `releases `_ - click "Draft a new release" on the far right, fill in the tag name - (if you didn't tag above, it will be made here), fill in a release name - like "Version X.Y.Z", and copy-and-paste the markdown-formatted (!) changelog - into the description. You can use ``cat docs/changelog.rst | pandoc -f rst -t gfm``, - then manually remove line breaks and strip links to PRs and issues, - e.g. to a bare ``#1234``, without the surrounding ``<...>_`` hyperlink markup. - Check "pre-release" if this is a beta/RC. - - - CLI method: with ``gh`` installed, run ``gh release create vX.Y.Z -t "Version X.Y.Z"`` - If this is a pre-release, add ``-p``. - -- Get back to work - - - Make sure you are on master, not somewhere else: ``git checkout master`` - - - Update version macros in ``include/pybind11/detail/common.h`` (set PATCH to - ``0.dev1`` and increment MINOR). - - - Update ``pybind11/_version.py`` to match. - - - Run ``nox -s tests_packaging`` to ensure this was done correctly. - - - If the release was a new MINOR version, add a new ``IN DEVELOPMENT`` - section in ``docs/changelog.rst``. - - - ``git add``, ``git commit``, ``git push`` - -If a version branch is updated, remember to set PATCH to ``1.dev1``. - -If you'd like to bump homebrew, run: - -.. code-block:: console - - brew bump-formula-pr --url https://github.com/pybind/pybind11/archive/vX.Y.Z.tar.gz - -Conda-forge should automatically make a PR in a few hours, and automatically -merge it if there are no issues. - - -Manual packaging -^^^^^^^^^^^^^^^^ - -If you need to manually upload releases, you can download the releases from -the job artifacts and upload them with twine. You can also make the files -locally (not recommended in general, as your local directory is more likely -to be "dirty" and SDists love picking up random unrelated/hidden files); -this is the procedure: - -.. code-block:: bash - - nox -s build - twine upload dist/* - -This makes SDists and wheels, and the final line uploads them. +On version numbers +^^^^^^^^^^^^^^^^^^ + +The two version numbers (C++ and Python) must match when combined (checked when +you build the PyPI package), and must be a valid `PEP 440 +`_ version when combined. + +For example: + +.. code-block:: C++ + + #define PYBIND11_VERSION_MAJOR X + #define PYBIND11_VERSION_MINOR Y + #define PYBIND11_VERSION_PATCH Z.dev1 + +For beta, ``PYBIND11_VERSION_PATCH`` should be ``Z.b1``. RC's can be ``Z.rc1``. +Always include the dot (even though PEP 440 allows it to be dropped). For a +final release, this must be a simple integer. There is also +``PYBIND11_VERSION_HEX`` just below that needs to be updated. + + +To release a new version of pybind11: +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you don't have nox, you should either use ``pipx run nox`` instead, or use +``pipx install nox`` or ``brew install nox`` (Unix). + +- Update the version number + + - Update ``PYBIND11_VERSION_MAJOR`` etc. in + ``include/pybind11/detail/common.h``. PATCH should be a simple integer. + + - Update ``PYBIND11_VERSION_HEX`` just below as well. + + - Update ``pybind11/_version.py`` (match above). + + - Run ``nox -s tests_packaging`` to ensure this was done correctly. + +- Ensure that all the information in ``setup.cfg`` is up-to-date, like + supported Python versions. + +- Add release date in ``docs/changelog.rst`` and integrate the output of + ``nox -s make_changelog``. + + - Note that the ``nox -s make_changelog`` command inspects + `needs changelog `_. + + - Manually clear the ``needs changelog`` labels using the GitHub web + interface (very easy: start by clicking the link above). + +- ``git add`` and ``git commit``, ``git push``. **Ensure CI passes**. (If it + fails due to a known flake issue, either ignore or restart CI.) + +- Add a release branch if this is a new MINOR version, or update the existing + release branch if it is a patch version + + - New branch: ``git checkout -b vX.Y``, ``git push -u origin vX.Y`` + + - Update branch: ``git checkout vX.Y``, ``git merge ``, ``git push`` + +- Update tags (optional; if you skip this, the GitHub release makes a + non-annotated tag for you) + + - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'`` + + - ``grep ^__version__ pybind11/_version.py`` + + - Last-minute consistency check: same as tag? + + - ``git push --tags`` + +- Update stable + + - ``git checkout stable`` + + - ``git merge -X theirs vX.Y.Z`` + + - ``git diff vX.Y.Z`` + + - Carefully review and reconcile any diffs. There should be none. + + - ``git push`` + +- Make a GitHub release (this shows up in the UI, sends new release + notifications to users watching releases, and also uploads PyPI packages). + (Note: if you do not use an existing tag, this creates a new lightweight tag + for you, so you could skip the above step.) + + - GUI method: Under `releases `_ + click "Draft a new release" on the far right, fill in the tag name + (if you didn't tag above, it will be made here), fill in a release name + like "Version X.Y.Z", and copy-and-paste the markdown-formatted (!) changelog + into the description. You can use ``cat docs/changelog.rst | pandoc -f rst -t gfm``, + then manually remove line breaks and strip links to PRs and issues, + e.g. to a bare ``#1234``, without the surrounding ``<...>_`` hyperlink markup. + Check "pre-release" if this is a beta/RC. + + - CLI method: with ``gh`` installed, run ``gh release create vX.Y.Z -t "Version X.Y.Z"`` + If this is a pre-release, add ``-p``. + +- Get back to work + + - Make sure you are on master, not somewhere else: ``git checkout master`` + + - Update version macros in ``include/pybind11/detail/common.h`` (set PATCH to + ``0.dev1`` and increment MINOR). + + - Update ``pybind11/_version.py`` to match. + + - Run ``nox -s tests_packaging`` to ensure this was done correctly. + + - If the release was a new MINOR version, add a new ``IN DEVELOPMENT`` + section in ``docs/changelog.rst``. + + - ``git add``, ``git commit``, ``git push`` + +If a version branch is updated, remember to set PATCH to ``1.dev1``. + +If you'd like to bump homebrew, run: + +.. code-block:: console + + brew bump-formula-pr --url https://github.com/pybind/pybind11/archive/vX.Y.Z.tar.gz + +Conda-forge should automatically make a PR in a few hours, and automatically +merge it if there are no issues. + + +Manual packaging +^^^^^^^^^^^^^^^^ + +If you need to manually upload releases, you can download the releases from +the job artifacts and upload them with twine. You can also make the files +locally (not recommended in general, as your local directory is more likely +to be "dirty" and SDists love picking up random unrelated/hidden files); +this is the procedure: + +.. code-block:: bash + + nox -s build + twine upload dist/* + +This makes SDists and wheels, and the final line uploads them. diff --git a/third_party/CityFlow/extern/pybind11/docs/requirements.txt b/third_party/CityFlow/extern/pybind11/docs/requirements.txt index d2a9ae1645be110a5db5405d454176082d3f9296..119773409c89ad1f8bc91b28cba6ab155468baec 100644 --- a/third_party/CityFlow/extern/pybind11/docs/requirements.txt +++ b/third_party/CityFlow/extern/pybind11/docs/requirements.txt @@ -1,6 +1,6 @@ -breathe==4.34.0 -furo==2022.6.21 -sphinx==5.0.2 -sphinx-copybutton==0.5.0 -sphinxcontrib-moderncmakedomain==3.21.4 -sphinxcontrib-svg2pdfconverter==1.2.0 +breathe==4.34.0 +furo==2022.6.21 +sphinx==5.0.2 +sphinx-copybutton==0.5.0 +sphinxcontrib-moderncmakedomain==3.21.4 +sphinxcontrib-svg2pdfconverter==1.2.0 diff --git a/third_party/CityFlow/extern/pybind11/docs/upgrade.rst b/third_party/CityFlow/extern/pybind11/docs/upgrade.rst index 17c26aaa9389ec42a1a49aef5901fec743ad5c95..1c07ab252461ff4ac77d13ee6aa6e02c06d85c02 100644 --- a/third_party/CityFlow/extern/pybind11/docs/upgrade.rst +++ b/third_party/CityFlow/extern/pybind11/docs/upgrade.rst @@ -1,594 +1,594 @@ -Upgrade guide -############# - -This is a companion guide to the :doc:`changelog`. While the changelog briefly -lists all of the new features, improvements and bug fixes, this upgrade guide -focuses only the subset which directly impacts your experience when upgrading -to a new version. But it goes into more detail. This includes things like -deprecated APIs and their replacements, build system changes, general code -modernization and other useful information. - -.. _upgrade-guide-2.12: - -v2.12 -===== - -NumPy support has been upgraded to support the 2.x series too. The two relevant -changes are that: - -* ``dtype.flags()`` is now a ``uint64`` and ``dtype.alignment()`` an - ``ssize_t`` (and NumPy may return an larger than integer value for - ``itemsize()`` in NumPy 2.x). - -* The long deprecated NumPy function ``PyArray_GetArrayParamsFromObject`` - function is not available anymore. - -Due to NumPy changes, you may experience difficulties updating to NumPy 2. -Please see the [NumPy 2 migration guide](https://numpy.org/devdocs/numpy_2_0_migration_guide.html) for details. -For example, a more direct change could be that the default integer ``"int_"`` -(and ``"uint"``) is now ``ssize_t`` and not ``long`` (affects 64bit windows). - -If you want to only support NumPy 1.x for now and are having problems due to -the two internal changes listed above, you can define -``PYBIND11_NUMPY_1_ONLY`` to disable the new support for now. Make sure you -define this on all pybind11 compile units, since it could be a source of ODR -violations if used inconsistently. This option will be removed in the future, -so adapting your code is highly recommended. - - -.. _upgrade-guide-2.11: - -v2.11 -===== - -* The minimum version of CMake is now 3.5. A future version will likely move to - requiring something like CMake 3.15. Note that CMake 3.27 is removing the - long-deprecated support for ``FindPythonInterp`` if you set 3.27 as the - minimum or maximum supported version. To prepare for that future, CMake 3.15+ - using ``FindPython`` or setting ``PYBIND11_FINDPYTHON`` is highly recommended, - otherwise pybind11 will automatically switch to using ``FindPython`` if - ``FindPythonInterp`` is not available. - - -.. _upgrade-guide-2.9: - -v2.9 -==== - -* Any usage of the recently added ``py::make_simple_namespace`` should be - converted to using ``py::module_::import("types").attr("SimpleNamespace")`` - instead. - -* The use of ``_`` in custom type casters can now be replaced with the more - readable ``const_name`` instead. The old ``_`` shortcut has been retained - unless it is being used as a macro (like for gettext). - - -.. _upgrade-guide-2.7: - -v2.7 -==== - -*Before* v2.7, ``py::str`` can hold ``PyUnicodeObject`` or ``PyBytesObject``, -and ``py::isinstance()`` is ``true`` for both ``py::str`` and -``py::bytes``. Starting with v2.7, ``py::str`` exclusively holds -``PyUnicodeObject`` (`#2409 `_), -and ``py::isinstance()`` is ``true`` only for ``py::str``. To help in -the transition of user code, the ``PYBIND11_STR_LEGACY_PERMISSIVE`` macro -is provided as an escape hatch to go back to the legacy behavior. This macro -will be removed in future releases. Two types of required fixes are expected -to be common: - -* Accidental use of ``py::str`` instead of ``py::bytes``, masked by the legacy - behavior. These are probably very easy to fix, by changing from - ``py::str`` to ``py::bytes``. - -* Reliance on py::isinstance(obj) being ``true`` for - ``py::bytes``. This is likely to be easy to fix in most cases by adding - ``|| py::isinstance(obj)``, but a fix may be more involved, e.g. if - ``py::isinstance`` appears in a template. Such situations will require - careful review and custom fixes. - - -.. _upgrade-guide-2.6: - -v2.6 -==== - -Usage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should -be replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the -old macros may be deprecated and removed. - -``py::module`` has been renamed ``py::module_``, but a backward compatible -typedef has been included. This change was to avoid a language change in C++20 -that requires unqualified ``module`` not be placed at the start of a logical -line. Qualified usage is unaffected and the typedef will remain unless the -C++ language rules change again. - -The public constructors of ``py::module_`` have been deprecated. Use -``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead. - -An error is now thrown when ``__init__`` is forgotten on subclasses. This was -incorrect before, but was not checked. Add a call to ``__init__`` if it is -missing. - -A ``py::type_error`` is now thrown when casting to a subclass (like -``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid -conversion instead. - -The undocumented ``h.get_type()`` method has been deprecated and replaced by -``py::type::of(h)``. - -Enums now have a ``__str__`` method pre-defined; if you want to override it, -the simplest fix is to add the new ``py::prepend()`` tag when defining -``"__str__"``. - -If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to -``None``, as in normal CPython. You should add ``__hash__`` if you intended the -class to be hashable, possibly using the new ``py::hash`` shortcut. - -The constructors for ``py::array`` now always take signed integers for size, -for consistency. This may lead to compiler warnings on some systems. Cast to -``py::ssize_t`` instead of ``std::size_t``. - -The ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a -standalone package, `pybind11-mkdoc`_. If you were using those tools, please -use them via a pip install from the new location. - -The ``pybind11`` package on PyPI no longer fills the wheel "headers" slot - if -you were using the headers from this slot, they are available by requesting the -``global`` extra, that is, ``pip install "pybind11[global]"``. (Most users will -be unaffected, as the ``pybind11/include`` location is reported by ``python -m -pybind11 --includes`` and ``pybind11.get_include()`` is still correct and has -not changed since 2.5). - -.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc - -CMake support: --------------- - -The minimum required version of CMake is now 3.4. Several details of the CMake -support have been deprecated; warnings will be shown if you need to change -something. The changes are: - -* ``PYBIND11_CPP_STANDARD=`` is deprecated, please use - ``CMAKE_CXX_STANDARD=`` instead, or any other valid CMake CXX or CUDA - standard selection method, like ``target_compile_features``. - -* If you do not request a standard, pybind11 targets will compile with the - compiler default, but not less than C++11, instead of forcing C++14 always. - If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING "")`` - instead. - -* Direct ``pybind11::module`` usage should always be accompanied by at least - ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to - manually force this compiler flag (but not correctly on all compilers or with - CUDA). - -* ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing; - linking now behaves like other imported libraries consistently in both - config and submodule mode, and behaves like a ``SYSTEM`` library by - default. - -* If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``, - ``virtualenv``, and ``conda``) are prioritized over the standard search - (similar to the new FindPython mode). - -In addition, the following changes may be of interest: - -* ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by - ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or - ``pybind11::thin_lto``. - -* Using ``find_package(Python COMPONENTS Interpreter Development)`` before - pybind11 will cause pybind11 to use the new Python mechanisms instead of its - own custom search, based on a patched version of classic ``FindPythonInterp`` - / ``FindPythonLibs``. In the future, this may become the default. A recent - (3.15+ or 3.18.2+) version of CMake is recommended. - - - -v2.5 -==== - -The Python package now includes the headers as data in the package itself, as -well as in the "headers" wheel slot. ``pybind11 --includes`` and -``pybind11.get_include()`` report the new location, which is always correct -regardless of how pybind11 was installed, making the old ``user=`` argument -meaningless. If you are not using the function to get the location already, you -are encouraged to switch to the package location. - - -v2.2 -==== - -Deprecation of the ``PYBIND11_PLUGIN`` macro --------------------------------------------- - -``PYBIND11_MODULE`` is now the preferred way to create module entry points. -The old macro emits a compile-time deprecation warning. - -.. code-block:: cpp - - // old - PYBIND11_PLUGIN(example) { - py::module m("example", "documentation string"); - - m.def("add", [](int a, int b) { return a + b; }); - - return m.ptr(); - } - - // new - PYBIND11_MODULE(example, m) { - m.doc() = "documentation string"; // optional - - m.def("add", [](int a, int b) { return a + b; }); - } - - -New API for defining custom constructors and pickling functions ---------------------------------------------------------------- - -The old placement-new custom constructors have been deprecated. The new approach -uses ``py::init()`` and factory functions to greatly improve type safety. - -Placement-new can be called accidentally with an incompatible type (without any -compiler errors or warnings), or it can initialize the same object multiple times -if not careful with the Python-side ``__init__`` calls. The new-style custom -constructors prevent such mistakes. See :ref:`custom_constructors` for details. - -.. code-block:: cpp - - // old -- deprecated (runtime warning shown only in debug mode) - py::class(m, "Foo") - .def("__init__", [](Foo &self, ...) { - new (&self) Foo(...); // uses placement-new - }); - - // new - py::class(m, "Foo") - .def(py::init([](...) { // Note: no `self` argument - return new Foo(...); // return by raw pointer - // or: return std::make_unique(...); // return by holder - // or: return Foo(...); // return by value (move constructor) - })); - -Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred -way to get and set object state. See :ref:`pickling` for details. - -.. code-block:: cpp - - // old -- deprecated (runtime warning shown only in debug mode) - py::class(m, "Foo") - ... - .def("__getstate__", [](const Foo &self) { - return py::make_tuple(self.value1(), self.value2(), ...); - }) - .def("__setstate__", [](Foo &self, py::tuple t) { - new (&self) Foo(t[0].cast(), ...); - }); - - // new - py::class(m, "Foo") - ... - .def(py::pickle( - [](const Foo &self) { // __getstate__ - return py::make_tuple(self.value1(), self.value2(), ...); // unchanged - }, - [](py::tuple t) { // __setstate__, note: no `self` argument - return new Foo(t[0].cast(), ...); - // or: return std::make_unique(...); // return by holder - // or: return Foo(...); // return by value (move constructor) - } - )); - -For both the constructors and pickling, warnings are shown at module -initialization time (on import, not when the functions are called). -They're only visible when compiled in debug mode. Sample warning: - -.. code-block:: none - - pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' - which has been deprecated. See the upgrade guide in pybind11's docs. - - -Stricter enforcement of hidden symbol visibility for pybind11 modules ---------------------------------------------------------------------- - -pybind11 now tries to actively enforce hidden symbol visibility for modules. -If you're using either one of pybind11's :doc:`CMake or Python build systems -` (the two example repositories) and you haven't been exporting any -symbols, there's nothing to be concerned about. All the changes have been done -transparently in the background. If you were building manually or relied on -specific default visibility, read on. - -Setting default symbol visibility to *hidden* has always been recommended for -pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol -visibility (in conjunction with the ``strip`` utility) yields much smaller -module binaries. `CPython's extension docs`_ also recommend hiding symbols -by default, with the goal of avoiding symbol name clashes between modules. -Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring -all symbols inside the ``pybind11`` namespace as hidden and (2) by including -the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension -modules, not for embedding the interpreter). - -.. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module - -The namespace-scope hidden visibility is done automatically in pybind11's -headers and it's generally transparent to users. It ensures that: - -* Modules compiled with different pybind11 versions don't clash with each other. - -* Some new features, like ``py::module_local`` bindings, can work as intended. - -The ``-fvisibility=hidden`` flag applies the same visibility to user bindings -outside of the ``pybind11`` namespace. It's now set automatic by pybind11's -CMake and Python build systems, but this needs to be done manually by users -of other build systems. Adding this flag: - -* Minimizes the chances of symbol conflicts between modules. E.g. if two - unrelated modules were statically linked to different (ABI-incompatible) - versions of the same third-party library, a symbol clash would be likely - (and would end with unpredictable results). - -* Produces smaller binaries on Linux and macOS, as pointed out previously. - -Within pybind11's CMake build system, ``pybind11_add_module`` has always been -setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's -being applied unconditionally, even in debug mode and it can no longer be opted -out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also -adds this flag to its interface. The ``pybind11::embed`` target is unchanged. - -The most significant change here is for the ``pybind11::module`` target. If you -were previously relying on default visibility, i.e. if your Python module was -doubling as a shared library with dependents, you'll need to either export -symbols manually (recommended for cross-platform libraries) or factor out the -shared library (and have the Python module link to it like the other -dependents). As a temporary workaround, you can also restore default visibility -using the CMake code below, but this is not recommended in the long run: - -.. code-block:: cmake - - target_link_libraries(mymodule PRIVATE pybind11::module) - - add_library(restore_default_visibility INTERFACE) - target_compile_options(restore_default_visibility INTERFACE -fvisibility=default) - target_link_libraries(mymodule PRIVATE restore_default_visibility) - - -Local STL container bindings ----------------------------- - -Previous pybind11 versions could only bind types globally -- all pybind11 -modules, even unrelated ones, would have access to the same exported types. -However, this would also result in a conflict if two modules exported the -same C++ type, which is especially problematic for very common types, e.g. -``std::vector``. :ref:`module_local` were added to resolve this (see -that section for a complete usage guide). - -``py::class_`` still defaults to global bindings (because these types are -usually unique across modules), however in order to avoid clashes of opaque -types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers -as ``py::module_local`` if their elements are: builtins (``int``, ``float``, -etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For -example, this change allows multiple modules to bind ``std::vector`` -without causing conflicts. See :ref:`stl_bind` for more details. - -When upgrading to this version, if you have multiple modules which depend on -a single global binding of an STL container, note that all modules can still -accept foreign ``py::module_local`` types in the direction of Python-to-C++. -The locality only affects the C++-to-Python direction. If this is needed in -multiple modules, you'll need to either: - -* Add a copy of the same STL binding to all of the modules which need it. - -* Restore the global status of that single binding by marking it - ``py::module_local(false)``. - -The latter is an easy workaround, but in the long run it would be best to -localize all common type bindings in order to avoid conflicts with -third-party modules. - - -Negative strides for Python buffer objects and numpy arrays ------------------------------------------------------------ - -Support for negative strides required changing the integer type from unsigned -to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you -have compiler warnings enabled, you may notice some new conversion warnings -after upgrading. These can be resolved using ``static_cast``. - - -Deprecation of some ``py::object`` APIs ---------------------------------------- - -To compare ``py::object`` instances by pointer, you should now use -``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python. -Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but -that could be confusing and is now deprecated (so that it can eventually -be replaced with proper rich object comparison in a future release). - -For classes which inherit from ``py::object``, ``borrowed`` and ``stolen`` -were previously available as protected constructor tags. Now the types -should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}`` -(`#771 `_). - - -Stricter compile-time error checking ------------------------------------- - -Some error checks have been moved from run time to compile time. Notably, -automatic conversion of ``std::shared_ptr`` is not possible when ``T`` is -not directly registered with ``py::class_`` (e.g. ``std::shared_ptr`` -or ``std::shared_ptr>`` are not automatically convertible). -Attempting to bind a function with such arguments now results in a compile-time -error instead of waiting to fail at run time. - -``py::init<...>()`` constructor definitions are also stricter and now prevent -bindings which could cause unexpected behavior: - -.. code-block:: cpp - - struct Example { - Example(int &); - }; - - py::class_(m, "Example") - .def(py::init()); // OK, exact match - // .def(py::init()); // compile-time error, mismatch - -A non-``const`` lvalue reference is not allowed to bind to an rvalue. However, -note that a constructor taking ``const T &`` can still be registered using -``py::init()`` because a ``const`` lvalue reference can bind to an rvalue. - -v2.1 -==== - -Minimum compiler versions are enforced at compile time ------------------------------------------------------- - -The minimums also apply to v2.0 but the check is now explicit and a compile-time -error is raised if the compiler does not meet the requirements: - -* GCC >= 4.8 -* clang >= 3.3 (appleclang >= 5.0) -* MSVC >= 2015u3 -* Intel C++ >= 15.0 - - -The ``py::metaclass`` attribute is not required for static properties ---------------------------------------------------------------------- - -Binding classes with static properties is now possible by default. The -zero-parameter version of ``py::metaclass()`` is deprecated. However, a new -one-parameter ``py::metaclass(python_type)`` version was added for rare -cases when a custom metaclass is needed to override pybind11's default. - -.. code-block:: cpp - - // old -- emits a deprecation warning - py::class_(m, "Foo", py::metaclass()) - .def_property_readonly_static("foo", ...); - - // new -- static properties work without the attribute - py::class_(m, "Foo") - .def_property_readonly_static("foo", ...); - - // new -- advanced feature, override pybind11's default metaclass - py::class_(m, "Bar", py::metaclass(custom_python_type)) - ... - - -v2.0 -==== - -Breaking changes in ``py::class_`` ----------------------------------- - -These changes were necessary to make type definitions in pybind11 -future-proof, to support PyPy via its ``cpyext`` mechanism (`#527 -`_), and to improve efficiency -(`rev. 86d825 `_). - -1. Declarations of types that provide access via the buffer protocol must - now include the ``py::buffer_protocol()`` annotation as an argument to - the ``py::class_`` constructor. - - .. code-block:: cpp - - py::class_("Matrix", py::buffer_protocol()) - .def(py::init<...>()) - .def_buffer(...); - -2. Classes which include static properties (e.g. ``def_readwrite_static()``) - must now include the ``py::metaclass()`` attribute. Note: this requirement - has since been removed in v2.1. If you're upgrading from 1.x, it's - recommended to skip directly to v2.1 or newer. - -3. This version of pybind11 uses a redesigned mechanism for instantiating - trampoline classes that are used to override virtual methods from within - Python. This led to the following user-visible syntax change: - - .. code-block:: cpp - - // old v1.x syntax - py::class_("MyClass") - .alias() - ... - - // new v2.x syntax - py::class_("MyClass") - ... - - Importantly, both the original and the trampoline class are now specified - as arguments to the ``py::class_`` template, and the ``alias<..>()`` call - is gone. The new scheme has zero overhead in cases when Python doesn't - override any functions of the underlying C++ class. - `rev. 86d825 `_. - - The class type must be the first template argument given to ``py::class_`` - while the trampoline can be mixed in arbitrary order with other arguments - (see the following section). - - -Deprecation of the ``py::base()`` attribute ----------------------------------------------- - -``py::base()`` was deprecated in favor of specifying ``T`` as a template -argument to ``py::class_``. This new syntax also supports multiple inheritance. -Note that, while the type being exported must be the first argument in the -``py::class_`` template, the order of the following types (bases, -holder and/or trampoline) is not important. - -.. code-block:: cpp - - // old v1.x - py::class_("Derived", py::base()); - - // new v2.x - py::class_("Derived"); - - // new -- multiple inheritance - py::class_("Derived"); - - // new -- apart from `Derived` the argument order can be arbitrary - py::class_("Derived"); - - -Out-of-the-box support for ``std::shared_ptr`` ----------------------------------------------- - -The relevant type caster is now built in, so it's no longer necessary to -include a declaration of the form: - -.. code-block:: cpp - - PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr) - -Continuing to do so won't cause an error or even a deprecation warning, -but it's completely redundant. - - -Deprecation of a few ``py::object`` APIs ----------------------------------------- - -All of the old-style calls emit deprecation warnings. - -+---------------------------------------+---------------------------------------------+ -| Old syntax | New syntax | -+=======================================+=============================================+ -| ``obj.call(args...)`` | ``obj(args...)`` | -+---------------------------------------+---------------------------------------------+ -| ``obj.str()`` | ``py::str(obj)`` | -+---------------------------------------+---------------------------------------------+ -| ``auto l = py::list(obj); l.check()`` | ``py::isinstance(obj)`` | -+---------------------------------------+---------------------------------------------+ -| ``py::object(ptr, true)`` | ``py::reinterpret_borrow(ptr)`` | -+---------------------------------------+---------------------------------------------+ -| ``py::object(ptr, false)`` | ``py::reinterpret_steal(ptr)`` | -+---------------------------------------+---------------------------------------------+ -| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` | -+---------------------------------------+---------------------------------------------+ -| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` | -+---------------------------------------+---------------------------------------------+ +Upgrade guide +############# + +This is a companion guide to the :doc:`changelog`. While the changelog briefly +lists all of the new features, improvements and bug fixes, this upgrade guide +focuses only the subset which directly impacts your experience when upgrading +to a new version. But it goes into more detail. This includes things like +deprecated APIs and their replacements, build system changes, general code +modernization and other useful information. + +.. _upgrade-guide-2.12: + +v2.12 +===== + +NumPy support has been upgraded to support the 2.x series too. The two relevant +changes are that: + +* ``dtype.flags()`` is now a ``uint64`` and ``dtype.alignment()`` an + ``ssize_t`` (and NumPy may return an larger than integer value for + ``itemsize()`` in NumPy 2.x). + +* The long deprecated NumPy function ``PyArray_GetArrayParamsFromObject`` + function is not available anymore. + +Due to NumPy changes, you may experience difficulties updating to NumPy 2. +Please see the [NumPy 2 migration guide](https://numpy.org/devdocs/numpy_2_0_migration_guide.html) for details. +For example, a more direct change could be that the default integer ``"int_"`` +(and ``"uint"``) is now ``ssize_t`` and not ``long`` (affects 64bit windows). + +If you want to only support NumPy 1.x for now and are having problems due to +the two internal changes listed above, you can define +``PYBIND11_NUMPY_1_ONLY`` to disable the new support for now. Make sure you +define this on all pybind11 compile units, since it could be a source of ODR +violations if used inconsistently. This option will be removed in the future, +so adapting your code is highly recommended. + + +.. _upgrade-guide-2.11: + +v2.11 +===== + +* The minimum version of CMake is now 3.5. A future version will likely move to + requiring something like CMake 3.15. Note that CMake 3.27 is removing the + long-deprecated support for ``FindPythonInterp`` if you set 3.27 as the + minimum or maximum supported version. To prepare for that future, CMake 3.15+ + using ``FindPython`` or setting ``PYBIND11_FINDPYTHON`` is highly recommended, + otherwise pybind11 will automatically switch to using ``FindPython`` if + ``FindPythonInterp`` is not available. + + +.. _upgrade-guide-2.9: + +v2.9 +==== + +* Any usage of the recently added ``py::make_simple_namespace`` should be + converted to using ``py::module_::import("types").attr("SimpleNamespace")`` + instead. + +* The use of ``_`` in custom type casters can now be replaced with the more + readable ``const_name`` instead. The old ``_`` shortcut has been retained + unless it is being used as a macro (like for gettext). + + +.. _upgrade-guide-2.7: + +v2.7 +==== + +*Before* v2.7, ``py::str`` can hold ``PyUnicodeObject`` or ``PyBytesObject``, +and ``py::isinstance()`` is ``true`` for both ``py::str`` and +``py::bytes``. Starting with v2.7, ``py::str`` exclusively holds +``PyUnicodeObject`` (`#2409 `_), +and ``py::isinstance()`` is ``true`` only for ``py::str``. To help in +the transition of user code, the ``PYBIND11_STR_LEGACY_PERMISSIVE`` macro +is provided as an escape hatch to go back to the legacy behavior. This macro +will be removed in future releases. Two types of required fixes are expected +to be common: + +* Accidental use of ``py::str`` instead of ``py::bytes``, masked by the legacy + behavior. These are probably very easy to fix, by changing from + ``py::str`` to ``py::bytes``. + +* Reliance on py::isinstance(obj) being ``true`` for + ``py::bytes``. This is likely to be easy to fix in most cases by adding + ``|| py::isinstance(obj)``, but a fix may be more involved, e.g. if + ``py::isinstance`` appears in a template. Such situations will require + careful review and custom fixes. + + +.. _upgrade-guide-2.6: + +v2.6 +==== + +Usage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should +be replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the +old macros may be deprecated and removed. + +``py::module`` has been renamed ``py::module_``, but a backward compatible +typedef has been included. This change was to avoid a language change in C++20 +that requires unqualified ``module`` not be placed at the start of a logical +line. Qualified usage is unaffected and the typedef will remain unless the +C++ language rules change again. + +The public constructors of ``py::module_`` have been deprecated. Use +``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead. + +An error is now thrown when ``__init__`` is forgotten on subclasses. This was +incorrect before, but was not checked. Add a call to ``__init__`` if it is +missing. + +A ``py::type_error`` is now thrown when casting to a subclass (like +``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid +conversion instead. + +The undocumented ``h.get_type()`` method has been deprecated and replaced by +``py::type::of(h)``. + +Enums now have a ``__str__`` method pre-defined; if you want to override it, +the simplest fix is to add the new ``py::prepend()`` tag when defining +``"__str__"``. + +If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to +``None``, as in normal CPython. You should add ``__hash__`` if you intended the +class to be hashable, possibly using the new ``py::hash`` shortcut. + +The constructors for ``py::array`` now always take signed integers for size, +for consistency. This may lead to compiler warnings on some systems. Cast to +``py::ssize_t`` instead of ``std::size_t``. + +The ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a +standalone package, `pybind11-mkdoc`_. If you were using those tools, please +use them via a pip install from the new location. + +The ``pybind11`` package on PyPI no longer fills the wheel "headers" slot - if +you were using the headers from this slot, they are available by requesting the +``global`` extra, that is, ``pip install "pybind11[global]"``. (Most users will +be unaffected, as the ``pybind11/include`` location is reported by ``python -m +pybind11 --includes`` and ``pybind11.get_include()`` is still correct and has +not changed since 2.5). + +.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc + +CMake support: +-------------- + +The minimum required version of CMake is now 3.4. Several details of the CMake +support have been deprecated; warnings will be shown if you need to change +something. The changes are: + +* ``PYBIND11_CPP_STANDARD=`` is deprecated, please use + ``CMAKE_CXX_STANDARD=`` instead, or any other valid CMake CXX or CUDA + standard selection method, like ``target_compile_features``. + +* If you do not request a standard, pybind11 targets will compile with the + compiler default, but not less than C++11, instead of forcing C++14 always. + If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING "")`` + instead. + +* Direct ``pybind11::module`` usage should always be accompanied by at least + ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to + manually force this compiler flag (but not correctly on all compilers or with + CUDA). + +* ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing; + linking now behaves like other imported libraries consistently in both + config and submodule mode, and behaves like a ``SYSTEM`` library by + default. + +* If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``, + ``virtualenv``, and ``conda``) are prioritized over the standard search + (similar to the new FindPython mode). + +In addition, the following changes may be of interest: + +* ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by + ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or + ``pybind11::thin_lto``. + +* Using ``find_package(Python COMPONENTS Interpreter Development)`` before + pybind11 will cause pybind11 to use the new Python mechanisms instead of its + own custom search, based on a patched version of classic ``FindPythonInterp`` + / ``FindPythonLibs``. In the future, this may become the default. A recent + (3.15+ or 3.18.2+) version of CMake is recommended. + + + +v2.5 +==== + +The Python package now includes the headers as data in the package itself, as +well as in the "headers" wheel slot. ``pybind11 --includes`` and +``pybind11.get_include()`` report the new location, which is always correct +regardless of how pybind11 was installed, making the old ``user=`` argument +meaningless. If you are not using the function to get the location already, you +are encouraged to switch to the package location. + + +v2.2 +==== + +Deprecation of the ``PYBIND11_PLUGIN`` macro +-------------------------------------------- + +``PYBIND11_MODULE`` is now the preferred way to create module entry points. +The old macro emits a compile-time deprecation warning. + +.. code-block:: cpp + + // old + PYBIND11_PLUGIN(example) { + py::module m("example", "documentation string"); + + m.def("add", [](int a, int b) { return a + b; }); + + return m.ptr(); + } + + // new + PYBIND11_MODULE(example, m) { + m.doc() = "documentation string"; // optional + + m.def("add", [](int a, int b) { return a + b; }); + } + + +New API for defining custom constructors and pickling functions +--------------------------------------------------------------- + +The old placement-new custom constructors have been deprecated. The new approach +uses ``py::init()`` and factory functions to greatly improve type safety. + +Placement-new can be called accidentally with an incompatible type (without any +compiler errors or warnings), or it can initialize the same object multiple times +if not careful with the Python-side ``__init__`` calls. The new-style custom +constructors prevent such mistakes. See :ref:`custom_constructors` for details. + +.. code-block:: cpp + + // old -- deprecated (runtime warning shown only in debug mode) + py::class(m, "Foo") + .def("__init__", [](Foo &self, ...) { + new (&self) Foo(...); // uses placement-new + }); + + // new + py::class(m, "Foo") + .def(py::init([](...) { // Note: no `self` argument + return new Foo(...); // return by raw pointer + // or: return std::make_unique(...); // return by holder + // or: return Foo(...); // return by value (move constructor) + })); + +Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred +way to get and set object state. See :ref:`pickling` for details. + +.. code-block:: cpp + + // old -- deprecated (runtime warning shown only in debug mode) + py::class(m, "Foo") + ... + .def("__getstate__", [](const Foo &self) { + return py::make_tuple(self.value1(), self.value2(), ...); + }) + .def("__setstate__", [](Foo &self, py::tuple t) { + new (&self) Foo(t[0].cast(), ...); + }); + + // new + py::class(m, "Foo") + ... + .def(py::pickle( + [](const Foo &self) { // __getstate__ + return py::make_tuple(self.value1(), self.value2(), ...); // unchanged + }, + [](py::tuple t) { // __setstate__, note: no `self` argument + return new Foo(t[0].cast(), ...); + // or: return std::make_unique(...); // return by holder + // or: return Foo(...); // return by value (move constructor) + } + )); + +For both the constructors and pickling, warnings are shown at module +initialization time (on import, not when the functions are called). +They're only visible when compiled in debug mode. Sample warning: + +.. code-block:: none + + pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' + which has been deprecated. See the upgrade guide in pybind11's docs. + + +Stricter enforcement of hidden symbol visibility for pybind11 modules +--------------------------------------------------------------------- + +pybind11 now tries to actively enforce hidden symbol visibility for modules. +If you're using either one of pybind11's :doc:`CMake or Python build systems +` (the two example repositories) and you haven't been exporting any +symbols, there's nothing to be concerned about. All the changes have been done +transparently in the background. If you were building manually or relied on +specific default visibility, read on. + +Setting default symbol visibility to *hidden* has always been recommended for +pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol +visibility (in conjunction with the ``strip`` utility) yields much smaller +module binaries. `CPython's extension docs`_ also recommend hiding symbols +by default, with the goal of avoiding symbol name clashes between modules. +Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring +all symbols inside the ``pybind11`` namespace as hidden and (2) by including +the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension +modules, not for embedding the interpreter). + +.. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module + +The namespace-scope hidden visibility is done automatically in pybind11's +headers and it's generally transparent to users. It ensures that: + +* Modules compiled with different pybind11 versions don't clash with each other. + +* Some new features, like ``py::module_local`` bindings, can work as intended. + +The ``-fvisibility=hidden`` flag applies the same visibility to user bindings +outside of the ``pybind11`` namespace. It's now set automatic by pybind11's +CMake and Python build systems, but this needs to be done manually by users +of other build systems. Adding this flag: + +* Minimizes the chances of symbol conflicts between modules. E.g. if two + unrelated modules were statically linked to different (ABI-incompatible) + versions of the same third-party library, a symbol clash would be likely + (and would end with unpredictable results). + +* Produces smaller binaries on Linux and macOS, as pointed out previously. + +Within pybind11's CMake build system, ``pybind11_add_module`` has always been +setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's +being applied unconditionally, even in debug mode and it can no longer be opted +out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also +adds this flag to its interface. The ``pybind11::embed`` target is unchanged. + +The most significant change here is for the ``pybind11::module`` target. If you +were previously relying on default visibility, i.e. if your Python module was +doubling as a shared library with dependents, you'll need to either export +symbols manually (recommended for cross-platform libraries) or factor out the +shared library (and have the Python module link to it like the other +dependents). As a temporary workaround, you can also restore default visibility +using the CMake code below, but this is not recommended in the long run: + +.. code-block:: cmake + + target_link_libraries(mymodule PRIVATE pybind11::module) + + add_library(restore_default_visibility INTERFACE) + target_compile_options(restore_default_visibility INTERFACE -fvisibility=default) + target_link_libraries(mymodule PRIVATE restore_default_visibility) + + +Local STL container bindings +---------------------------- + +Previous pybind11 versions could only bind types globally -- all pybind11 +modules, even unrelated ones, would have access to the same exported types. +However, this would also result in a conflict if two modules exported the +same C++ type, which is especially problematic for very common types, e.g. +``std::vector``. :ref:`module_local` were added to resolve this (see +that section for a complete usage guide). + +``py::class_`` still defaults to global bindings (because these types are +usually unique across modules), however in order to avoid clashes of opaque +types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers +as ``py::module_local`` if their elements are: builtins (``int``, ``float``, +etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For +example, this change allows multiple modules to bind ``std::vector`` +without causing conflicts. See :ref:`stl_bind` for more details. + +When upgrading to this version, if you have multiple modules which depend on +a single global binding of an STL container, note that all modules can still +accept foreign ``py::module_local`` types in the direction of Python-to-C++. +The locality only affects the C++-to-Python direction. If this is needed in +multiple modules, you'll need to either: + +* Add a copy of the same STL binding to all of the modules which need it. + +* Restore the global status of that single binding by marking it + ``py::module_local(false)``. + +The latter is an easy workaround, but in the long run it would be best to +localize all common type bindings in order to avoid conflicts with +third-party modules. + + +Negative strides for Python buffer objects and numpy arrays +----------------------------------------------------------- + +Support for negative strides required changing the integer type from unsigned +to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you +have compiler warnings enabled, you may notice some new conversion warnings +after upgrading. These can be resolved using ``static_cast``. + + +Deprecation of some ``py::object`` APIs +--------------------------------------- + +To compare ``py::object`` instances by pointer, you should now use +``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python. +Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but +that could be confusing and is now deprecated (so that it can eventually +be replaced with proper rich object comparison in a future release). + +For classes which inherit from ``py::object``, ``borrowed`` and ``stolen`` +were previously available as protected constructor tags. Now the types +should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}`` +(`#771 `_). + + +Stricter compile-time error checking +------------------------------------ + +Some error checks have been moved from run time to compile time. Notably, +automatic conversion of ``std::shared_ptr`` is not possible when ``T`` is +not directly registered with ``py::class_`` (e.g. ``std::shared_ptr`` +or ``std::shared_ptr>`` are not automatically convertible). +Attempting to bind a function with such arguments now results in a compile-time +error instead of waiting to fail at run time. + +``py::init<...>()`` constructor definitions are also stricter and now prevent +bindings which could cause unexpected behavior: + +.. code-block:: cpp + + struct Example { + Example(int &); + }; + + py::class_(m, "Example") + .def(py::init()); // OK, exact match + // .def(py::init()); // compile-time error, mismatch + +A non-``const`` lvalue reference is not allowed to bind to an rvalue. However, +note that a constructor taking ``const T &`` can still be registered using +``py::init()`` because a ``const`` lvalue reference can bind to an rvalue. + +v2.1 +==== + +Minimum compiler versions are enforced at compile time +------------------------------------------------------ + +The minimums also apply to v2.0 but the check is now explicit and a compile-time +error is raised if the compiler does not meet the requirements: + +* GCC >= 4.8 +* clang >= 3.3 (appleclang >= 5.0) +* MSVC >= 2015u3 +* Intel C++ >= 15.0 + + +The ``py::metaclass`` attribute is not required for static properties +--------------------------------------------------------------------- + +Binding classes with static properties is now possible by default. The +zero-parameter version of ``py::metaclass()`` is deprecated. However, a new +one-parameter ``py::metaclass(python_type)`` version was added for rare +cases when a custom metaclass is needed to override pybind11's default. + +.. code-block:: cpp + + // old -- emits a deprecation warning + py::class_(m, "Foo", py::metaclass()) + .def_property_readonly_static("foo", ...); + + // new -- static properties work without the attribute + py::class_(m, "Foo") + .def_property_readonly_static("foo", ...); + + // new -- advanced feature, override pybind11's default metaclass + py::class_(m, "Bar", py::metaclass(custom_python_type)) + ... + + +v2.0 +==== + +Breaking changes in ``py::class_`` +---------------------------------- + +These changes were necessary to make type definitions in pybind11 +future-proof, to support PyPy via its ``cpyext`` mechanism (`#527 +`_), and to improve efficiency +(`rev. 86d825 `_). + +1. Declarations of types that provide access via the buffer protocol must + now include the ``py::buffer_protocol()`` annotation as an argument to + the ``py::class_`` constructor. + + .. code-block:: cpp + + py::class_("Matrix", py::buffer_protocol()) + .def(py::init<...>()) + .def_buffer(...); + +2. Classes which include static properties (e.g. ``def_readwrite_static()``) + must now include the ``py::metaclass()`` attribute. Note: this requirement + has since been removed in v2.1. If you're upgrading from 1.x, it's + recommended to skip directly to v2.1 or newer. + +3. This version of pybind11 uses a redesigned mechanism for instantiating + trampoline classes that are used to override virtual methods from within + Python. This led to the following user-visible syntax change: + + .. code-block:: cpp + + // old v1.x syntax + py::class_("MyClass") + .alias() + ... + + // new v2.x syntax + py::class_("MyClass") + ... + + Importantly, both the original and the trampoline class are now specified + as arguments to the ``py::class_`` template, and the ``alias<..>()`` call + is gone. The new scheme has zero overhead in cases when Python doesn't + override any functions of the underlying C++ class. + `rev. 86d825 `_. + + The class type must be the first template argument given to ``py::class_`` + while the trampoline can be mixed in arbitrary order with other arguments + (see the following section). + + +Deprecation of the ``py::base()`` attribute +---------------------------------------------- + +``py::base()`` was deprecated in favor of specifying ``T`` as a template +argument to ``py::class_``. This new syntax also supports multiple inheritance. +Note that, while the type being exported must be the first argument in the +``py::class_`` template, the order of the following types (bases, +holder and/or trampoline) is not important. + +.. code-block:: cpp + + // old v1.x + py::class_("Derived", py::base()); + + // new v2.x + py::class_("Derived"); + + // new -- multiple inheritance + py::class_("Derived"); + + // new -- apart from `Derived` the argument order can be arbitrary + py::class_("Derived"); + + +Out-of-the-box support for ``std::shared_ptr`` +---------------------------------------------- + +The relevant type caster is now built in, so it's no longer necessary to +include a declaration of the form: + +.. code-block:: cpp + + PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr) + +Continuing to do so won't cause an error or even a deprecation warning, +but it's completely redundant. + + +Deprecation of a few ``py::object`` APIs +---------------------------------------- + +All of the old-style calls emit deprecation warnings. + ++---------------------------------------+---------------------------------------------+ +| Old syntax | New syntax | ++=======================================+=============================================+ +| ``obj.call(args...)`` | ``obj(args...)`` | ++---------------------------------------+---------------------------------------------+ +| ``obj.str()`` | ``py::str(obj)`` | ++---------------------------------------+---------------------------------------------+ +| ``auto l = py::list(obj); l.check()`` | ``py::isinstance(obj)`` | ++---------------------------------------+---------------------------------------------+ +| ``py::object(ptr, true)`` | ``py::reinterpret_borrow(ptr)`` | ++---------------------------------------+---------------------------------------------+ +| ``py::object(ptr, false)`` | ``py::reinterpret_steal(ptr)`` | ++---------------------------------------+---------------------------------------------+ +| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` | ++---------------------------------------+---------------------------------------------+ +| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` | ++---------------------------------------+---------------------------------------------+ diff --git a/third_party/CityFlow/extern/pybind11/noxfile.py b/third_party/CityFlow/extern/pybind11/noxfile.py index f95b6491263659ec3dcd12e11e9a696f09dc7e29..a6d96a1e5d5c8fd6f8051c6854599483f5fd285f 100644 --- a/third_party/CityFlow/extern/pybind11/noxfile.py +++ b/third_party/CityFlow/extern/pybind11/noxfile.py @@ -1,107 +1,107 @@ -import os - -import nox - -nox.needs_version = ">=2022.1.7" -nox.options.sessions = ["lint", "tests", "tests_packaging"] - -PYTHON_VERSIONS = [ - "3.6", - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "pypy3.7", - "pypy3.8", - "pypy3.9", -] - -if os.environ.get("CI", None): - nox.options.error_on_missing_interpreters = True - - -@nox.session(reuse_venv=True) -def lint(session: nox.Session) -> None: - """ - Lint the codebase (except for clang-format/tidy). - """ - session.install("pre-commit") - session.run("pre-commit", "run", "-a", *session.posargs) - - -@nox.session(python=PYTHON_VERSIONS) -def tests(session: nox.Session) -> None: - """ - Run the tests (requires a compiler). - """ - tmpdir = session.create_tmp() - session.install("cmake") - session.install("-r", "tests/requirements.txt") - session.run( - "cmake", - "-S.", - f"-B{tmpdir}", - "-DPYBIND11_WERROR=ON", - "-DDOWNLOAD_CATCH=ON", - "-DDOWNLOAD_EIGEN=ON", - *session.posargs, - ) - session.run("cmake", "--build", tmpdir) - session.run("cmake", "--build", tmpdir, "--config=Release", "--target", "check") - - -@nox.session -def tests_packaging(session: nox.Session) -> None: - """ - Run the packaging tests. - """ - - session.install("-r", "tests/requirements.txt") - session.run("pytest", "tests/extra_python_package", *session.posargs) - - -@nox.session(reuse_venv=True) -def docs(session: nox.Session) -> None: - """ - Build the docs. Pass "serve" to serve. - """ - - session.install("-r", "docs/requirements.txt") - session.chdir("docs") - - if "pdf" in session.posargs: - session.run("sphinx-build", "-M", "latexpdf", ".", "_build") - return - - session.run("sphinx-build", "-M", "html", ".", "_build") - - if "serve" in session.posargs: - session.log("Launching docs at http://localhost:8000/ - use Ctrl-C to quit") - session.run("python", "-m", "http.server", "8000", "-d", "_build/html") - elif session.posargs: - session.error("Unsupported argument to docs") - - -@nox.session(reuse_venv=True) -def make_changelog(session: nox.Session) -> None: - """ - Inspect the closed issues and make entries for a changelog. - """ - session.install("ghapi", "rich") - session.run("python", "tools/make_changelog.py") - - -@nox.session(reuse_venv=True) -def build(session: nox.Session) -> None: - """ - Build SDists and wheels. - """ - - session.install("build") - session.log("Building normal files") - session.run("python", "-m", "build", *session.posargs) - session.log("Building pybind11-global files (PYBIND11_GLOBAL_SDIST=1)") - session.run( - "python", "-m", "build", *session.posargs, env={"PYBIND11_GLOBAL_SDIST": "1"} - ) +import os + +import nox + +nox.needs_version = ">=2022.1.7" +nox.options.sessions = ["lint", "tests", "tests_packaging"] + +PYTHON_VERSIONS = [ + "3.6", + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "pypy3.7", + "pypy3.8", + "pypy3.9", +] + +if os.environ.get("CI", None): + nox.options.error_on_missing_interpreters = True + + +@nox.session(reuse_venv=True) +def lint(session: nox.Session) -> None: + """ + Lint the codebase (except for clang-format/tidy). + """ + session.install("pre-commit") + session.run("pre-commit", "run", "-a", *session.posargs) + + +@nox.session(python=PYTHON_VERSIONS) +def tests(session: nox.Session) -> None: + """ + Run the tests (requires a compiler). + """ + tmpdir = session.create_tmp() + session.install("cmake") + session.install("-r", "tests/requirements.txt") + session.run( + "cmake", + "-S.", + f"-B{tmpdir}", + "-DPYBIND11_WERROR=ON", + "-DDOWNLOAD_CATCH=ON", + "-DDOWNLOAD_EIGEN=ON", + *session.posargs, + ) + session.run("cmake", "--build", tmpdir) + session.run("cmake", "--build", tmpdir, "--config=Release", "--target", "check") + + +@nox.session +def tests_packaging(session: nox.Session) -> None: + """ + Run the packaging tests. + """ + + session.install("-r", "tests/requirements.txt") + session.run("pytest", "tests/extra_python_package", *session.posargs) + + +@nox.session(reuse_venv=True) +def docs(session: nox.Session) -> None: + """ + Build the docs. Pass "serve" to serve. + """ + + session.install("-r", "docs/requirements.txt") + session.chdir("docs") + + if "pdf" in session.posargs: + session.run("sphinx-build", "-M", "latexpdf", ".", "_build") + return + + session.run("sphinx-build", "-M", "html", ".", "_build") + + if "serve" in session.posargs: + session.log("Launching docs at http://localhost:8000/ - use Ctrl-C to quit") + session.run("python", "-m", "http.server", "8000", "-d", "_build/html") + elif session.posargs: + session.error("Unsupported argument to docs") + + +@nox.session(reuse_venv=True) +def make_changelog(session: nox.Session) -> None: + """ + Inspect the closed issues and make entries for a changelog. + """ + session.install("ghapi", "rich") + session.run("python", "tools/make_changelog.py") + + +@nox.session(reuse_venv=True) +def build(session: nox.Session) -> None: + """ + Build SDists and wheels. + """ + + session.install("build") + session.log("Building normal files") + session.run("python", "-m", "build", *session.posargs) + session.log("Building pybind11-global files (PYBIND11_GLOBAL_SDIST=1)") + session.run( + "python", "-m", "build", *session.posargs, env={"PYBIND11_GLOBAL_SDIST": "1"} + ) diff --git a/third_party/CityFlow/extern/pybind11/pybind11/__init__.py b/third_party/CityFlow/extern/pybind11/pybind11/__init__.py index 7c10b305780ecc33264285f276f558699f863f11..ba91d7c00457122160a658cd2ec42f161c241102 100644 --- a/third_party/CityFlow/extern/pybind11/pybind11/__init__.py +++ b/third_party/CityFlow/extern/pybind11/pybind11/__init__.py @@ -1,17 +1,17 @@ -import sys - -if sys.version_info < (3, 6): # noqa: UP036 - msg = "pybind11 does not support Python < 3.6. 2.9 was the last release supporting Python 2.7 and 3.5." - raise ImportError(msg) - - -from ._version import __version__, version_info -from .commands import get_cmake_dir, get_include, get_pkgconfig_dir - -__all__ = ( - "version_info", - "__version__", - "get_include", - "get_cmake_dir", - "get_pkgconfig_dir", -) +import sys + +if sys.version_info < (3, 6): # noqa: UP036 + msg = "pybind11 does not support Python < 3.6. 2.9 was the last release supporting Python 2.7 and 3.5." + raise ImportError(msg) + + +from ._version import __version__, version_info +from .commands import get_cmake_dir, get_include, get_pkgconfig_dir + +__all__ = ( + "version_info", + "__version__", + "get_include", + "get_cmake_dir", + "get_pkgconfig_dir", +) diff --git a/third_party/CityFlow/extern/pybind11/pybind11/__main__.py b/third_party/CityFlow/extern/pybind11/pybind11/__main__.py index 180665c23cda3a2b0ce269057dfff40d9ea11bca..deb0be60fb6c1d09daedb86405bfb55dfa284ae4 100644 --- a/third_party/CityFlow/extern/pybind11/pybind11/__main__.py +++ b/third_party/CityFlow/extern/pybind11/pybind11/__main__.py @@ -1,62 +1,62 @@ -# pylint: disable=missing-function-docstring - -import argparse -import sys -import sysconfig - -from ._version import __version__ -from .commands import get_cmake_dir, get_include, get_pkgconfig_dir - - -def print_includes() -> None: - dirs = [ - sysconfig.get_path("include"), - sysconfig.get_path("platinclude"), - get_include(), - ] - - # Make unique but preserve order - unique_dirs = [] - for d in dirs: - if d and d not in unique_dirs: - unique_dirs.append(d) - - print(" ".join("-I" + d for d in unique_dirs)) - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument( - "--version", - action="version", - version=__version__, - help="Print the version and exit.", - ) - parser.add_argument( - "--includes", - action="store_true", - help="Include flags for both pybind11 and Python headers.", - ) - parser.add_argument( - "--cmakedir", - action="store_true", - help="Print the CMake module directory, ideal for setting -Dpybind11_ROOT in CMake.", - ) - parser.add_argument( - "--pkgconfigdir", - action="store_true", - help="Print the pkgconfig directory, ideal for setting $PKG_CONFIG_PATH.", - ) - args = parser.parse_args() - if not sys.argv[1:]: - parser.print_help() - if args.includes: - print_includes() - if args.cmakedir: - print(get_cmake_dir()) - if args.pkgconfigdir: - print(get_pkgconfig_dir()) - - -if __name__ == "__main__": - main() +# pylint: disable=missing-function-docstring + +import argparse +import sys +import sysconfig + +from ._version import __version__ +from .commands import get_cmake_dir, get_include, get_pkgconfig_dir + + +def print_includes() -> None: + dirs = [ + sysconfig.get_path("include"), + sysconfig.get_path("platinclude"), + get_include(), + ] + + # Make unique but preserve order + unique_dirs = [] + for d in dirs: + if d and d not in unique_dirs: + unique_dirs.append(d) + + print(" ".join("-I" + d for d in unique_dirs)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--version", + action="version", + version=__version__, + help="Print the version and exit.", + ) + parser.add_argument( + "--includes", + action="store_true", + help="Include flags for both pybind11 and Python headers.", + ) + parser.add_argument( + "--cmakedir", + action="store_true", + help="Print the CMake module directory, ideal for setting -Dpybind11_ROOT in CMake.", + ) + parser.add_argument( + "--pkgconfigdir", + action="store_true", + help="Print the pkgconfig directory, ideal for setting $PKG_CONFIG_PATH.", + ) + args = parser.parse_args() + if not sys.argv[1:]: + parser.print_help() + if args.includes: + print_includes() + if args.cmakedir: + print(get_cmake_dir()) + if args.pkgconfigdir: + print(get_pkgconfig_dir()) + + +if __name__ == "__main__": + main() diff --git a/third_party/CityFlow/extern/pybind11/pybind11/_version.py b/third_party/CityFlow/extern/pybind11/pybind11/_version.py index ab5a7bf5f5b421d23a517ae94cb0fb5d2bb86429..32ddaaa423bf3a002865462fbd991507b97e1331 100644 --- a/third_party/CityFlow/extern/pybind11/pybind11/_version.py +++ b/third_party/CityFlow/extern/pybind11/pybind11/_version.py @@ -1,12 +1,12 @@ -from typing import Union - - -def _to_int(s: str) -> Union[int, str]: - try: - return int(s) - except ValueError: - return s - - -__version__ = "2.12.0" -version_info = tuple(_to_int(s) for s in __version__.split(".")) +from typing import Union + + +def _to_int(s: str) -> Union[int, str]: + try: + return int(s) + except ValueError: + return s + + +__version__ = "2.12.0" +version_info = tuple(_to_int(s) for s in __version__.split(".")) diff --git a/third_party/CityFlow/extern/pybind11/pybind11/commands.py b/third_party/CityFlow/extern/pybind11/pybind11/commands.py index b11690f46b21773ec19495c48196219a04c8bab9..25619e65a52a7daa4c148d067df9befa9841cf82 100644 --- a/third_party/CityFlow/extern/pybind11/pybind11/commands.py +++ b/third_party/CityFlow/extern/pybind11/pybind11/commands.py @@ -1,37 +1,37 @@ -import os - -DIR = os.path.abspath(os.path.dirname(__file__)) - - -def get_include(user: bool = False) -> str: # noqa: ARG001 - """ - Return the path to the pybind11 include directory. The historical "user" - argument is unused, and may be removed. - """ - installed_path = os.path.join(DIR, "include") - source_path = os.path.join(os.path.dirname(DIR), "include") - return installed_path if os.path.exists(installed_path) else source_path - - -def get_cmake_dir() -> str: - """ - Return the path to the pybind11 CMake module directory. - """ - cmake_installed_path = os.path.join(DIR, "share", "cmake", "pybind11") - if os.path.exists(cmake_installed_path): - return cmake_installed_path - - msg = "pybind11 not installed, installation required to access the CMake files" - raise ImportError(msg) - - -def get_pkgconfig_dir() -> str: - """ - Return the path to the pybind11 pkgconfig directory. - """ - pkgconfig_installed_path = os.path.join(DIR, "share", "pkgconfig") - if os.path.exists(pkgconfig_installed_path): - return pkgconfig_installed_path - - msg = "pybind11 not installed, installation required to access the pkgconfig files" - raise ImportError(msg) +import os + +DIR = os.path.abspath(os.path.dirname(__file__)) + + +def get_include(user: bool = False) -> str: # noqa: ARG001 + """ + Return the path to the pybind11 include directory. The historical "user" + argument is unused, and may be removed. + """ + installed_path = os.path.join(DIR, "include") + source_path = os.path.join(os.path.dirname(DIR), "include") + return installed_path if os.path.exists(installed_path) else source_path + + +def get_cmake_dir() -> str: + """ + Return the path to the pybind11 CMake module directory. + """ + cmake_installed_path = os.path.join(DIR, "share", "cmake", "pybind11") + if os.path.exists(cmake_installed_path): + return cmake_installed_path + + msg = "pybind11 not installed, installation required to access the CMake files" + raise ImportError(msg) + + +def get_pkgconfig_dir() -> str: + """ + Return the path to the pybind11 pkgconfig directory. + """ + pkgconfig_installed_path = os.path.join(DIR, "share", "pkgconfig") + if os.path.exists(pkgconfig_installed_path): + return pkgconfig_installed_path + + msg = "pybind11 not installed, installation required to access the pkgconfig files" + raise ImportError(msg) diff --git a/third_party/CityFlow/extern/pybind11/pybind11/setup_helpers.py b/third_party/CityFlow/extern/pybind11/pybind11/setup_helpers.py index 3b16dca88692f40895433bd1df187dd28cf3b98e..f662ad0f58a67f09258652a1f3b0373817ae2e38 100644 --- a/third_party/CityFlow/extern/pybind11/pybind11/setup_helpers.py +++ b/third_party/CityFlow/extern/pybind11/pybind11/setup_helpers.py @@ -1,500 +1,500 @@ -""" -This module provides helpers for C++11+ projects using pybind11. - -LICENSE: - -Copyright (c) 2016 Wenzel Jakob , All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -# IMPORTANT: If you change this file in the pybind11 repo, also review -# setup_helpers.pyi for matching changes. -# -# If you copy this file in, you don't -# need the .pyi file; it's just an interface file for static type checkers. - -import contextlib -import os -import platform -import shlex -import shutil -import sys -import sysconfig -import tempfile -import threading -import warnings -from functools import lru_cache -from pathlib import Path -from typing import ( - Any, - Callable, - Dict, - Iterable, - Iterator, - List, - Optional, - Tuple, - TypeVar, - Union, -) - -try: - from setuptools import Extension as _Extension - from setuptools.command.build_ext import build_ext as _build_ext -except ImportError: - from distutils.command.build_ext import ( # type: ignore[assignment] - build_ext as _build_ext, - ) - from distutils.extension import Extension as _Extension # type: ignore[assignment] - -import distutils.ccompiler -import distutils.errors - -WIN = sys.platform.startswith("win32") and "mingw" not in sysconfig.get_platform() -MACOS = sys.platform.startswith("darwin") -STD_TMPL = "/std:c++{}" if WIN else "-std=c++{}" - - -# It is recommended to use PEP 518 builds if using this module. However, this -# file explicitly supports being copied into a user's project directory -# standalone, and pulling pybind11 with the deprecated setup_requires feature. -# If you copy the file, remember to add it to your MANIFEST.in, and add the current -# directory into your path if it sits beside your setup.py. - - -class Pybind11Extension(_Extension): - """ - Build a C++11+ Extension module with pybind11. This automatically adds the - recommended flags when you init the extension and assumes C++ sources - you - can further modify the options yourself. - - The customizations are: - - * ``/EHsc`` and ``/bigobj`` on Windows - * ``stdlib=libc++`` on macOS - * ``visibility=hidden`` and ``-g0`` on Unix - - Finally, you can set ``cxx_std`` via constructor or afterwards to enable - flags for C++ std, and a few extra helper flags related to the C++ standard - level. It is _highly_ recommended you either set this, or use the provided - ``build_ext``, which will search for the highest supported extension for - you if the ``cxx_std`` property is not set. Do not set the ``cxx_std`` - property more than once, as flags are added when you set it. Set the - property to None to disable the addition of C++ standard flags. - - If you want to add pybind11 headers manually, for example for an exact - git checkout, then set ``include_pybind11=False``. - """ - - # flags are prepended, so that they can be further overridden, e.g. by - # ``extra_compile_args=["-g"]``. - - def _add_cflags(self, flags: List[str]) -> None: - self.extra_compile_args[:0] = flags - - def _add_ldflags(self, flags: List[str]) -> None: - self.extra_link_args[:0] = flags - - def __init__(self, *args: Any, **kwargs: Any) -> None: - self._cxx_level = 0 - cxx_std = kwargs.pop("cxx_std", 0) - - if "language" not in kwargs: - kwargs["language"] = "c++" - - include_pybind11 = kwargs.pop("include_pybind11", True) - - super().__init__(*args, **kwargs) - - # Include the installed package pybind11 headers - if include_pybind11: - # If using setup_requires, this fails the first time - that's okay - try: - import pybind11 - - pyinc = pybind11.get_include() - - if pyinc not in self.include_dirs: - self.include_dirs.append(pyinc) - except ModuleNotFoundError: - pass - - self.cxx_std = cxx_std - - cflags = [] - if WIN: - cflags += ["/EHsc", "/bigobj"] - else: - cflags += ["-fvisibility=hidden"] - env_cflags = os.environ.get("CFLAGS", "") - env_cppflags = os.environ.get("CPPFLAGS", "") - c_cpp_flags = shlex.split(env_cflags) + shlex.split(env_cppflags) - if not any(opt.startswith("-g") for opt in c_cpp_flags): - cflags += ["-g0"] - self._add_cflags(cflags) - - @property - def cxx_std(self) -> int: - """ - The CXX standard level. If set, will add the required flags. If left at - 0, it will trigger an automatic search when pybind11's build_ext is - used. If None, will have no effect. Besides just the flags, this may - add a macos-min 10.9 or 10.14 flag if MACOSX_DEPLOYMENT_TARGET is - unset. - """ - return self._cxx_level - - @cxx_std.setter - def cxx_std(self, level: int) -> None: - if self._cxx_level: - warnings.warn( - "You cannot safely change the cxx_level after setting it!", stacklevel=2 - ) - - # MSVC 2015 Update 3 and later only have 14 (and later 17) modes, so - # force a valid flag here. - if WIN and level == 11: - level = 14 - - self._cxx_level = level - - if not level: - return - - cflags = [STD_TMPL.format(level)] - ldflags = [] - - if MACOS and "MACOSX_DEPLOYMENT_TARGET" not in os.environ: - # C++17 requires a higher min version of macOS. An earlier version - # (10.12 or 10.13) can be set manually via environment variable if - # you are careful in your feature usage, but 10.14 is the safest - # setting for general use. However, never set higher than the - # current macOS version! - current_macos = tuple(int(x) for x in platform.mac_ver()[0].split(".")[:2]) - desired_macos = (10, 9) if level < 17 else (10, 14) - macos_string = ".".join(str(x) for x in min(current_macos, desired_macos)) - macosx_min = f"-mmacosx-version-min={macos_string}" - cflags += [macosx_min] - ldflags += [macosx_min] - - self._add_cflags(cflags) - self._add_ldflags(ldflags) - - -# Just in case someone clever tries to multithread -tmp_chdir_lock = threading.Lock() - - -@contextlib.contextmanager -def tmp_chdir() -> Iterator[str]: - "Prepare and enter a temporary directory, cleanup when done" - - # Threadsafe - with tmp_chdir_lock: - olddir = os.getcwd() - try: - tmpdir = tempfile.mkdtemp() - os.chdir(tmpdir) - yield tmpdir - finally: - os.chdir(olddir) - shutil.rmtree(tmpdir) - - -# cf http://bugs.python.org/issue26689 -def has_flag(compiler: Any, flag: str) -> bool: - """ - Return the flag if a flag name is supported on the - specified compiler, otherwise None (can be used as a boolean). - If multiple flags are passed, return the first that matches. - """ - - with tmp_chdir(): - fname = Path("flagcheck.cpp") - # Don't trigger -Wunused-parameter. - fname.write_text("int main (int, char **) { return 0; }", encoding="utf-8") - - try: - compiler.compile([str(fname)], extra_postargs=[flag]) - except distutils.errors.CompileError: - return False - return True - - -# Every call will cache the result -cpp_flag_cache = None - - -@lru_cache() -def auto_cpp_level(compiler: Any) -> Union[str, int]: - """ - Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows. - """ - - if WIN: - return "latest" - - levels = [17, 14, 11] - - for level in levels: - if has_flag(compiler, STD_TMPL.format(level)): - return level - - msg = "Unsupported compiler -- at least C++11 support is needed!" - raise RuntimeError(msg) - - -class build_ext(_build_ext): # noqa: N801 - """ - Customized build_ext that allows an auto-search for the highest supported - C++ level for Pybind11Extension. This is only needed for the auto-search - for now, and is completely optional otherwise. - """ - - def build_extensions(self) -> None: - """ - Build extensions, injecting C++ std for Pybind11Extension if needed. - """ - - for ext in self.extensions: - if hasattr(ext, "_cxx_level") and ext._cxx_level == 0: - ext.cxx_std = auto_cpp_level(self.compiler) - - super().build_extensions() - - -def intree_extensions( - paths: Iterable[str], package_dir: Optional[Dict[str, str]] = None -) -> List[Pybind11Extension]: - """ - Generate Pybind11Extensions from source files directly located in a Python - source tree. - - ``package_dir`` behaves as in ``setuptools.setup``. If unset, the Python - package root parent is determined as the first parent directory that does - not contain an ``__init__.py`` file. - """ - exts = [] - - if package_dir is None: - for path in paths: - parent, _ = os.path.split(path) - while os.path.exists(os.path.join(parent, "__init__.py")): - parent, _ = os.path.split(parent) - relname, _ = os.path.splitext(os.path.relpath(path, parent)) - qualified_name = relname.replace(os.path.sep, ".") - exts.append(Pybind11Extension(qualified_name, [path])) - return exts - - for path in paths: - for prefix, parent in package_dir.items(): - if path.startswith(parent): - relname, _ = os.path.splitext(os.path.relpath(path, parent)) - qualified_name = relname.replace(os.path.sep, ".") - if prefix: - qualified_name = prefix + "." + qualified_name - exts.append(Pybind11Extension(qualified_name, [path])) - break - else: - msg = ( - f"path {path} is not a child of any of the directories listed " - f"in 'package_dir' ({package_dir})" - ) - raise ValueError(msg) - - return exts - - -def naive_recompile(obj: str, src: str) -> bool: - """ - This will recompile only if the source file changes. It does not check - header files, so a more advanced function or Ccache is better if you have - editable header files in your package. - """ - return os.stat(obj).st_mtime < os.stat(src).st_mtime - - -def no_recompile(obg: str, src: str) -> bool: # noqa: ARG001 - """ - This is the safest but slowest choice (and is the default) - will always - recompile sources. - """ - return True - - -S = TypeVar("S", bound="ParallelCompile") - -CCompilerMethod = Callable[ - [ - distutils.ccompiler.CCompiler, - List[str], - Optional[str], - Optional[Union[Tuple[str], Tuple[str, Optional[str]]]], - Optional[List[str]], - bool, - Optional[List[str]], - Optional[List[str]], - Optional[List[str]], - ], - List[str], -] - - -# Optional parallel compile utility -# inspired by: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils -# and: https://github.com/tbenthompson/cppimport/blob/stable/cppimport/build_module.py -# and NumPy's parallel distutils module: -# https://github.com/numpy/numpy/blob/master/numpy/distutils/ccompiler.py -class ParallelCompile: - """ - Make a parallel compile function. Inspired by - numpy.distutils.ccompiler.CCompiler.compile and cppimport. - - This takes several arguments that allow you to customize the compile - function created: - - envvar: - Set an environment variable to control the compilation threads, like - NPY_NUM_BUILD_JOBS - default: - 0 will automatically multithread, or 1 will only multithread if the - envvar is set. - max: - The limit for automatic multithreading if non-zero - needs_recompile: - A function of (obj, src) that returns True when recompile is needed. No - effect in isolated mode; use ccache instead, see - https://github.com/matplotlib/matplotlib/issues/1507/ - - To use:: - - ParallelCompile("NPY_NUM_BUILD_JOBS").install() - - or:: - - with ParallelCompile("NPY_NUM_BUILD_JOBS"): - setup(...) - - By default, this assumes all files need to be recompiled. A smarter - function can be provided via needs_recompile. If the output has not yet - been generated, the compile will always run, and this function is not - called. - """ - - __slots__ = ("envvar", "default", "max", "_old", "needs_recompile") - - def __init__( - self, - envvar: Optional[str] = None, - default: int = 0, - max: int = 0, # pylint: disable=redefined-builtin - needs_recompile: Callable[[str, str], bool] = no_recompile, - ) -> None: - self.envvar = envvar - self.default = default - self.max = max - self.needs_recompile = needs_recompile - self._old: List[CCompilerMethod] = [] - - def function(self) -> CCompilerMethod: - """ - Builds a function object usable as distutils.ccompiler.CCompiler.compile. - """ - - def compile_function( - compiler: distutils.ccompiler.CCompiler, - sources: List[str], - output_dir: Optional[str] = None, - macros: Optional[Union[Tuple[str], Tuple[str, Optional[str]]]] = None, - include_dirs: Optional[List[str]] = None, - debug: bool = False, - extra_preargs: Optional[List[str]] = None, - extra_postargs: Optional[List[str]] = None, - depends: Optional[List[str]] = None, - ) -> Any: - # These lines are directly from distutils.ccompiler.CCompiler - macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile( # type: ignore[attr-defined] - output_dir, macros, include_dirs, sources, depends, extra_postargs - ) - cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs) # type: ignore[attr-defined] - - # The number of threads; start with default. - threads = self.default - - # Determine the number of compilation threads, unless set by an environment variable. - if self.envvar is not None: - threads = int(os.environ.get(self.envvar, self.default)) - - def _single_compile(obj: Any) -> None: - try: - src, ext = build[obj] - except KeyError: - return - - if not os.path.exists(obj) or self.needs_recompile(obj, src): - compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # type: ignore[attr-defined] - - try: - # Importing .synchronize checks for platforms that have some multiprocessing - # capabilities but lack semaphores, such as AWS Lambda and Android Termux. - import multiprocessing.synchronize - from multiprocessing.pool import ThreadPool - except ImportError: - threads = 1 - - if threads == 0: - try: - threads = multiprocessing.cpu_count() - threads = self.max if self.max and self.max < threads else threads - except NotImplementedError: - threads = 1 - - if threads > 1: - with ThreadPool(threads) as pool: - for _ in pool.imap_unordered(_single_compile, objects): - pass - else: - for ob in objects: - _single_compile(ob) - - return objects - - return compile_function - - def install(self: S) -> S: - """ - Installs the compile function into distutils.ccompiler.CCompiler.compile. - """ - distutils.ccompiler.CCompiler.compile = self.function() # type: ignore[assignment] - return self - - def __enter__(self: S) -> S: - self._old.append(distutils.ccompiler.CCompiler.compile) - return self.install() - - def __exit__(self, *args: Any) -> None: - distutils.ccompiler.CCompiler.compile = self._old.pop() # type: ignore[assignment] +""" +This module provides helpers for C++11+ projects using pybind11. + +LICENSE: + +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +# IMPORTANT: If you change this file in the pybind11 repo, also review +# setup_helpers.pyi for matching changes. +# +# If you copy this file in, you don't +# need the .pyi file; it's just an interface file for static type checkers. + +import contextlib +import os +import platform +import shlex +import shutil +import sys +import sysconfig +import tempfile +import threading +import warnings +from functools import lru_cache +from pathlib import Path +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +try: + from setuptools import Extension as _Extension + from setuptools.command.build_ext import build_ext as _build_ext +except ImportError: + from distutils.command.build_ext import ( # type: ignore[assignment] + build_ext as _build_ext, + ) + from distutils.extension import Extension as _Extension # type: ignore[assignment] + +import distutils.ccompiler +import distutils.errors + +WIN = sys.platform.startswith("win32") and "mingw" not in sysconfig.get_platform() +MACOS = sys.platform.startswith("darwin") +STD_TMPL = "/std:c++{}" if WIN else "-std=c++{}" + + +# It is recommended to use PEP 518 builds if using this module. However, this +# file explicitly supports being copied into a user's project directory +# standalone, and pulling pybind11 with the deprecated setup_requires feature. +# If you copy the file, remember to add it to your MANIFEST.in, and add the current +# directory into your path if it sits beside your setup.py. + + +class Pybind11Extension(_Extension): + """ + Build a C++11+ Extension module with pybind11. This automatically adds the + recommended flags when you init the extension and assumes C++ sources - you + can further modify the options yourself. + + The customizations are: + + * ``/EHsc`` and ``/bigobj`` on Windows + * ``stdlib=libc++`` on macOS + * ``visibility=hidden`` and ``-g0`` on Unix + + Finally, you can set ``cxx_std`` via constructor or afterwards to enable + flags for C++ std, and a few extra helper flags related to the C++ standard + level. It is _highly_ recommended you either set this, or use the provided + ``build_ext``, which will search for the highest supported extension for + you if the ``cxx_std`` property is not set. Do not set the ``cxx_std`` + property more than once, as flags are added when you set it. Set the + property to None to disable the addition of C++ standard flags. + + If you want to add pybind11 headers manually, for example for an exact + git checkout, then set ``include_pybind11=False``. + """ + + # flags are prepended, so that they can be further overridden, e.g. by + # ``extra_compile_args=["-g"]``. + + def _add_cflags(self, flags: List[str]) -> None: + self.extra_compile_args[:0] = flags + + def _add_ldflags(self, flags: List[str]) -> None: + self.extra_link_args[:0] = flags + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._cxx_level = 0 + cxx_std = kwargs.pop("cxx_std", 0) + + if "language" not in kwargs: + kwargs["language"] = "c++" + + include_pybind11 = kwargs.pop("include_pybind11", True) + + super().__init__(*args, **kwargs) + + # Include the installed package pybind11 headers + if include_pybind11: + # If using setup_requires, this fails the first time - that's okay + try: + import pybind11 + + pyinc = pybind11.get_include() + + if pyinc not in self.include_dirs: + self.include_dirs.append(pyinc) + except ModuleNotFoundError: + pass + + self.cxx_std = cxx_std + + cflags = [] + if WIN: + cflags += ["/EHsc", "/bigobj"] + else: + cflags += ["-fvisibility=hidden"] + env_cflags = os.environ.get("CFLAGS", "") + env_cppflags = os.environ.get("CPPFLAGS", "") + c_cpp_flags = shlex.split(env_cflags) + shlex.split(env_cppflags) + if not any(opt.startswith("-g") for opt in c_cpp_flags): + cflags += ["-g0"] + self._add_cflags(cflags) + + @property + def cxx_std(self) -> int: + """ + The CXX standard level. If set, will add the required flags. If left at + 0, it will trigger an automatic search when pybind11's build_ext is + used. If None, will have no effect. Besides just the flags, this may + add a macos-min 10.9 or 10.14 flag if MACOSX_DEPLOYMENT_TARGET is + unset. + """ + return self._cxx_level + + @cxx_std.setter + def cxx_std(self, level: int) -> None: + if self._cxx_level: + warnings.warn( + "You cannot safely change the cxx_level after setting it!", stacklevel=2 + ) + + # MSVC 2015 Update 3 and later only have 14 (and later 17) modes, so + # force a valid flag here. + if WIN and level == 11: + level = 14 + + self._cxx_level = level + + if not level: + return + + cflags = [STD_TMPL.format(level)] + ldflags = [] + + if MACOS and "MACOSX_DEPLOYMENT_TARGET" not in os.environ: + # C++17 requires a higher min version of macOS. An earlier version + # (10.12 or 10.13) can be set manually via environment variable if + # you are careful in your feature usage, but 10.14 is the safest + # setting for general use. However, never set higher than the + # current macOS version! + current_macos = tuple(int(x) for x in platform.mac_ver()[0].split(".")[:2]) + desired_macos = (10, 9) if level < 17 else (10, 14) + macos_string = ".".join(str(x) for x in min(current_macos, desired_macos)) + macosx_min = f"-mmacosx-version-min={macos_string}" + cflags += [macosx_min] + ldflags += [macosx_min] + + self._add_cflags(cflags) + self._add_ldflags(ldflags) + + +# Just in case someone clever tries to multithread +tmp_chdir_lock = threading.Lock() + + +@contextlib.contextmanager +def tmp_chdir() -> Iterator[str]: + "Prepare and enter a temporary directory, cleanup when done" + + # Threadsafe + with tmp_chdir_lock: + olddir = os.getcwd() + try: + tmpdir = tempfile.mkdtemp() + os.chdir(tmpdir) + yield tmpdir + finally: + os.chdir(olddir) + shutil.rmtree(tmpdir) + + +# cf http://bugs.python.org/issue26689 +def has_flag(compiler: Any, flag: str) -> bool: + """ + Return the flag if a flag name is supported on the + specified compiler, otherwise None (can be used as a boolean). + If multiple flags are passed, return the first that matches. + """ + + with tmp_chdir(): + fname = Path("flagcheck.cpp") + # Don't trigger -Wunused-parameter. + fname.write_text("int main (int, char **) { return 0; }", encoding="utf-8") + + try: + compiler.compile([str(fname)], extra_postargs=[flag]) + except distutils.errors.CompileError: + return False + return True + + +# Every call will cache the result +cpp_flag_cache = None + + +@lru_cache() +def auto_cpp_level(compiler: Any) -> Union[str, int]: + """ + Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows. + """ + + if WIN: + return "latest" + + levels = [17, 14, 11] + + for level in levels: + if has_flag(compiler, STD_TMPL.format(level)): + return level + + msg = "Unsupported compiler -- at least C++11 support is needed!" + raise RuntimeError(msg) + + +class build_ext(_build_ext): # noqa: N801 + """ + Customized build_ext that allows an auto-search for the highest supported + C++ level for Pybind11Extension. This is only needed for the auto-search + for now, and is completely optional otherwise. + """ + + def build_extensions(self) -> None: + """ + Build extensions, injecting C++ std for Pybind11Extension if needed. + """ + + for ext in self.extensions: + if hasattr(ext, "_cxx_level") and ext._cxx_level == 0: + ext.cxx_std = auto_cpp_level(self.compiler) + + super().build_extensions() + + +def intree_extensions( + paths: Iterable[str], package_dir: Optional[Dict[str, str]] = None +) -> List[Pybind11Extension]: + """ + Generate Pybind11Extensions from source files directly located in a Python + source tree. + + ``package_dir`` behaves as in ``setuptools.setup``. If unset, the Python + package root parent is determined as the first parent directory that does + not contain an ``__init__.py`` file. + """ + exts = [] + + if package_dir is None: + for path in paths: + parent, _ = os.path.split(path) + while os.path.exists(os.path.join(parent, "__init__.py")): + parent, _ = os.path.split(parent) + relname, _ = os.path.splitext(os.path.relpath(path, parent)) + qualified_name = relname.replace(os.path.sep, ".") + exts.append(Pybind11Extension(qualified_name, [path])) + return exts + + for path in paths: + for prefix, parent in package_dir.items(): + if path.startswith(parent): + relname, _ = os.path.splitext(os.path.relpath(path, parent)) + qualified_name = relname.replace(os.path.sep, ".") + if prefix: + qualified_name = prefix + "." + qualified_name + exts.append(Pybind11Extension(qualified_name, [path])) + break + else: + msg = ( + f"path {path} is not a child of any of the directories listed " + f"in 'package_dir' ({package_dir})" + ) + raise ValueError(msg) + + return exts + + +def naive_recompile(obj: str, src: str) -> bool: + """ + This will recompile only if the source file changes. It does not check + header files, so a more advanced function or Ccache is better if you have + editable header files in your package. + """ + return os.stat(obj).st_mtime < os.stat(src).st_mtime + + +def no_recompile(obg: str, src: str) -> bool: # noqa: ARG001 + """ + This is the safest but slowest choice (and is the default) - will always + recompile sources. + """ + return True + + +S = TypeVar("S", bound="ParallelCompile") + +CCompilerMethod = Callable[ + [ + distutils.ccompiler.CCompiler, + List[str], + Optional[str], + Optional[Union[Tuple[str], Tuple[str, Optional[str]]]], + Optional[List[str]], + bool, + Optional[List[str]], + Optional[List[str]], + Optional[List[str]], + ], + List[str], +] + + +# Optional parallel compile utility +# inspired by: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils +# and: https://github.com/tbenthompson/cppimport/blob/stable/cppimport/build_module.py +# and NumPy's parallel distutils module: +# https://github.com/numpy/numpy/blob/master/numpy/distutils/ccompiler.py +class ParallelCompile: + """ + Make a parallel compile function. Inspired by + numpy.distutils.ccompiler.CCompiler.compile and cppimport. + + This takes several arguments that allow you to customize the compile + function created: + + envvar: + Set an environment variable to control the compilation threads, like + NPY_NUM_BUILD_JOBS + default: + 0 will automatically multithread, or 1 will only multithread if the + envvar is set. + max: + The limit for automatic multithreading if non-zero + needs_recompile: + A function of (obj, src) that returns True when recompile is needed. No + effect in isolated mode; use ccache instead, see + https://github.com/matplotlib/matplotlib/issues/1507/ + + To use:: + + ParallelCompile("NPY_NUM_BUILD_JOBS").install() + + or:: + + with ParallelCompile("NPY_NUM_BUILD_JOBS"): + setup(...) + + By default, this assumes all files need to be recompiled. A smarter + function can be provided via needs_recompile. If the output has not yet + been generated, the compile will always run, and this function is not + called. + """ + + __slots__ = ("envvar", "default", "max", "_old", "needs_recompile") + + def __init__( + self, + envvar: Optional[str] = None, + default: int = 0, + max: int = 0, # pylint: disable=redefined-builtin + needs_recompile: Callable[[str, str], bool] = no_recompile, + ) -> None: + self.envvar = envvar + self.default = default + self.max = max + self.needs_recompile = needs_recompile + self._old: List[CCompilerMethod] = [] + + def function(self) -> CCompilerMethod: + """ + Builds a function object usable as distutils.ccompiler.CCompiler.compile. + """ + + def compile_function( + compiler: distutils.ccompiler.CCompiler, + sources: List[str], + output_dir: Optional[str] = None, + macros: Optional[Union[Tuple[str], Tuple[str, Optional[str]]]] = None, + include_dirs: Optional[List[str]] = None, + debug: bool = False, + extra_preargs: Optional[List[str]] = None, + extra_postargs: Optional[List[str]] = None, + depends: Optional[List[str]] = None, + ) -> Any: + # These lines are directly from distutils.ccompiler.CCompiler + macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile( # type: ignore[attr-defined] + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs) # type: ignore[attr-defined] + + # The number of threads; start with default. + threads = self.default + + # Determine the number of compilation threads, unless set by an environment variable. + if self.envvar is not None: + threads = int(os.environ.get(self.envvar, self.default)) + + def _single_compile(obj: Any) -> None: + try: + src, ext = build[obj] + except KeyError: + return + + if not os.path.exists(obj) or self.needs_recompile(obj, src): + compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # type: ignore[attr-defined] + + try: + # Importing .synchronize checks for platforms that have some multiprocessing + # capabilities but lack semaphores, such as AWS Lambda and Android Termux. + import multiprocessing.synchronize + from multiprocessing.pool import ThreadPool + except ImportError: + threads = 1 + + if threads == 0: + try: + threads = multiprocessing.cpu_count() + threads = self.max if self.max and self.max < threads else threads + except NotImplementedError: + threads = 1 + + if threads > 1: + with ThreadPool(threads) as pool: + for _ in pool.imap_unordered(_single_compile, objects): + pass + else: + for ob in objects: + _single_compile(ob) + + return objects + + return compile_function + + def install(self: S) -> S: + """ + Installs the compile function into distutils.ccompiler.CCompiler.compile. + """ + distutils.ccompiler.CCompiler.compile = self.function() # type: ignore[assignment] + return self + + def __enter__(self: S) -> S: + self._old.append(distutils.ccompiler.CCompiler.compile) + return self.install() + + def __exit__(self, *args: Any) -> None: + distutils.ccompiler.CCompiler.compile = self._old.pop() # type: ignore[assignment] diff --git a/third_party/CityFlow/extern/pybind11/pyproject.toml b/third_party/CityFlow/extern/pybind11/pyproject.toml index 5af6015a6b34a758632f1dcc6704e9d4c0394c86..3b67f88ee054425194d1f162fe344f53d8ba7621 100644 --- a/third_party/CityFlow/extern/pybind11/pyproject.toml +++ b/third_party/CityFlow/extern/pybind11/pyproject.toml @@ -1,95 +1,95 @@ -[build-system] -requires = ["setuptools>=42", "cmake>=3.18", "ninja"] -build-backend = "setuptools.build_meta" - - -[tool.check-manifest] -ignore = [ - "tests/**", - "docs/**", - "tools/**", - "include/**", - ".*", - "pybind11/include/**", - "pybind11/share/**", - "CMakeLists.txt", - "noxfile.py", -] - - -[tool.mypy] -files = ["pybind11"] -python_version = "3.7" -strict = true -show_error_codes = true -enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] -warn_unreachable = true - -[[tool.mypy.overrides]] -module = ["ghapi.*"] -ignore_missing_imports = true - - -[tool.pytest.ini_options] -minversion = "6.0" -addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"] -xfail_strict = true -filterwarnings = ["error"] -log_cli_level = "info" -testpaths = [ - "tests", -] -timeout=300 - - -[tool.pylint] -master.py-version = "3.6" -reports.output-format = "colorized" -messages_control.disable = [ - "design", - "fixme", - "imports", - "line-too-long", - "imports", - "invalid-name", - "protected-access", - "missing-module-docstring", - "unused-argument", # covered by Ruff ARG -] - -[tool.ruff] -target-version = "py37" -src = ["src"] - -[tool.ruff.lint] -extend-select = [ - "B", # flake8-bugbear - "I", # isort - "N", # pep8-naming - "ARG", # flake8-unused-arguments - "C4", # flake8-comprehensions - "EM", # flake8-errmsg - "ICN", # flake8-import-conventions - "PGH", # pygrep-hooks - "PIE", # flake8-pie - "PL", # pylint - "PT", # flake8-pytest-style - "RET", # flake8-return - "RUF100", # Ruff-specific - "SIM", # flake8-simplify - "UP", # pyupgrade - "YTT", # flake8-2020 -] -ignore = [ - "PLR", # Design related pylint - "E501", # Line too long (Black is enough) - "PT011", # Too broad with raises in pytest - "PT004", # Fixture that doesn't return needs underscore (no, it is fine) - "SIM118", # iter(x) is not always the same as iter(x.keys()) -] -unfixable = ["T20"] -isort.known-first-party = ["env", "pybind11_cross_module_tests", "pybind11_tests"] - -[tool.ruff.lint.per-file-ignores] -"tests/**" = ["EM", "N", "E721"] -"tests/test_call_policies.py" = ["PLC1901"] +[build-system] +requires = ["setuptools>=42", "cmake>=3.18", "ninja"] +build-backend = "setuptools.build_meta" + + +[tool.check-manifest] +ignore = [ + "tests/**", + "docs/**", + "tools/**", + "include/**", + ".*", + "pybind11/include/**", + "pybind11/share/**", + "CMakeLists.txt", + "noxfile.py", +] + + +[tool.mypy] +files = ["pybind11"] +python_version = "3.7" +strict = true +show_error_codes = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] +warn_unreachable = true + +[[tool.mypy.overrides]] +module = ["ghapi.*"] +ignore_missing_imports = true + + +[tool.pytest.ini_options] +minversion = "6.0" +addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"] +xfail_strict = true +filterwarnings = ["error"] +log_cli_level = "info" +testpaths = [ + "tests", +] +timeout=300 + + +[tool.pylint] +master.py-version = "3.6" +reports.output-format = "colorized" +messages_control.disable = [ + "design", + "fixme", + "imports", + "line-too-long", + "imports", + "invalid-name", + "protected-access", + "missing-module-docstring", + "unused-argument", # covered by Ruff ARG +] + +[tool.ruff] +target-version = "py37" +src = ["src"] + +[tool.ruff.lint] +extend-select = [ + "B", # flake8-bugbear + "I", # isort + "N", # pep8-naming + "ARG", # flake8-unused-arguments + "C4", # flake8-comprehensions + "EM", # flake8-errmsg + "ICN", # flake8-import-conventions + "PGH", # pygrep-hooks + "PIE", # flake8-pie + "PL", # pylint + "PT", # flake8-pytest-style + "RET", # flake8-return + "RUF100", # Ruff-specific + "SIM", # flake8-simplify + "UP", # pyupgrade + "YTT", # flake8-2020 +] +ignore = [ + "PLR", # Design related pylint + "E501", # Line too long (Black is enough) + "PT011", # Too broad with raises in pytest + "PT004", # Fixture that doesn't return needs underscore (no, it is fine) + "SIM118", # iter(x) is not always the same as iter(x.keys()) +] +unfixable = ["T20"] +isort.known-first-party = ["env", "pybind11_cross_module_tests", "pybind11_tests"] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["EM", "N", "E721"] +"tests/test_call_policies.py" = ["PLC1901"] diff --git a/third_party/CityFlow/extern/pybind11/setup.cfg b/third_party/CityFlow/extern/pybind11/setup.cfg index 92e6c953a900639003e96ac7dffb63adf16fb9bb..49a881f5dca3ba7ca7b80f808b3df6a6d2b61fd1 100644 --- a/third_party/CityFlow/extern/pybind11/setup.cfg +++ b/third_party/CityFlow/extern/pybind11/setup.cfg @@ -1,43 +1,43 @@ -[metadata] -long_description = file: README.rst -long_description_content_type = text/x-rst -description = Seamless operability between C++11 and Python -author = Wenzel Jakob -author_email = wenzel.jakob@epfl.ch -url = https://github.com/pybind/pybind11 -license = BSD - -classifiers = - Development Status :: 5 - Production/Stable - Intended Audience :: Developers - Topic :: Software Development :: Libraries :: Python Modules - Topic :: Utilities - Programming Language :: C++ - Programming Language :: Python :: 3 :: Only - Programming Language :: Python :: 3.6 - Programming Language :: Python :: 3.7 - Programming Language :: Python :: 3.8 - Programming Language :: Python :: 3.9 - Programming Language :: Python :: 3.10 - Programming Language :: Python :: 3.11 - Programming Language :: Python :: 3.12 - License :: OSI Approved :: BSD License - Programming Language :: Python :: Implementation :: PyPy - Programming Language :: Python :: Implementation :: CPython - Programming Language :: C++ - Topic :: Software Development :: Libraries :: Python Modules - -keywords = - C++11 - Python bindings - -project_urls = - Documentation = https://pybind11.readthedocs.io/ - Bug Tracker = https://github.com/pybind/pybind11/issues - Discussions = https://github.com/pybind/pybind11/discussions - Changelog = https://pybind11.readthedocs.io/en/latest/changelog.html - Chat = https://gitter.im/pybind/Lobby - -[options] -python_requires = >=3.6 -zip_safe = False +[metadata] +long_description = file: README.rst +long_description_content_type = text/x-rst +description = Seamless operability between C++11 and Python +author = Wenzel Jakob +author_email = wenzel.jakob@epfl.ch +url = https://github.com/pybind/pybind11 +license = BSD + +classifiers = + Development Status :: 5 - Production/Stable + Intended Audience :: Developers + Topic :: Software Development :: Libraries :: Python Modules + Topic :: Utilities + Programming Language :: C++ + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 + Programming Language :: Python :: 3.12 + License :: OSI Approved :: BSD License + Programming Language :: Python :: Implementation :: PyPy + Programming Language :: Python :: Implementation :: CPython + Programming Language :: C++ + Topic :: Software Development :: Libraries :: Python Modules + +keywords = + C++11 + Python bindings + +project_urls = + Documentation = https://pybind11.readthedocs.io/ + Bug Tracker = https://github.com/pybind/pybind11/issues + Discussions = https://github.com/pybind/pybind11/discussions + Changelog = https://pybind11.readthedocs.io/en/latest/changelog.html + Chat = https://gitter.im/pybind/Lobby + +[options] +python_requires = >=3.6 +zip_safe = False diff --git a/third_party/CityFlow/extern/pybind11/setup.py b/third_party/CityFlow/extern/pybind11/setup.py index 9fea7d35c7953f094a347233cadc73a72c3d8efe..67793c4f584a1ffa81273ce92314b46b7f2689f8 100644 --- a/third_party/CityFlow/extern/pybind11/setup.py +++ b/third_party/CityFlow/extern/pybind11/setup.py @@ -1,150 +1,150 @@ -#!/usr/bin/env python3 - -# Setup script for PyPI; use CMakeFile.txt to build extension modules - -import contextlib -import os -import re -import shutil -import string -import subprocess -import sys -from pathlib import Path -from tempfile import TemporaryDirectory -from typing import Dict, Iterator, List, Union - -import setuptools.command.sdist - -DIR = Path(__file__).parent.absolute() -VERSION_REGEX = re.compile( - r"^\s*#\s*define\s+PYBIND11_VERSION_([A-Z]+)\s+(.*)$", re.MULTILINE -) -VERSION_FILE = Path("pybind11/_version.py") -COMMON_FILE = Path("include/pybind11/detail/common.h") - - -def build_expected_version_hex(matches: Dict[str, str]) -> str: - patch_level_serial = matches["PATCH"] - serial = None - major = int(matches["MAJOR"]) - minor = int(matches["MINOR"]) - flds = patch_level_serial.split(".") - if flds: - patch = int(flds[0]) - if len(flds) == 1: - level = "0" - serial = 0 - elif len(flds) == 2: - level_serial = flds[1] - for level in ("a", "b", "c", "dev"): - if level_serial.startswith(level): - serial = int(level_serial[len(level) :]) - break - if serial is None: - msg = f'Invalid PYBIND11_VERSION_PATCH: "{patch_level_serial}"' - raise RuntimeError(msg) - version_hex_str = f"{major:02x}{minor:02x}{patch:02x}{level[:1]}{serial:x}" - return f"0x{version_hex_str.upper()}" - - -# PYBIND11_GLOBAL_SDIST will build a different sdist, with the python-headers -# files, and the sys.prefix files (CMake and headers). - -global_sdist = os.environ.get("PYBIND11_GLOBAL_SDIST", False) - -setup_py = Path( - "tools/setup_global.py.in" if global_sdist else "tools/setup_main.py.in" -) -extra_cmd = 'cmdclass["sdist"] = SDist\n' - -to_src = ( - (Path("pyproject.toml"), Path("tools/pyproject.toml")), - (Path("setup.py"), setup_py), -) - - -# Read the listed version -loc: Dict[str, str] = {} -code = compile(VERSION_FILE.read_text(encoding="utf-8"), "pybind11/_version.py", "exec") -exec(code, loc) -version = loc["__version__"] - -# Verify that the version matches the one in C++ -matches = dict(VERSION_REGEX.findall(COMMON_FILE.read_text(encoding="utf8"))) -cpp_version = "{MAJOR}.{MINOR}.{PATCH}".format(**matches) -if version != cpp_version: - msg = f"Python version {version} does not match C++ version {cpp_version}!" - raise RuntimeError(msg) - -version_hex = matches.get("HEX", "MISSING") -exp_version_hex = build_expected_version_hex(matches) -if version_hex != exp_version_hex: - msg = f"PYBIND11_VERSION_HEX {version_hex} does not match expected value {exp_version_hex}!" - raise RuntimeError(msg) - - -# TODO: use literals & overload (typing extensions or Python 3.8) -def get_and_replace( - filename: Path, binary: bool = False, **opts: str -) -> Union[bytes, str]: - if binary: - contents = filename.read_bytes() - return string.Template(contents.decode()).substitute(opts).encode() - - return string.Template(filename.read_text()).substitute(opts) - - -# Use our input files instead when making the SDist (and anything that depends -# on it, like a wheel) -class SDist(setuptools.command.sdist.sdist): - def make_release_tree(self, base_dir: str, files: List[str]) -> None: - super().make_release_tree(base_dir, files) - - for to, src in to_src: - txt = get_and_replace(src, binary=True, version=version, extra_cmd="") - - dest = Path(base_dir) / to - - # This is normally linked, so unlink before writing! - dest.unlink() - dest.write_bytes(txt) # type: ignore[arg-type] - - -# Remove the CMake install directory when done -@contextlib.contextmanager -def remove_output(*sources: str) -> Iterator[None]: - try: - yield - finally: - for src in sources: - shutil.rmtree(src) - - -with remove_output("pybind11/include", "pybind11/share"): - # Generate the files if they are not present. - with TemporaryDirectory() as tmpdir: - cmd = ["cmake", "-S", ".", "-B", tmpdir] + [ - "-DCMAKE_INSTALL_PREFIX=pybind11", - "-DBUILD_TESTING=OFF", - "-DPYBIND11_NOPYTHON=ON", - "-Dprefix_for_pc_file=${pcfiledir}/../../", - ] - if "CMAKE_ARGS" in os.environ: - fcommand = [ - c - for c in os.environ["CMAKE_ARGS"].split() - if "DCMAKE_INSTALL_PREFIX" not in c - ] - cmd += fcommand - subprocess.run(cmd, check=True, cwd=DIR, stdout=sys.stdout, stderr=sys.stderr) - subprocess.run( - ["cmake", "--install", tmpdir], - check=True, - cwd=DIR, - stdout=sys.stdout, - stderr=sys.stderr, - ) - - txt = get_and_replace(setup_py, version=version, extra_cmd=extra_cmd) - code = compile(txt, setup_py, "exec") - exec(code, {"SDist": SDist}) +#!/usr/bin/env python3 + +# Setup script for PyPI; use CMakeFile.txt to build extension modules + +import contextlib +import os +import re +import shutil +import string +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Dict, Iterator, List, Union + +import setuptools.command.sdist + +DIR = Path(__file__).parent.absolute() +VERSION_REGEX = re.compile( + r"^\s*#\s*define\s+PYBIND11_VERSION_([A-Z]+)\s+(.*)$", re.MULTILINE +) +VERSION_FILE = Path("pybind11/_version.py") +COMMON_FILE = Path("include/pybind11/detail/common.h") + + +def build_expected_version_hex(matches: Dict[str, str]) -> str: + patch_level_serial = matches["PATCH"] + serial = None + major = int(matches["MAJOR"]) + minor = int(matches["MINOR"]) + flds = patch_level_serial.split(".") + if flds: + patch = int(flds[0]) + if len(flds) == 1: + level = "0" + serial = 0 + elif len(flds) == 2: + level_serial = flds[1] + for level in ("a", "b", "c", "dev"): + if level_serial.startswith(level): + serial = int(level_serial[len(level) :]) + break + if serial is None: + msg = f'Invalid PYBIND11_VERSION_PATCH: "{patch_level_serial}"' + raise RuntimeError(msg) + version_hex_str = f"{major:02x}{minor:02x}{patch:02x}{level[:1]}{serial:x}" + return f"0x{version_hex_str.upper()}" + + +# PYBIND11_GLOBAL_SDIST will build a different sdist, with the python-headers +# files, and the sys.prefix files (CMake and headers). + +global_sdist = os.environ.get("PYBIND11_GLOBAL_SDIST", False) + +setup_py = Path( + "tools/setup_global.py.in" if global_sdist else "tools/setup_main.py.in" +) +extra_cmd = 'cmdclass["sdist"] = SDist\n' + +to_src = ( + (Path("pyproject.toml"), Path("tools/pyproject.toml")), + (Path("setup.py"), setup_py), +) + + +# Read the listed version +loc: Dict[str, str] = {} +code = compile(VERSION_FILE.read_text(encoding="utf-8"), "pybind11/_version.py", "exec") +exec(code, loc) +version = loc["__version__"] + +# Verify that the version matches the one in C++ +matches = dict(VERSION_REGEX.findall(COMMON_FILE.read_text(encoding="utf8"))) +cpp_version = "{MAJOR}.{MINOR}.{PATCH}".format(**matches) +if version != cpp_version: + msg = f"Python version {version} does not match C++ version {cpp_version}!" + raise RuntimeError(msg) + +version_hex = matches.get("HEX", "MISSING") +exp_version_hex = build_expected_version_hex(matches) +if version_hex != exp_version_hex: + msg = f"PYBIND11_VERSION_HEX {version_hex} does not match expected value {exp_version_hex}!" + raise RuntimeError(msg) + + +# TODO: use literals & overload (typing extensions or Python 3.8) +def get_and_replace( + filename: Path, binary: bool = False, **opts: str +) -> Union[bytes, str]: + if binary: + contents = filename.read_bytes() + return string.Template(contents.decode()).substitute(opts).encode() + + return string.Template(filename.read_text()).substitute(opts) + + +# Use our input files instead when making the SDist (and anything that depends +# on it, like a wheel) +class SDist(setuptools.command.sdist.sdist): + def make_release_tree(self, base_dir: str, files: List[str]) -> None: + super().make_release_tree(base_dir, files) + + for to, src in to_src: + txt = get_and_replace(src, binary=True, version=version, extra_cmd="") + + dest = Path(base_dir) / to + + # This is normally linked, so unlink before writing! + dest.unlink() + dest.write_bytes(txt) # type: ignore[arg-type] + + +# Remove the CMake install directory when done +@contextlib.contextmanager +def remove_output(*sources: str) -> Iterator[None]: + try: + yield + finally: + for src in sources: + shutil.rmtree(src) + + +with remove_output("pybind11/include", "pybind11/share"): + # Generate the files if they are not present. + with TemporaryDirectory() as tmpdir: + cmd = ["cmake", "-S", ".", "-B", tmpdir] + [ + "-DCMAKE_INSTALL_PREFIX=pybind11", + "-DBUILD_TESTING=OFF", + "-DPYBIND11_NOPYTHON=ON", + "-Dprefix_for_pc_file=${pcfiledir}/../../", + ] + if "CMAKE_ARGS" in os.environ: + fcommand = [ + c + for c in os.environ["CMAKE_ARGS"].split() + if "DCMAKE_INSTALL_PREFIX" not in c + ] + cmd += fcommand + subprocess.run(cmd, check=True, cwd=DIR, stdout=sys.stdout, stderr=sys.stderr) + subprocess.run( + ["cmake", "--install", tmpdir], + check=True, + cwd=DIR, + stdout=sys.stdout, + stderr=sys.stderr, + ) + + txt = get_and_replace(setup_py, version=version, extra_cmd=extra_cmd) + code = compile(txt, setup_py, "exec") + exec(code, {"SDist": SDist}) diff --git a/third_party/CityFlow/extern/pybind11/tests/CMakeLists.txt b/third_party/CityFlow/extern/pybind11/tests/CMakeLists.txt index e347a2e5c5eef214c7eb1e8a879483c95e858d7c..d37b3df8731043d0e528ef70f7984cb0cec9cd31 100644 --- a/third_party/CityFlow/extern/pybind11/tests/CMakeLists.txt +++ b/third_party/CityFlow/extern/pybind11/tests/CMakeLists.txt @@ -1,589 +1,589 @@ -# CMakeLists.txt -- Build system for the pybind11 test suite -# -# Copyright (c) 2015 Wenzel Jakob -# -# All rights reserved. Use of this source code is governed by a -# BSD-style license that can be found in the LICENSE file. - -cmake_minimum_required(VERSION 3.5) - -# The `cmake_minimum_required(VERSION 3.5...3.27)` syntax does not work with -# some versions of VS that have a patched CMake 3.11. This forces us to emulate -# the behavior using the following workaround: -if(${CMAKE_VERSION} VERSION_LESS 3.27) - cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) -else() - cmake_policy(VERSION 3.27) -endif() - -# Filter out items; print an optional message if any items filtered. This ignores extensions. -# -# Usage: -# pybind11_filter_tests(LISTNAME file1.cpp file2.cpp ... MESSAGE "") -# -macro(pybind11_filter_tests LISTNAME) - cmake_parse_arguments(ARG "" "MESSAGE" "" ${ARGN}) - set(PYBIND11_FILTER_TESTS_FOUND OFF) - # Make a list of the test without any extensions, for easier filtering. - set(_TMP_ACTUAL_LIST "${${LISTNAME}};") # enforce ';' at the end to allow matching last item. - string(REGEX REPLACE "\\.[^.;]*;" ";" LIST_WITHOUT_EXTENSIONS "${_TMP_ACTUAL_LIST}") - foreach(filename IN LISTS ARG_UNPARSED_ARGUMENTS) - string(REGEX REPLACE "\\.[^.]*$" "" filename_no_ext ${filename}) - # Search in the list without extensions. - list(FIND LIST_WITHOUT_EXTENSIONS ${filename_no_ext} _FILE_FOUND) - if(_FILE_FOUND GREATER -1) - list(REMOVE_AT ${LISTNAME} ${_FILE_FOUND}) # And remove from the list with extensions. - list(REMOVE_AT LIST_WITHOUT_EXTENSIONS ${_FILE_FOUND} - )# And our search list, to ensure it is in sync. - set(PYBIND11_FILTER_TESTS_FOUND ON) - endif() - endforeach() - if(PYBIND11_FILTER_TESTS_FOUND AND ARG_MESSAGE) - message(STATUS "${ARG_MESSAGE}") - endif() -endmacro() - -macro(possibly_uninitialized) - foreach(VARNAME ${ARGN}) - if(NOT DEFINED "${VARNAME}") - set("${VARNAME}" "") - endif() - endforeach() -endmacro() - -# Function to add additional targets if any of the provided tests are found. -# Needles; Specifies the test names to look for. -# Additions; Specifies the additional test targets to add when any of the needles are found. -macro(tests_extra_targets needles additions) - # Add the index for this relation to the index extra targets map. - list(LENGTH PYBIND11_TEST_EXTRA_TARGETS PYBIND11_TEST_EXTRA_TARGETS_LEN) - list(APPEND PYBIND11_TEST_EXTRA_TARGETS ${PYBIND11_TEST_EXTRA_TARGETS_LEN}) - # Add the test names to look for, and the associated test target additions. - set(PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${needles}) - set(PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${additions}) -endmacro() - -# New Python support -if(DEFINED Python_EXECUTABLE) - set(PYTHON_EXECUTABLE "${Python_EXECUTABLE}") - set(PYTHON_VERSION "${Python_VERSION}") -endif() - -# There's no harm in including a project in a project -project(pybind11_tests CXX) - -# Access FindCatch and more -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../tools") - -option(PYBIND11_WERROR "Report all warnings as errors" OFF) -option(DOWNLOAD_EIGEN "Download EIGEN (requires CMake 3.11+)" OFF) -option(PYBIND11_CUDA_TESTS "Enable building CUDA tests (requires CMake 3.12+)" OFF) -set(PYBIND11_TEST_OVERRIDE - "" - CACHE STRING "Tests from ;-separated list of *.cpp files will be built instead of all tests") -set(PYBIND11_TEST_FILTER - "" - CACHE STRING "Tests from ;-separated list of *.cpp files will be removed from all tests") - -if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - # We're being loaded directly, i.e. not via add_subdirectory, so make this - # work as its own project and load the pybind11Config to get the tools we need - find_package(pybind11 REQUIRED CONFIG) -endif() - -if(NOT CMAKE_BUILD_TYPE AND NOT DEFINED CMAKE_CONFIGURATION_TYPES) - message(STATUS "Setting tests build type to MinSizeRel as none was specified") - set(CMAKE_BUILD_TYPE - MinSizeRel - CACHE STRING "Choose the type of build." FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" - "RelWithDebInfo") -endif() - -if(PYBIND11_CUDA_TESTS) - enable_language(CUDA) - if(DEFINED CMAKE_CXX_STANDARD) - set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD}) - endif() - set(CMAKE_CUDA_STANDARD_REQUIRED ON) -endif() - -# Full set of test files (you can override these; see below, overrides ignore extension) -# Any test that has no extension is both .py and .cpp, so 'foo' will add 'foo.cpp' and 'foo.py'. -# Any test that has an extension is exclusively that and handled as such. -set(PYBIND11_TEST_FILES - test_async - test_buffers - test_builtin_casters - test_call_policies - test_callbacks - test_chrono - test_class - test_const_name - test_constants_and_functions - test_copy_move - test_custom_type_casters - test_custom_type_setup - test_docstring_options - test_eigen_matrix - test_eigen_tensor - test_enum - test_eval - test_exceptions - test_factory_constructors - test_gil_scoped - test_iostream - test_kwargs_and_defaults - test_local_bindings - test_methods_and_attributes - test_modules - test_multiple_inheritance - test_numpy_array - test_numpy_dtypes - test_numpy_vectorize - test_opaque_types - test_operator_overloading - test_pickling - test_python_multiple_inheritance - test_pytypes - test_sequences_and_iterators - test_smart_ptr - test_stl - test_stl_binders - test_tagbased_polymorphic - test_thread - test_type_caster_pyobject_ptr - test_union - test_unnamed_namespace_a - test_unnamed_namespace_b - test_vector_unique_ptr_member - test_virtual_functions) - -# Invoking cmake with something like: -# cmake -DPYBIND11_TEST_OVERRIDE="test_callbacks.cpp;test_pickling.cpp" .. -# lets you override the tests that get compiled and run. You can restore to all tests with: -# cmake -DPYBIND11_TEST_OVERRIDE= .. -if(PYBIND11_TEST_OVERRIDE) - # Instead of doing a direct override here, we iterate over the overrides without extension and - # match them against entries from the PYBIND11_TEST_FILES, anything that not matches goes into the filter list. - string(REGEX REPLACE "\\.[^.;]*;" ";" TEST_OVERRIDE_NO_EXT "${PYBIND11_TEST_OVERRIDE};") - string(REGEX REPLACE "\\.[^.;]*;" ";" TEST_FILES_NO_EXT "${PYBIND11_TEST_FILES};") - # This allows the override to be done with extensions, preserving backwards compatibility. - foreach(test_name ${TEST_FILES_NO_EXT}) - if(NOT ${test_name} IN_LIST TEST_OVERRIDE_NO_EXT - )# If not in the allowlist, add to be filtered out. - list(APPEND PYBIND11_TEST_FILTER ${test_name}) - endif() - endforeach() -endif() - -# You can also filter tests: -if(PYBIND11_TEST_FILTER) - pybind11_filter_tests(PYBIND11_TEST_FILES ${PYBIND11_TEST_FILTER}) -endif() - -# Skip tests for CUDA check: -# /pybind11/tests/test_constants_and_functions.cpp(125): -# error: incompatible exception specifications -if(PYBIND11_CUDA_TESTS) - pybind11_filter_tests( - PYBIND11_TEST_FILES test_constants_and_functions.cpp MESSAGE - "Skipping test_constants_and_functions due to incompatible exception specifications") -endif() - -# Now that the test filtering is complete, we need to split the list into the test for PYTEST -# and the list for the cpp targets. -set(PYBIND11_CPPTEST_FILES "") -set(PYBIND11_PYTEST_FILES "") - -foreach(test_name ${PYBIND11_TEST_FILES}) - if(test_name MATCHES "\\.py$") # Ends in .py, purely python test. - list(APPEND PYBIND11_PYTEST_FILES ${test_name}) - elseif(test_name MATCHES "\\.cpp$") # Ends in .cpp, purely cpp test. - list(APPEND PYBIND11_CPPTEST_FILES ${test_name}) - elseif(NOT test_name MATCHES "\\.") # No extension specified, assume both, add extension. - list(APPEND PYBIND11_PYTEST_FILES ${test_name}.py) - list(APPEND PYBIND11_CPPTEST_FILES ${test_name}.cpp) - else() - message(WARNING "Unhanded test extension in test: ${test_name}") - endif() -endforeach() -set(PYBIND11_TEST_FILES ${PYBIND11_CPPTEST_FILES}) -list(SORT PYBIND11_PYTEST_FILES) - -# Contains the set of test files that require pybind11_cross_module_tests to be -# built; if none of these are built (i.e. because TEST_OVERRIDE is used and -# doesn't include them) the second module doesn't get built. -tests_extra_targets("test_exceptions.py;test_local_bindings.py;test_stl.py;test_stl_binders.py" - "pybind11_cross_module_tests") - -# And add additional targets for other tests. -tests_extra_targets("test_exceptions.py" "cross_module_interleaved_error_already_set") -tests_extra_targets("test_gil_scoped.py" "cross_module_gil_utils") - -set(PYBIND11_EIGEN_REPO - "https://gitlab.com/libeigen/eigen.git" - CACHE STRING "Eigen repository to use for tests") -# Always use a hash for reconfigure speed and security reasons -# Include the version number for pretty printing (keep in sync) -set(PYBIND11_EIGEN_VERSION_AND_HASH - "3.4.0;929bc0e191d0927b1735b9a1ddc0e8b77e3a25ec" - CACHE STRING "Eigen version to use for tests, format: VERSION;HASH") - -list(GET PYBIND11_EIGEN_VERSION_AND_HASH 0 PYBIND11_EIGEN_VERSION_STRING) -list(GET PYBIND11_EIGEN_VERSION_AND_HASH 1 PYBIND11_EIGEN_VERSION_HASH) - -# Check if Eigen is available; if not, remove from PYBIND11_TEST_FILES (but -# keep it in PYBIND11_PYTEST_FILES, so that we get the "eigen is not installed" -# skip message). -list(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I) -if(PYBIND11_TEST_FILES_EIGEN_I EQUAL -1) - list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) -endif() -if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) - # Try loading via newer Eigen's Eigen3Config first (bypassing tools/FindEigen3.cmake). - # Eigen 3.3.1+ exports a cmake 3.0+ target for handling dependency requirements, but also - # produces a fatal error if loaded from a pre-3.0 cmake. - if(DOWNLOAD_EIGEN) - if(CMAKE_VERSION VERSION_LESS 3.11) - message(FATAL_ERROR "CMake 3.11+ required when using DOWNLOAD_EIGEN") - endif() - - include(FetchContent) - FetchContent_Declare( - eigen - GIT_REPOSITORY "${PYBIND11_EIGEN_REPO}" - GIT_TAG "${PYBIND11_EIGEN_VERSION_HASH}") - - FetchContent_GetProperties(eigen) - if(NOT eigen_POPULATED) - message( - STATUS - "Downloading Eigen ${PYBIND11_EIGEN_VERSION_STRING} (${PYBIND11_EIGEN_VERSION_HASH}) from ${PYBIND11_EIGEN_REPO}" - ) - FetchContent_Populate(eigen) - endif() - - set(EIGEN3_INCLUDE_DIR ${eigen_SOURCE_DIR}) - set(EIGEN3_FOUND TRUE) - # When getting locally, the version is not visible from a superprojet, - # so just force it. - set(EIGEN3_VERSION "${PYBIND11_EIGEN_VERSION_STRING}") - - else() - find_package(Eigen3 3.2.7 QUIET CONFIG) - - if(NOT EIGEN3_FOUND) - # Couldn't load via target, so fall back to allowing module mode finding, which will pick up - # tools/FindEigen3.cmake - find_package(Eigen3 3.2.7 QUIET) - endif() - endif() - - if(EIGEN3_FOUND) - if(NOT TARGET Eigen3::Eigen) - add_library(Eigen3::Eigen IMPORTED INTERFACE) - set_property(TARGET Eigen3::Eigen PROPERTY INTERFACE_INCLUDE_DIRECTORIES - "${EIGEN3_INCLUDE_DIR}") - endif() - - # Eigen 3.3.1+ cmake sets EIGEN3_VERSION_STRING (and hard codes the version when installed - # rather than looking it up in the cmake script); older versions, and the - # tools/FindEigen3.cmake, set EIGEN3_VERSION instead. - if(NOT EIGEN3_VERSION AND EIGEN3_VERSION_STRING) - set(EIGEN3_VERSION ${EIGEN3_VERSION_STRING}) - endif() - message(STATUS "Building tests with Eigen v${EIGEN3_VERSION}") - - if(NOT (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)) - tests_extra_targets("test_eigen_tensor.py" "eigen_tensor_avoid_stl_array") - endif() - - else() - list(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I) - if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) - list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) - endif() - - list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) - if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) - list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) - endif() - message( - STATUS "Building tests WITHOUT Eigen, use -DDOWNLOAD_EIGEN=ON on CMake 3.11+ to download") - endif() -endif() - -# Some code doesn't support gcc 4 -if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) - list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) - if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) - list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) - endif() -endif() - -# Optional dependency for some tests (boost::variant is only supported with version >= 1.56) -find_package(Boost 1.56) - -if(Boost_FOUND) - if(NOT TARGET Boost::headers) - add_library(Boost::headers IMPORTED INTERFACE) - if(TARGET Boost::boost) - # Classic FindBoost - set_property(TARGET Boost::boost PROPERTY INTERFACE_LINK_LIBRARIES Boost::boost) - else() - # Very old FindBoost, or newer Boost than CMake in older CMakes - set_property(TARGET Boost::headers PROPERTY INTERFACE_INCLUDE_DIRECTORIES - ${Boost_INCLUDE_DIRS}) - endif() - endif() -endif() - -# Check if we need to add -lstdc++fs or -lc++fs or nothing -if(DEFINED CMAKE_CXX_STANDARD AND CMAKE_CXX_STANDARD LESS 17) - set(STD_FS_NO_LIB_NEEDED TRUE) -elseif(MSVC) - set(STD_FS_NO_LIB_NEEDED TRUE) -else() - file( - WRITE ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - "#include \nint main(int argc, char ** argv) {\n std::filesystem::path p(argv[0]);\n return p.string().length();\n}" - ) - try_compile( - STD_FS_NO_LIB_NEEDED ${CMAKE_CURRENT_BINARY_DIR} - SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - COMPILE_DEFINITIONS -std=c++17) - try_compile( - STD_FS_NEEDS_STDCXXFS ${CMAKE_CURRENT_BINARY_DIR} - SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - COMPILE_DEFINITIONS -std=c++17 - LINK_LIBRARIES stdc++fs) - try_compile( - STD_FS_NEEDS_CXXFS ${CMAKE_CURRENT_BINARY_DIR} - SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp - COMPILE_DEFINITIONS -std=c++17 - LINK_LIBRARIES c++fs) -endif() - -if(${STD_FS_NEEDS_STDCXXFS}) - set(STD_FS_LIB stdc++fs) -elseif(${STD_FS_NEEDS_CXXFS}) - set(STD_FS_LIB c++fs) -elseif(${STD_FS_NO_LIB_NEEDED}) - set(STD_FS_LIB "") -else() - message(WARNING "Unknown C++17 compiler - not passing -lstdc++fs") - set(STD_FS_LIB "") -endif() - -# Compile with compiler warnings turned on -function(pybind11_enable_warnings target_name) - if(MSVC) - target_compile_options(${target_name} PRIVATE /W4 /wd4189) - elseif(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Intel|Clang)" AND NOT PYBIND11_CUDA_TESTS) - target_compile_options( - ${target_name} - PRIVATE -Wall - -Wextra - -Wconversion - -Wcast-qual - -Wdeprecated - -Wundef - -Wnon-virtual-dtor) - endif() - - if(PYBIND11_WERROR) - if(MSVC) - target_compile_options(${target_name} PRIVATE /WX) - elseif(PYBIND11_CUDA_TESTS) - target_compile_options(${target_name} PRIVATE "SHELL:-Werror all-warnings") - elseif(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang|IntelLLVM)") - target_compile_options(${target_name} PRIVATE -Werror) - elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Intel") - if(CMAKE_CXX_STANDARD EQUAL 17) # See PR #3570 - target_compile_options(${target_name} PRIVATE -Wno-conversion) - endif() - target_compile_options( - ${target_name} - PRIVATE - -Werror-all - # "Inlining inhibited by limit max-size", "Inlining inhibited by limit max-total-size" - -diag-disable 11074,11076) - endif() - endif() -endfunction() - -set(test_targets pybind11_tests) - -# Check if any tests need extra targets by iterating through the mappings registered. -foreach(i ${PYBIND11_TEST_EXTRA_TARGETS}) - foreach(needle ${PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${i}}) - if(needle IN_LIST PYBIND11_PYTEST_FILES) - # Add all the additional targets to the test list. List join in newer cmake. - foreach(extra_target ${PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${i}}) - list(APPEND test_targets ${extra_target}) - endforeach() - break() # Breaks out of the needle search, continues with the next mapping. - endif() - endforeach() -endforeach() - -# Support CUDA testing by forcing the target file to compile with NVCC -if(PYBIND11_CUDA_TESTS) - set_property(SOURCE ${PYBIND11_TEST_FILES} PROPERTY LANGUAGE CUDA) -endif() - -foreach(target ${test_targets}) - set(test_files ${PYBIND11_TEST_FILES}) - if(NOT "${target}" STREQUAL "pybind11_tests") - set(test_files "") - endif() - - # Support CUDA testing by forcing the target file to compile with NVCC - if(PYBIND11_CUDA_TESTS) - set_property(SOURCE ${target}.cpp PROPERTY LANGUAGE CUDA) - endif() - - # Create the binding library - pybind11_add_module(${target} THIN_LTO ${target}.cpp ${test_files} ${PYBIND11_HEADERS}) - pybind11_enable_warnings(${target}) - - if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) - get_property( - suffix - TARGET ${target} - PROPERTY SUFFIX) - set(source_output "${CMAKE_CURRENT_SOURCE_DIR}/${target}${suffix}") - if(suffix AND EXISTS "${source_output}") - message(WARNING "Output file also in source directory; " - "please remove to avoid confusion: ${source_output}") - endif() - endif() - - if(MSVC) - target_compile_options(${target} PRIVATE /utf-8) - endif() - - if(EIGEN3_FOUND) - target_link_libraries(${target} PRIVATE Eigen3::Eigen) - target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_EIGEN) - endif() - - if(Boost_FOUND) - target_link_libraries(${target} PRIVATE Boost::headers) - target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_BOOST) - endif() - - target_link_libraries(${target} PRIVATE ${STD_FS_LIB}) - - # Always write the output file directly into the 'tests' directory (even on MSVC) - if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) - set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_CURRENT_BINARY_DIR}") - - if(DEFINED CMAKE_CONFIGURATION_TYPES) - foreach(config ${CMAKE_CONFIGURATION_TYPES}) - string(TOUPPER ${config} config) - set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${config} - "${CMAKE_CURRENT_BINARY_DIR}") - endforeach() - endif() - endif() -endforeach() - -# Provide nice organisation in IDEs -if(NOT CMAKE_VERSION VERSION_LESS 3.8) - source_group( - TREE "${CMAKE_CURRENT_SOURCE_DIR}/../include" - PREFIX "Header Files" - FILES ${PYBIND11_HEADERS}) -endif() - -# Make sure pytest is found or produce a warning -pybind11_find_import(pytest VERSION 3.1) - -if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) - # This is not used later in the build, so it's okay to regenerate each time. - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/pytest.ini" "${CMAKE_CURRENT_BINARY_DIR}/pytest.ini" - COPYONLY) - file(APPEND "${CMAKE_CURRENT_BINARY_DIR}/pytest.ini" - "\ntestpaths = \"${CMAKE_CURRENT_SOURCE_DIR}\"") - -endif() - -# cmake 3.12 added list(transform prepend -# but we can't use it yet -string(REPLACE "test_" "${CMAKE_CURRENT_SOURCE_DIR}/test_" PYBIND11_ABS_PYTEST_FILES - "${PYBIND11_PYTEST_FILES}") - -set(PYBIND11_TEST_PREFIX_COMMAND - "" - CACHE STRING "Put this before pytest, use for checkers and such") - -set(PYBIND11_PYTEST_ARGS - "" - CACHE STRING "Extra arguments for pytest") - -# A single command to compile and run the tests -add_custom_target( - pytest - COMMAND ${PYBIND11_TEST_PREFIX_COMMAND} ${PYTHON_EXECUTABLE} -m pytest - ${PYBIND11_ABS_PYTEST_FILES} ${PYBIND11_PYTEST_ARGS} - DEPENDS ${test_targets} - WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" - USES_TERMINAL) - -if(PYBIND11_TEST_OVERRIDE) - add_custom_command( - TARGET pytest - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E echo - "Note: not all tests run: -DPYBIND11_TEST_OVERRIDE is in effect") -endif() - -# cmake-format: off -add_custom_target( - memcheck - COMMAND - PYTHONMALLOC=malloc - valgrind - --leak-check=full - --show-leak-kinds=definite,indirect - --errors-for-leak-kinds=definite,indirect - --error-exitcode=1 - --read-var-info=yes - --track-origins=yes - --suppressions="${CMAKE_CURRENT_SOURCE_DIR}/valgrind-python.supp" - --suppressions="${CMAKE_CURRENT_SOURCE_DIR}/valgrind-numpy-scipy.supp" - --gen-suppressions=all - ${PYTHON_EXECUTABLE} -m pytest ${PYBIND11_ABS_PYTEST_FILES} - DEPENDS ${test_targets} - WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" - USES_TERMINAL) -# cmake-format: on - -# Add a check target to run all the tests, starting with pytest (we add dependencies to this below) -add_custom_target(check DEPENDS pytest) - -# The remaining tests only apply when being built as part of the pybind11 project, but not if the -# tests are being built independently. -if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - return() -endif() - -# Add a post-build comment to show the primary test suite .so size and, if a previous size, compare it: -add_custom_command( - TARGET pybind11_tests - POST_BUILD - COMMAND - ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/../tools/libsize.py - $ - ${CMAKE_CURRENT_BINARY_DIR}/sosize-$.txt) - -if(NOT PYBIND11_CUDA_TESTS) - # Test embedding the interpreter. Provides the `cpptest` target. - add_subdirectory(test_embed) - - # Test CMake build using functions and targets from subdirectory or installed location - add_subdirectory(test_cmake_build) -endif() +# CMakeLists.txt -- Build system for the pybind11 test suite +# +# Copyright (c) 2015 Wenzel Jakob +# +# All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +cmake_minimum_required(VERSION 3.5) + +# The `cmake_minimum_required(VERSION 3.5...3.27)` syntax does not work with +# some versions of VS that have a patched CMake 3.11. This forces us to emulate +# the behavior using the following workaround: +if(${CMAKE_VERSION} VERSION_LESS 3.27) + cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) +else() + cmake_policy(VERSION 3.27) +endif() + +# Filter out items; print an optional message if any items filtered. This ignores extensions. +# +# Usage: +# pybind11_filter_tests(LISTNAME file1.cpp file2.cpp ... MESSAGE "") +# +macro(pybind11_filter_tests LISTNAME) + cmake_parse_arguments(ARG "" "MESSAGE" "" ${ARGN}) + set(PYBIND11_FILTER_TESTS_FOUND OFF) + # Make a list of the test without any extensions, for easier filtering. + set(_TMP_ACTUAL_LIST "${${LISTNAME}};") # enforce ';' at the end to allow matching last item. + string(REGEX REPLACE "\\.[^.;]*;" ";" LIST_WITHOUT_EXTENSIONS "${_TMP_ACTUAL_LIST}") + foreach(filename IN LISTS ARG_UNPARSED_ARGUMENTS) + string(REGEX REPLACE "\\.[^.]*$" "" filename_no_ext ${filename}) + # Search in the list without extensions. + list(FIND LIST_WITHOUT_EXTENSIONS ${filename_no_ext} _FILE_FOUND) + if(_FILE_FOUND GREATER -1) + list(REMOVE_AT ${LISTNAME} ${_FILE_FOUND}) # And remove from the list with extensions. + list(REMOVE_AT LIST_WITHOUT_EXTENSIONS ${_FILE_FOUND} + )# And our search list, to ensure it is in sync. + set(PYBIND11_FILTER_TESTS_FOUND ON) + endif() + endforeach() + if(PYBIND11_FILTER_TESTS_FOUND AND ARG_MESSAGE) + message(STATUS "${ARG_MESSAGE}") + endif() +endmacro() + +macro(possibly_uninitialized) + foreach(VARNAME ${ARGN}) + if(NOT DEFINED "${VARNAME}") + set("${VARNAME}" "") + endif() + endforeach() +endmacro() + +# Function to add additional targets if any of the provided tests are found. +# Needles; Specifies the test names to look for. +# Additions; Specifies the additional test targets to add when any of the needles are found. +macro(tests_extra_targets needles additions) + # Add the index for this relation to the index extra targets map. + list(LENGTH PYBIND11_TEST_EXTRA_TARGETS PYBIND11_TEST_EXTRA_TARGETS_LEN) + list(APPEND PYBIND11_TEST_EXTRA_TARGETS ${PYBIND11_TEST_EXTRA_TARGETS_LEN}) + # Add the test names to look for, and the associated test target additions. + set(PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${needles}) + set(PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${additions}) +endmacro() + +# New Python support +if(DEFINED Python_EXECUTABLE) + set(PYTHON_EXECUTABLE "${Python_EXECUTABLE}") + set(PYTHON_VERSION "${Python_VERSION}") +endif() + +# There's no harm in including a project in a project +project(pybind11_tests CXX) + +# Access FindCatch and more +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../tools") + +option(PYBIND11_WERROR "Report all warnings as errors" OFF) +option(DOWNLOAD_EIGEN "Download EIGEN (requires CMake 3.11+)" OFF) +option(PYBIND11_CUDA_TESTS "Enable building CUDA tests (requires CMake 3.12+)" OFF) +set(PYBIND11_TEST_OVERRIDE + "" + CACHE STRING "Tests from ;-separated list of *.cpp files will be built instead of all tests") +set(PYBIND11_TEST_FILTER + "" + CACHE STRING "Tests from ;-separated list of *.cpp files will be removed from all tests") + +if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + # We're being loaded directly, i.e. not via add_subdirectory, so make this + # work as its own project and load the pybind11Config to get the tools we need + find_package(pybind11 REQUIRED CONFIG) +endif() + +if(NOT CMAKE_BUILD_TYPE AND NOT DEFINED CMAKE_CONFIGURATION_TYPES) + message(STATUS "Setting tests build type to MinSizeRel as none was specified") + set(CMAKE_BUILD_TYPE + MinSizeRel + CACHE STRING "Choose the type of build." FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" + "RelWithDebInfo") +endif() + +if(PYBIND11_CUDA_TESTS) + enable_language(CUDA) + if(DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD}) + endif() + set(CMAKE_CUDA_STANDARD_REQUIRED ON) +endif() + +# Full set of test files (you can override these; see below, overrides ignore extension) +# Any test that has no extension is both .py and .cpp, so 'foo' will add 'foo.cpp' and 'foo.py'. +# Any test that has an extension is exclusively that and handled as such. +set(PYBIND11_TEST_FILES + test_async + test_buffers + test_builtin_casters + test_call_policies + test_callbacks + test_chrono + test_class + test_const_name + test_constants_and_functions + test_copy_move + test_custom_type_casters + test_custom_type_setup + test_docstring_options + test_eigen_matrix + test_eigen_tensor + test_enum + test_eval + test_exceptions + test_factory_constructors + test_gil_scoped + test_iostream + test_kwargs_and_defaults + test_local_bindings + test_methods_and_attributes + test_modules + test_multiple_inheritance + test_numpy_array + test_numpy_dtypes + test_numpy_vectorize + test_opaque_types + test_operator_overloading + test_pickling + test_python_multiple_inheritance + test_pytypes + test_sequences_and_iterators + test_smart_ptr + test_stl + test_stl_binders + test_tagbased_polymorphic + test_thread + test_type_caster_pyobject_ptr + test_union + test_unnamed_namespace_a + test_unnamed_namespace_b + test_vector_unique_ptr_member + test_virtual_functions) + +# Invoking cmake with something like: +# cmake -DPYBIND11_TEST_OVERRIDE="test_callbacks.cpp;test_pickling.cpp" .. +# lets you override the tests that get compiled and run. You can restore to all tests with: +# cmake -DPYBIND11_TEST_OVERRIDE= .. +if(PYBIND11_TEST_OVERRIDE) + # Instead of doing a direct override here, we iterate over the overrides without extension and + # match them against entries from the PYBIND11_TEST_FILES, anything that not matches goes into the filter list. + string(REGEX REPLACE "\\.[^.;]*;" ";" TEST_OVERRIDE_NO_EXT "${PYBIND11_TEST_OVERRIDE};") + string(REGEX REPLACE "\\.[^.;]*;" ";" TEST_FILES_NO_EXT "${PYBIND11_TEST_FILES};") + # This allows the override to be done with extensions, preserving backwards compatibility. + foreach(test_name ${TEST_FILES_NO_EXT}) + if(NOT ${test_name} IN_LIST TEST_OVERRIDE_NO_EXT + )# If not in the allowlist, add to be filtered out. + list(APPEND PYBIND11_TEST_FILTER ${test_name}) + endif() + endforeach() +endif() + +# You can also filter tests: +if(PYBIND11_TEST_FILTER) + pybind11_filter_tests(PYBIND11_TEST_FILES ${PYBIND11_TEST_FILTER}) +endif() + +# Skip tests for CUDA check: +# /pybind11/tests/test_constants_and_functions.cpp(125): +# error: incompatible exception specifications +if(PYBIND11_CUDA_TESTS) + pybind11_filter_tests( + PYBIND11_TEST_FILES test_constants_and_functions.cpp MESSAGE + "Skipping test_constants_and_functions due to incompatible exception specifications") +endif() + +# Now that the test filtering is complete, we need to split the list into the test for PYTEST +# and the list for the cpp targets. +set(PYBIND11_CPPTEST_FILES "") +set(PYBIND11_PYTEST_FILES "") + +foreach(test_name ${PYBIND11_TEST_FILES}) + if(test_name MATCHES "\\.py$") # Ends in .py, purely python test. + list(APPEND PYBIND11_PYTEST_FILES ${test_name}) + elseif(test_name MATCHES "\\.cpp$") # Ends in .cpp, purely cpp test. + list(APPEND PYBIND11_CPPTEST_FILES ${test_name}) + elseif(NOT test_name MATCHES "\\.") # No extension specified, assume both, add extension. + list(APPEND PYBIND11_PYTEST_FILES ${test_name}.py) + list(APPEND PYBIND11_CPPTEST_FILES ${test_name}.cpp) + else() + message(WARNING "Unhanded test extension in test: ${test_name}") + endif() +endforeach() +set(PYBIND11_TEST_FILES ${PYBIND11_CPPTEST_FILES}) +list(SORT PYBIND11_PYTEST_FILES) + +# Contains the set of test files that require pybind11_cross_module_tests to be +# built; if none of these are built (i.e. because TEST_OVERRIDE is used and +# doesn't include them) the second module doesn't get built. +tests_extra_targets("test_exceptions.py;test_local_bindings.py;test_stl.py;test_stl_binders.py" + "pybind11_cross_module_tests") + +# And add additional targets for other tests. +tests_extra_targets("test_exceptions.py" "cross_module_interleaved_error_already_set") +tests_extra_targets("test_gil_scoped.py" "cross_module_gil_utils") + +set(PYBIND11_EIGEN_REPO + "https://gitlab.com/libeigen/eigen.git" + CACHE STRING "Eigen repository to use for tests") +# Always use a hash for reconfigure speed and security reasons +# Include the version number for pretty printing (keep in sync) +set(PYBIND11_EIGEN_VERSION_AND_HASH + "3.4.0;929bc0e191d0927b1735b9a1ddc0e8b77e3a25ec" + CACHE STRING "Eigen version to use for tests, format: VERSION;HASH") + +list(GET PYBIND11_EIGEN_VERSION_AND_HASH 0 PYBIND11_EIGEN_VERSION_STRING) +list(GET PYBIND11_EIGEN_VERSION_AND_HASH 1 PYBIND11_EIGEN_VERSION_HASH) + +# Check if Eigen is available; if not, remove from PYBIND11_TEST_FILES (but +# keep it in PYBIND11_PYTEST_FILES, so that we get the "eigen is not installed" +# skip message). +list(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I) +if(PYBIND11_TEST_FILES_EIGEN_I EQUAL -1) + list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) +endif() +if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) + # Try loading via newer Eigen's Eigen3Config first (bypassing tools/FindEigen3.cmake). + # Eigen 3.3.1+ exports a cmake 3.0+ target for handling dependency requirements, but also + # produces a fatal error if loaded from a pre-3.0 cmake. + if(DOWNLOAD_EIGEN) + if(CMAKE_VERSION VERSION_LESS 3.11) + message(FATAL_ERROR "CMake 3.11+ required when using DOWNLOAD_EIGEN") + endif() + + include(FetchContent) + FetchContent_Declare( + eigen + GIT_REPOSITORY "${PYBIND11_EIGEN_REPO}" + GIT_TAG "${PYBIND11_EIGEN_VERSION_HASH}") + + FetchContent_GetProperties(eigen) + if(NOT eigen_POPULATED) + message( + STATUS + "Downloading Eigen ${PYBIND11_EIGEN_VERSION_STRING} (${PYBIND11_EIGEN_VERSION_HASH}) from ${PYBIND11_EIGEN_REPO}" + ) + FetchContent_Populate(eigen) + endif() + + set(EIGEN3_INCLUDE_DIR ${eigen_SOURCE_DIR}) + set(EIGEN3_FOUND TRUE) + # When getting locally, the version is not visible from a superprojet, + # so just force it. + set(EIGEN3_VERSION "${PYBIND11_EIGEN_VERSION_STRING}") + + else() + find_package(Eigen3 3.2.7 QUIET CONFIG) + + if(NOT EIGEN3_FOUND) + # Couldn't load via target, so fall back to allowing module mode finding, which will pick up + # tools/FindEigen3.cmake + find_package(Eigen3 3.2.7 QUIET) + endif() + endif() + + if(EIGEN3_FOUND) + if(NOT TARGET Eigen3::Eigen) + add_library(Eigen3::Eigen IMPORTED INTERFACE) + set_property(TARGET Eigen3::Eigen PROPERTY INTERFACE_INCLUDE_DIRECTORIES + "${EIGEN3_INCLUDE_DIR}") + endif() + + # Eigen 3.3.1+ cmake sets EIGEN3_VERSION_STRING (and hard codes the version when installed + # rather than looking it up in the cmake script); older versions, and the + # tools/FindEigen3.cmake, set EIGEN3_VERSION instead. + if(NOT EIGEN3_VERSION AND EIGEN3_VERSION_STRING) + set(EIGEN3_VERSION ${EIGEN3_VERSION_STRING}) + endif() + message(STATUS "Building tests with Eigen v${EIGEN3_VERSION}") + + if(NOT (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)) + tests_extra_targets("test_eigen_tensor.py" "eigen_tensor_avoid_stl_array") + endif() + + else() + list(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I) + if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) + list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) + endif() + + list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) + if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) + list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) + endif() + message( + STATUS "Building tests WITHOUT Eigen, use -DDOWNLOAD_EIGEN=ON on CMake 3.11+ to download") + endif() +endif() + +# Some code doesn't support gcc 4 +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) + list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I) + if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1) + list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I}) + endif() +endif() + +# Optional dependency for some tests (boost::variant is only supported with version >= 1.56) +find_package(Boost 1.56) + +if(Boost_FOUND) + if(NOT TARGET Boost::headers) + add_library(Boost::headers IMPORTED INTERFACE) + if(TARGET Boost::boost) + # Classic FindBoost + set_property(TARGET Boost::boost PROPERTY INTERFACE_LINK_LIBRARIES Boost::boost) + else() + # Very old FindBoost, or newer Boost than CMake in older CMakes + set_property(TARGET Boost::headers PROPERTY INTERFACE_INCLUDE_DIRECTORIES + ${Boost_INCLUDE_DIRS}) + endif() + endif() +endif() + +# Check if we need to add -lstdc++fs or -lc++fs or nothing +if(DEFINED CMAKE_CXX_STANDARD AND CMAKE_CXX_STANDARD LESS 17) + set(STD_FS_NO_LIB_NEEDED TRUE) +elseif(MSVC) + set(STD_FS_NO_LIB_NEEDED TRUE) +else() + file( + WRITE ${CMAKE_CURRENT_BINARY_DIR}/main.cpp + "#include \nint main(int argc, char ** argv) {\n std::filesystem::path p(argv[0]);\n return p.string().length();\n}" + ) + try_compile( + STD_FS_NO_LIB_NEEDED ${CMAKE_CURRENT_BINARY_DIR} + SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp + COMPILE_DEFINITIONS -std=c++17) + try_compile( + STD_FS_NEEDS_STDCXXFS ${CMAKE_CURRENT_BINARY_DIR} + SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp + COMPILE_DEFINITIONS -std=c++17 + LINK_LIBRARIES stdc++fs) + try_compile( + STD_FS_NEEDS_CXXFS ${CMAKE_CURRENT_BINARY_DIR} + SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp + COMPILE_DEFINITIONS -std=c++17 + LINK_LIBRARIES c++fs) +endif() + +if(${STD_FS_NEEDS_STDCXXFS}) + set(STD_FS_LIB stdc++fs) +elseif(${STD_FS_NEEDS_CXXFS}) + set(STD_FS_LIB c++fs) +elseif(${STD_FS_NO_LIB_NEEDED}) + set(STD_FS_LIB "") +else() + message(WARNING "Unknown C++17 compiler - not passing -lstdc++fs") + set(STD_FS_LIB "") +endif() + +# Compile with compiler warnings turned on +function(pybind11_enable_warnings target_name) + if(MSVC) + target_compile_options(${target_name} PRIVATE /W4 /wd4189) + elseif(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Intel|Clang)" AND NOT PYBIND11_CUDA_TESTS) + target_compile_options( + ${target_name} + PRIVATE -Wall + -Wextra + -Wconversion + -Wcast-qual + -Wdeprecated + -Wundef + -Wnon-virtual-dtor) + endif() + + if(PYBIND11_WERROR) + if(MSVC) + target_compile_options(${target_name} PRIVATE /WX) + elseif(PYBIND11_CUDA_TESTS) + target_compile_options(${target_name} PRIVATE "SHELL:-Werror all-warnings") + elseif(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang|IntelLLVM)") + target_compile_options(${target_name} PRIVATE -Werror) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Intel") + if(CMAKE_CXX_STANDARD EQUAL 17) # See PR #3570 + target_compile_options(${target_name} PRIVATE -Wno-conversion) + endif() + target_compile_options( + ${target_name} + PRIVATE + -Werror-all + # "Inlining inhibited by limit max-size", "Inlining inhibited by limit max-total-size" + -diag-disable 11074,11076) + endif() + endif() +endfunction() + +set(test_targets pybind11_tests) + +# Check if any tests need extra targets by iterating through the mappings registered. +foreach(i ${PYBIND11_TEST_EXTRA_TARGETS}) + foreach(needle ${PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${i}}) + if(needle IN_LIST PYBIND11_PYTEST_FILES) + # Add all the additional targets to the test list. List join in newer cmake. + foreach(extra_target ${PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${i}}) + list(APPEND test_targets ${extra_target}) + endforeach() + break() # Breaks out of the needle search, continues with the next mapping. + endif() + endforeach() +endforeach() + +# Support CUDA testing by forcing the target file to compile with NVCC +if(PYBIND11_CUDA_TESTS) + set_property(SOURCE ${PYBIND11_TEST_FILES} PROPERTY LANGUAGE CUDA) +endif() + +foreach(target ${test_targets}) + set(test_files ${PYBIND11_TEST_FILES}) + if(NOT "${target}" STREQUAL "pybind11_tests") + set(test_files "") + endif() + + # Support CUDA testing by forcing the target file to compile with NVCC + if(PYBIND11_CUDA_TESTS) + set_property(SOURCE ${target}.cpp PROPERTY LANGUAGE CUDA) + endif() + + # Create the binding library + pybind11_add_module(${target} THIN_LTO ${target}.cpp ${test_files} ${PYBIND11_HEADERS}) + pybind11_enable_warnings(${target}) + + if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) + get_property( + suffix + TARGET ${target} + PROPERTY SUFFIX) + set(source_output "${CMAKE_CURRENT_SOURCE_DIR}/${target}${suffix}") + if(suffix AND EXISTS "${source_output}") + message(WARNING "Output file also in source directory; " + "please remove to avoid confusion: ${source_output}") + endif() + endif() + + if(MSVC) + target_compile_options(${target} PRIVATE /utf-8) + endif() + + if(EIGEN3_FOUND) + target_link_libraries(${target} PRIVATE Eigen3::Eigen) + target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_EIGEN) + endif() + + if(Boost_FOUND) + target_link_libraries(${target} PRIVATE Boost::headers) + target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_BOOST) + endif() + + target_link_libraries(${target} PRIVATE ${STD_FS_LIB}) + + # Always write the output file directly into the 'tests' directory (even on MSVC) + if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) + set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY + "${CMAKE_CURRENT_BINARY_DIR}") + + if(DEFINED CMAKE_CONFIGURATION_TYPES) + foreach(config ${CMAKE_CONFIGURATION_TYPES}) + string(TOUPPER ${config} config) + set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${config} + "${CMAKE_CURRENT_BINARY_DIR}") + endforeach() + endif() + endif() +endforeach() + +# Provide nice organisation in IDEs +if(NOT CMAKE_VERSION VERSION_LESS 3.8) + source_group( + TREE "${CMAKE_CURRENT_SOURCE_DIR}/../include" + PREFIX "Header Files" + FILES ${PYBIND11_HEADERS}) +endif() + +# Make sure pytest is found or produce a warning +pybind11_find_import(pytest VERSION 3.1) + +if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) + # This is not used later in the build, so it's okay to regenerate each time. + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/pytest.ini" "${CMAKE_CURRENT_BINARY_DIR}/pytest.ini" + COPYONLY) + file(APPEND "${CMAKE_CURRENT_BINARY_DIR}/pytest.ini" + "\ntestpaths = \"${CMAKE_CURRENT_SOURCE_DIR}\"") + +endif() + +# cmake 3.12 added list(transform prepend +# but we can't use it yet +string(REPLACE "test_" "${CMAKE_CURRENT_SOURCE_DIR}/test_" PYBIND11_ABS_PYTEST_FILES + "${PYBIND11_PYTEST_FILES}") + +set(PYBIND11_TEST_PREFIX_COMMAND + "" + CACHE STRING "Put this before pytest, use for checkers and such") + +set(PYBIND11_PYTEST_ARGS + "" + CACHE STRING "Extra arguments for pytest") + +# A single command to compile and run the tests +add_custom_target( + pytest + COMMAND ${PYBIND11_TEST_PREFIX_COMMAND} ${PYTHON_EXECUTABLE} -m pytest + ${PYBIND11_ABS_PYTEST_FILES} ${PYBIND11_PYTEST_ARGS} + DEPENDS ${test_targets} + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + USES_TERMINAL) + +if(PYBIND11_TEST_OVERRIDE) + add_custom_command( + TARGET pytest + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E echo + "Note: not all tests run: -DPYBIND11_TEST_OVERRIDE is in effect") +endif() + +# cmake-format: off +add_custom_target( + memcheck + COMMAND + PYTHONMALLOC=malloc + valgrind + --leak-check=full + --show-leak-kinds=definite,indirect + --errors-for-leak-kinds=definite,indirect + --error-exitcode=1 + --read-var-info=yes + --track-origins=yes + --suppressions="${CMAKE_CURRENT_SOURCE_DIR}/valgrind-python.supp" + --suppressions="${CMAKE_CURRENT_SOURCE_DIR}/valgrind-numpy-scipy.supp" + --gen-suppressions=all + ${PYTHON_EXECUTABLE} -m pytest ${PYBIND11_ABS_PYTEST_FILES} + DEPENDS ${test_targets} + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + USES_TERMINAL) +# cmake-format: on + +# Add a check target to run all the tests, starting with pytest (we add dependencies to this below) +add_custom_target(check DEPENDS pytest) + +# The remaining tests only apply when being built as part of the pybind11 project, but not if the +# tests are being built independently. +if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + return() +endif() + +# Add a post-build comment to show the primary test suite .so size and, if a previous size, compare it: +add_custom_command( + TARGET pybind11_tests + POST_BUILD + COMMAND + ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/../tools/libsize.py + $ + ${CMAKE_CURRENT_BINARY_DIR}/sosize-$.txt) + +if(NOT PYBIND11_CUDA_TESTS) + # Test embedding the interpreter. Provides the `cpptest` target. + add_subdirectory(test_embed) + + # Test CMake build using functions and targets from subdirectory or installed location + add_subdirectory(test_cmake_build) +endif() diff --git a/third_party/CityFlow/extern/pybind11/tests/conftest.py b/third_party/CityFlow/extern/pybind11/tests/conftest.py index 8ebc702224599bde0c42a59c615c5fbfbefee7d8..16a534790e47c11b9245962821c30506bc893aef 100644 --- a/third_party/CityFlow/extern/pybind11/tests/conftest.py +++ b/third_party/CityFlow/extern/pybind11/tests/conftest.py @@ -1,222 +1,222 @@ -"""pytest configuration - -Extends output capture as needed by pybind11: ignore constructors, optional unordered lines. -Adds docstring and exceptions message sanitizers. -""" - -import contextlib -import difflib -import gc -import multiprocessing -import re -import sys -import textwrap -import traceback - -import pytest - -# Early diagnostic for failed imports -try: - import pybind11_tests -except Exception: - # pytest does not show the traceback without this. - traceback.print_exc() - raise - - -@pytest.fixture(scope="session", autouse=True) -def use_multiprocessing_forkserver_on_linux(): - if sys.platform != "linux": - # The default on Windows and macOS is "spawn": If it's not broken, don't fix it. - return - - # Full background: https://github.com/pybind/pybind11/issues/4105#issuecomment-1301004592 - # In a nutshell: fork() after starting threads == flakiness in the form of deadlocks. - # It is actually a well-known pitfall, unfortunately without guard rails. - # "forkserver" is more performant than "spawn" (~9s vs ~13s for tests/test_gil_scoped.py, - # visit the issuecomment link above for details). - multiprocessing.set_start_method("forkserver") - - -_long_marker = re.compile(r"([0-9])L") -_hexadecimal = re.compile(r"0x[0-9a-fA-F]+") - -# Avoid collecting Python3 only files -collect_ignore = [] - - -def _strip_and_dedent(s): - """For triple-quote strings""" - return textwrap.dedent(s.lstrip("\n").rstrip()) - - -def _split_and_sort(s): - """For output which does not require specific line order""" - return sorted(_strip_and_dedent(s).splitlines()) - - -def _make_explanation(a, b): - """Explanation for a failed assert -- the a and b arguments are List[str]""" - return ["--- actual / +++ expected"] + [ - line.strip("\n") for line in difflib.ndiff(a, b) - ] - - -class Output: - """Basic output post-processing and comparison""" - - def __init__(self, string): - self.string = string - self.explanation = [] - - def __str__(self): - return self.string - - def __eq__(self, other): - # Ignore constructor/destructor output which is prefixed with "###" - a = [ - line - for line in self.string.strip().splitlines() - if not line.startswith("###") - ] - b = _strip_and_dedent(other).splitlines() - if a == b: - return True - self.explanation = _make_explanation(a, b) - return False - - -class Unordered(Output): - """Custom comparison for output without strict line ordering""" - - def __eq__(self, other): - a = _split_and_sort(self.string) - b = _split_and_sort(other) - if a == b: - return True - self.explanation = _make_explanation(a, b) - return False - - -class Capture: - def __init__(self, capfd): - self.capfd = capfd - self.out = "" - self.err = "" - - def __enter__(self): - self.capfd.readouterr() - return self - - def __exit__(self, *args): - self.out, self.err = self.capfd.readouterr() - - def __eq__(self, other): - a = Output(self.out) - b = other - if a == b: - return True - self.explanation = a.explanation - return False - - def __str__(self): - return self.out - - def __contains__(self, item): - return item in self.out - - @property - def unordered(self): - return Unordered(self.out) - - @property - def stderr(self): - return Output(self.err) - - -@pytest.fixture() -def capture(capsys): - """Extended `capsys` with context manager and custom equality operators""" - return Capture(capsys) - - -class SanitizedString: - def __init__(self, sanitizer): - self.sanitizer = sanitizer - self.string = "" - self.explanation = [] - - def __call__(self, thing): - self.string = self.sanitizer(thing) - return self - - def __eq__(self, other): - a = self.string - b = _strip_and_dedent(other) - if a == b: - return True - self.explanation = _make_explanation(a.splitlines(), b.splitlines()) - return False - - -def _sanitize_general(s): - s = s.strip() - s = s.replace("pybind11_tests.", "m.") - return _long_marker.sub(r"\1", s) - - -def _sanitize_docstring(thing): - s = thing.__doc__ - return _sanitize_general(s) - - -@pytest.fixture() -def doc(): - """Sanitize docstrings and add custom failure explanation""" - return SanitizedString(_sanitize_docstring) - - -def _sanitize_message(thing): - s = str(thing) - s = _sanitize_general(s) - return _hexadecimal.sub("0", s) - - -@pytest.fixture() -def msg(): - """Sanitize messages and add custom failure explanation""" - return SanitizedString(_sanitize_message) - - -def pytest_assertrepr_compare(op, left, right): # noqa: ARG001 - """Hook to insert custom failure explanation""" - if hasattr(left, "explanation"): - return left.explanation - return None - - -def gc_collect(): - """Run the garbage collector twice (needed when running - reference counting tests with PyPy)""" - gc.collect() - gc.collect() - - -def pytest_configure(): - pytest.suppress = contextlib.suppress - pytest.gc_collect = gc_collect - - -def pytest_report_header(config): - del config # Unused. - assert ( - pybind11_tests.compiler_info is not None - ), "Please update pybind11_tests.cpp if this assert fails." - return ( - "C++ Info:" - f" {pybind11_tests.compiler_info}" - f" {pybind11_tests.cpp_std}" - f" {pybind11_tests.PYBIND11_INTERNALS_ID}" - f" PYBIND11_SIMPLE_GIL_MANAGEMENT={pybind11_tests.PYBIND11_SIMPLE_GIL_MANAGEMENT}" - f" PYBIND11_NUMPY_1_ONLY={pybind11_tests.PYBIND11_NUMPY_1_ONLY}" - ) +"""pytest configuration + +Extends output capture as needed by pybind11: ignore constructors, optional unordered lines. +Adds docstring and exceptions message sanitizers. +""" + +import contextlib +import difflib +import gc +import multiprocessing +import re +import sys +import textwrap +import traceback + +import pytest + +# Early diagnostic for failed imports +try: + import pybind11_tests +except Exception: + # pytest does not show the traceback without this. + traceback.print_exc() + raise + + +@pytest.fixture(scope="session", autouse=True) +def use_multiprocessing_forkserver_on_linux(): + if sys.platform != "linux": + # The default on Windows and macOS is "spawn": If it's not broken, don't fix it. + return + + # Full background: https://github.com/pybind/pybind11/issues/4105#issuecomment-1301004592 + # In a nutshell: fork() after starting threads == flakiness in the form of deadlocks. + # It is actually a well-known pitfall, unfortunately without guard rails. + # "forkserver" is more performant than "spawn" (~9s vs ~13s for tests/test_gil_scoped.py, + # visit the issuecomment link above for details). + multiprocessing.set_start_method("forkserver") + + +_long_marker = re.compile(r"([0-9])L") +_hexadecimal = re.compile(r"0x[0-9a-fA-F]+") + +# Avoid collecting Python3 only files +collect_ignore = [] + + +def _strip_and_dedent(s): + """For triple-quote strings""" + return textwrap.dedent(s.lstrip("\n").rstrip()) + + +def _split_and_sort(s): + """For output which does not require specific line order""" + return sorted(_strip_and_dedent(s).splitlines()) + + +def _make_explanation(a, b): + """Explanation for a failed assert -- the a and b arguments are List[str]""" + return ["--- actual / +++ expected"] + [ + line.strip("\n") for line in difflib.ndiff(a, b) + ] + + +class Output: + """Basic output post-processing and comparison""" + + def __init__(self, string): + self.string = string + self.explanation = [] + + def __str__(self): + return self.string + + def __eq__(self, other): + # Ignore constructor/destructor output which is prefixed with "###" + a = [ + line + for line in self.string.strip().splitlines() + if not line.startswith("###") + ] + b = _strip_and_dedent(other).splitlines() + if a == b: + return True + self.explanation = _make_explanation(a, b) + return False + + +class Unordered(Output): + """Custom comparison for output without strict line ordering""" + + def __eq__(self, other): + a = _split_and_sort(self.string) + b = _split_and_sort(other) + if a == b: + return True + self.explanation = _make_explanation(a, b) + return False + + +class Capture: + def __init__(self, capfd): + self.capfd = capfd + self.out = "" + self.err = "" + + def __enter__(self): + self.capfd.readouterr() + return self + + def __exit__(self, *args): + self.out, self.err = self.capfd.readouterr() + + def __eq__(self, other): + a = Output(self.out) + b = other + if a == b: + return True + self.explanation = a.explanation + return False + + def __str__(self): + return self.out + + def __contains__(self, item): + return item in self.out + + @property + def unordered(self): + return Unordered(self.out) + + @property + def stderr(self): + return Output(self.err) + + +@pytest.fixture() +def capture(capsys): + """Extended `capsys` with context manager and custom equality operators""" + return Capture(capsys) + + +class SanitizedString: + def __init__(self, sanitizer): + self.sanitizer = sanitizer + self.string = "" + self.explanation = [] + + def __call__(self, thing): + self.string = self.sanitizer(thing) + return self + + def __eq__(self, other): + a = self.string + b = _strip_and_dedent(other) + if a == b: + return True + self.explanation = _make_explanation(a.splitlines(), b.splitlines()) + return False + + +def _sanitize_general(s): + s = s.strip() + s = s.replace("pybind11_tests.", "m.") + return _long_marker.sub(r"\1", s) + + +def _sanitize_docstring(thing): + s = thing.__doc__ + return _sanitize_general(s) + + +@pytest.fixture() +def doc(): + """Sanitize docstrings and add custom failure explanation""" + return SanitizedString(_sanitize_docstring) + + +def _sanitize_message(thing): + s = str(thing) + s = _sanitize_general(s) + return _hexadecimal.sub("0", s) + + +@pytest.fixture() +def msg(): + """Sanitize messages and add custom failure explanation""" + return SanitizedString(_sanitize_message) + + +def pytest_assertrepr_compare(op, left, right): # noqa: ARG001 + """Hook to insert custom failure explanation""" + if hasattr(left, "explanation"): + return left.explanation + return None + + +def gc_collect(): + """Run the garbage collector twice (needed when running + reference counting tests with PyPy)""" + gc.collect() + gc.collect() + + +def pytest_configure(): + pytest.suppress = contextlib.suppress + pytest.gc_collect = gc_collect + + +def pytest_report_header(config): + del config # Unused. + assert ( + pybind11_tests.compiler_info is not None + ), "Please update pybind11_tests.cpp if this assert fails." + return ( + "C++ Info:" + f" {pybind11_tests.compiler_info}" + f" {pybind11_tests.cpp_std}" + f" {pybind11_tests.PYBIND11_INTERNALS_ID}" + f" PYBIND11_SIMPLE_GIL_MANAGEMENT={pybind11_tests.PYBIND11_SIMPLE_GIL_MANAGEMENT}" + f" PYBIND11_NUMPY_1_ONLY={pybind11_tests.PYBIND11_NUMPY_1_ONLY}" + ) diff --git a/third_party/CityFlow/extern/pybind11/tests/constructor_stats.h b/third_party/CityFlow/extern/pybind11/tests/constructor_stats.h index 937f6c233bce04280d528de451ff532348c085ce..d8b9366eb201cfdf87d114498197201ae1e3f285 100644 --- a/third_party/CityFlow/extern/pybind11/tests/constructor_stats.h +++ b/third_party/CityFlow/extern/pybind11/tests/constructor_stats.h @@ -1,322 +1,322 @@ -#pragma once -/* - tests/constructor_stats.h -- framework for printing and tracking object - instance lifetimes in example/test code. - - Copyright (c) 2016 Jason Rhinelander - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. - -This header provides a few useful tools for writing examples or tests that want to check and/or -display object instance lifetimes. It requires that you include this header and add the following -function calls to constructors: - - class MyClass { - MyClass() { ...; print_default_created(this); } - ~MyClass() { ...; print_destroyed(this); } - MyClass(const MyClass &c) { ...; print_copy_created(this); } - MyClass(MyClass &&c) { ...; print_move_created(this); } - MyClass(int a, int b) { ...; print_created(this, a, b); } - MyClass &operator=(const MyClass &c) { ...; print_copy_assigned(this); } - MyClass &operator=(MyClass &&c) { ...; print_move_assigned(this); } - - ... - } - -You can find various examples of these in several of the existing testing .cpp files. (Of course -you don't need to add any of the above constructors/operators that you don't actually have, except -for the destructor). - -Each of these will print an appropriate message such as: - - ### MyClass @ 0x2801910 created via default constructor - ### MyClass @ 0x27fa780 created 100 200 - ### MyClass @ 0x2801910 destroyed - ### MyClass @ 0x27fa780 destroyed - -You can also include extra arguments (such as the 100, 200 in the output above, coming from the -value constructor) for all of the above methods which will be included in the output. - -For testing, each of these also keeps track the created instances and allows you to check how many -of the various constructors have been invoked from the Python side via code such as: - - from pybind11_tests import ConstructorStats - cstats = ConstructorStats.get(MyClass) - print(cstats.alive()) - print(cstats.default_constructions) - -Note that `.alive()` should usually be the first thing you call as it invokes Python's garbage -collector to actually destroy objects that aren't yet referenced. - -For everything except copy and move constructors and destructors, any extra values given to the -print_...() function is stored in a class-specific values list which you can retrieve and inspect -from the ConstructorStats instance `.values()` method. - -In some cases, when you need to track instances of a C++ class not registered with pybind11, you -need to add a function returning the ConstructorStats for the C++ class; this can be done with: - - m.def("get_special_cstats", &ConstructorStats::get, -py::return_value_policy::reference) - -Finally, you can suppress the output messages, but keep the constructor tracking (for -inspection/testing in python) by using the functions with `print_` replaced with `track_` (e.g. -`track_copy_created(this)`). - -*/ - -#include "pybind11_tests.h" - -#include -#include -#include -#include - -class ConstructorStats { -protected: - std::unordered_map _instances; // Need a map rather than set because members can - // shared address with parents - std::list _values; // Used to track values - // (e.g. of value constructors) -public: - int default_constructions = 0; - int copy_constructions = 0; - int move_constructions = 0; - int copy_assignments = 0; - int move_assignments = 0; - - void copy_created(void *inst) { - created(inst); - copy_constructions++; - } - - void move_created(void *inst) { - created(inst); - move_constructions++; - } - - void default_created(void *inst) { - created(inst); - default_constructions++; - } - - void created(void *inst) { ++_instances[inst]; } - - void destroyed(void *inst) { - if (--_instances[inst] < 0) { - throw std::runtime_error("cstats.destroyed() called with unknown " - "instance; potential double-destruction " - "or a missing cstats.created()"); - } - } - - static void gc() { - // Force garbage collection to ensure any pending destructors are invoked: -#if defined(PYPY_VERSION) - PyObject *globals = PyEval_GetGlobals(); - PyObject *result = PyRun_String("import gc\n" - "for i in range(2):\n" - " gc.collect()\n", - Py_file_input, - globals, - globals); - if (result == nullptr) - throw py::error_already_set(); - Py_DECREF(result); -#else - py::module_::import("gc").attr("collect")(); -#endif - } - - int alive() { - gc(); - int total = 0; - for (const auto &p : _instances) { - if (p.second > 0) { - total += p.second; - } - } - return total; - } - - void value() {} // Recursion terminator - // Takes one or more values, converts them to strings, then stores them. - template - void value(const T &v, Tmore &&...args) { - std::ostringstream oss; - oss << v; - _values.push_back(oss.str()); - value(std::forward(args)...); - } - - // Move out stored values - py::list values() { - py::list l; - for (const auto &v : _values) { - l.append(py::cast(v)); - } - _values.clear(); - return l; - } - - // Gets constructor stats from a C++ type index - static ConstructorStats &get(std::type_index type) { - static std::unordered_map all_cstats; - return all_cstats[type]; - } - - // Gets constructor stats from a C++ type - template - static ConstructorStats &get() { -#if defined(PYPY_VERSION) - gc(); -#endif - return get(typeid(T)); - } - - // Gets constructor stats from a Python class - static ConstructorStats &get(py::object class_) { - auto &internals = py::detail::get_internals(); - const std::type_index *t1 = nullptr, *t2 = nullptr; - try { - auto *type_info - = internals.registered_types_py.at((PyTypeObject *) class_.ptr()).at(0); - for (auto &p : internals.registered_types_cpp) { - if (p.second == type_info) { - if (t1) { - t2 = &p.first; - break; - } - t1 = &p.first; - } - } - } catch (const std::out_of_range &) { - } - if (!t1) { - throw std::runtime_error("Unknown class passed to ConstructorStats::get()"); - } - auto &cs1 = get(*t1); - // If we have both a t1 and t2 match, one is probably the trampoline class; return - // whichever has more constructions (typically one or the other will be 0) - if (t2) { - auto &cs2 = get(*t2); - int cs1_total = cs1.default_constructions + cs1.copy_constructions - + cs1.move_constructions + (int) cs1._values.size(); - int cs2_total = cs2.default_constructions + cs2.copy_constructions - + cs2.move_constructions + (int) cs2._values.size(); - if (cs2_total > cs1_total) { - return cs2; - } - } - return cs1; - } -}; - -// To track construction/destruction, you need to call these methods from the various -// constructors/operators. The ones that take extra values record the given values in the -// constructor stats values for later inspection. -template -void track_copy_created(T *inst) { - ConstructorStats::get().copy_created(inst); -} -template -void track_move_created(T *inst) { - ConstructorStats::get().move_created(inst); -} -template -void track_copy_assigned(T *, Values &&...values) { - auto &cst = ConstructorStats::get(); - cst.copy_assignments++; - cst.value(std::forward(values)...); -} -template -void track_move_assigned(T *, Values &&...values) { - auto &cst = ConstructorStats::get(); - cst.move_assignments++; - cst.value(std::forward(values)...); -} -template -void track_default_created(T *inst, Values &&...values) { - auto &cst = ConstructorStats::get(); - cst.default_created(inst); - cst.value(std::forward(values)...); -} -template -void track_created(T *inst, Values &&...values) { - auto &cst = ConstructorStats::get(); - cst.created(inst); - cst.value(std::forward(values)...); -} -template -void track_destroyed(T *inst) { - ConstructorStats::get().destroyed(inst); -} -template -void track_values(T *, Values &&...values) { - ConstructorStats::get().value(std::forward(values)...); -} - -/// Don't cast pointers to Python, print them as strings -inline const char *format_ptrs(const char *p) { return p; } -template -py::str format_ptrs(T *p) { - return "{:#x}"_s.format(reinterpret_cast(p)); -} -template -auto format_ptrs(T &&x) -> decltype(std::forward(x)) { - return std::forward(x); -} - -template -void print_constr_details(T *inst, const std::string &action, Output &&...output) { - py::print("###", - py::type_id(), - "@", - format_ptrs(inst), - action, - format_ptrs(std::forward(output))...); -} - -// Verbose versions of the above: -template -void print_copy_created(T *inst, - Values &&...values) { // NB: this prints, but doesn't store, given values - print_constr_details(inst, "created via copy constructor", values...); - track_copy_created(inst); -} -template -void print_move_created(T *inst, - Values &&...values) { // NB: this prints, but doesn't store, given values - print_constr_details(inst, "created via move constructor", values...); - track_move_created(inst); -} -template -void print_copy_assigned(T *inst, Values &&...values) { - print_constr_details(inst, "assigned via copy assignment", values...); - track_copy_assigned(inst, values...); -} -template -void print_move_assigned(T *inst, Values &&...values) { - print_constr_details(inst, "assigned via move assignment", values...); - track_move_assigned(inst, values...); -} -template -void print_default_created(T *inst, Values &&...values) { - print_constr_details(inst, "created via default constructor", values...); - track_default_created(inst, values...); -} -template -void print_created(T *inst, Values &&...values) { - print_constr_details(inst, "created", values...); - track_created(inst, values...); -} -template -void print_destroyed(T *inst, Values &&...values) { // Prints but doesn't store given values - print_constr_details(inst, "destroyed", values...); - track_destroyed(inst); -} -template -void print_values(T *inst, Values &&...values) { - print_constr_details(inst, ":", values...); - track_values(inst, values...); -} +#pragma once +/* + tests/constructor_stats.h -- framework for printing and tracking object + instance lifetimes in example/test code. + + Copyright (c) 2016 Jason Rhinelander + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. + +This header provides a few useful tools for writing examples or tests that want to check and/or +display object instance lifetimes. It requires that you include this header and add the following +function calls to constructors: + + class MyClass { + MyClass() { ...; print_default_created(this); } + ~MyClass() { ...; print_destroyed(this); } + MyClass(const MyClass &c) { ...; print_copy_created(this); } + MyClass(MyClass &&c) { ...; print_move_created(this); } + MyClass(int a, int b) { ...; print_created(this, a, b); } + MyClass &operator=(const MyClass &c) { ...; print_copy_assigned(this); } + MyClass &operator=(MyClass &&c) { ...; print_move_assigned(this); } + + ... + } + +You can find various examples of these in several of the existing testing .cpp files. (Of course +you don't need to add any of the above constructors/operators that you don't actually have, except +for the destructor). + +Each of these will print an appropriate message such as: + + ### MyClass @ 0x2801910 created via default constructor + ### MyClass @ 0x27fa780 created 100 200 + ### MyClass @ 0x2801910 destroyed + ### MyClass @ 0x27fa780 destroyed + +You can also include extra arguments (such as the 100, 200 in the output above, coming from the +value constructor) for all of the above methods which will be included in the output. + +For testing, each of these also keeps track the created instances and allows you to check how many +of the various constructors have been invoked from the Python side via code such as: + + from pybind11_tests import ConstructorStats + cstats = ConstructorStats.get(MyClass) + print(cstats.alive()) + print(cstats.default_constructions) + +Note that `.alive()` should usually be the first thing you call as it invokes Python's garbage +collector to actually destroy objects that aren't yet referenced. + +For everything except copy and move constructors and destructors, any extra values given to the +print_...() function is stored in a class-specific values list which you can retrieve and inspect +from the ConstructorStats instance `.values()` method. + +In some cases, when you need to track instances of a C++ class not registered with pybind11, you +need to add a function returning the ConstructorStats for the C++ class; this can be done with: + + m.def("get_special_cstats", &ConstructorStats::get, +py::return_value_policy::reference) + +Finally, you can suppress the output messages, but keep the constructor tracking (for +inspection/testing in python) by using the functions with `print_` replaced with `track_` (e.g. +`track_copy_created(this)`). + +*/ + +#include "pybind11_tests.h" + +#include +#include +#include +#include + +class ConstructorStats { +protected: + std::unordered_map _instances; // Need a map rather than set because members can + // shared address with parents + std::list _values; // Used to track values + // (e.g. of value constructors) +public: + int default_constructions = 0; + int copy_constructions = 0; + int move_constructions = 0; + int copy_assignments = 0; + int move_assignments = 0; + + void copy_created(void *inst) { + created(inst); + copy_constructions++; + } + + void move_created(void *inst) { + created(inst); + move_constructions++; + } + + void default_created(void *inst) { + created(inst); + default_constructions++; + } + + void created(void *inst) { ++_instances[inst]; } + + void destroyed(void *inst) { + if (--_instances[inst] < 0) { + throw std::runtime_error("cstats.destroyed() called with unknown " + "instance; potential double-destruction " + "or a missing cstats.created()"); + } + } + + static void gc() { + // Force garbage collection to ensure any pending destructors are invoked: +#if defined(PYPY_VERSION) + PyObject *globals = PyEval_GetGlobals(); + PyObject *result = PyRun_String("import gc\n" + "for i in range(2):\n" + " gc.collect()\n", + Py_file_input, + globals, + globals); + if (result == nullptr) + throw py::error_already_set(); + Py_DECREF(result); +#else + py::module_::import("gc").attr("collect")(); +#endif + } + + int alive() { + gc(); + int total = 0; + for (const auto &p : _instances) { + if (p.second > 0) { + total += p.second; + } + } + return total; + } + + void value() {} // Recursion terminator + // Takes one or more values, converts them to strings, then stores them. + template + void value(const T &v, Tmore &&...args) { + std::ostringstream oss; + oss << v; + _values.push_back(oss.str()); + value(std::forward(args)...); + } + + // Move out stored values + py::list values() { + py::list l; + for (const auto &v : _values) { + l.append(py::cast(v)); + } + _values.clear(); + return l; + } + + // Gets constructor stats from a C++ type index + static ConstructorStats &get(std::type_index type) { + static std::unordered_map all_cstats; + return all_cstats[type]; + } + + // Gets constructor stats from a C++ type + template + static ConstructorStats &get() { +#if defined(PYPY_VERSION) + gc(); +#endif + return get(typeid(T)); + } + + // Gets constructor stats from a Python class + static ConstructorStats &get(py::object class_) { + auto &internals = py::detail::get_internals(); + const std::type_index *t1 = nullptr, *t2 = nullptr; + try { + auto *type_info + = internals.registered_types_py.at((PyTypeObject *) class_.ptr()).at(0); + for (auto &p : internals.registered_types_cpp) { + if (p.second == type_info) { + if (t1) { + t2 = &p.first; + break; + } + t1 = &p.first; + } + } + } catch (const std::out_of_range &) { + } + if (!t1) { + throw std::runtime_error("Unknown class passed to ConstructorStats::get()"); + } + auto &cs1 = get(*t1); + // If we have both a t1 and t2 match, one is probably the trampoline class; return + // whichever has more constructions (typically one or the other will be 0) + if (t2) { + auto &cs2 = get(*t2); + int cs1_total = cs1.default_constructions + cs1.copy_constructions + + cs1.move_constructions + (int) cs1._values.size(); + int cs2_total = cs2.default_constructions + cs2.copy_constructions + + cs2.move_constructions + (int) cs2._values.size(); + if (cs2_total > cs1_total) { + return cs2; + } + } + return cs1; + } +}; + +// To track construction/destruction, you need to call these methods from the various +// constructors/operators. The ones that take extra values record the given values in the +// constructor stats values for later inspection. +template +void track_copy_created(T *inst) { + ConstructorStats::get().copy_created(inst); +} +template +void track_move_created(T *inst) { + ConstructorStats::get().move_created(inst); +} +template +void track_copy_assigned(T *, Values &&...values) { + auto &cst = ConstructorStats::get(); + cst.copy_assignments++; + cst.value(std::forward(values)...); +} +template +void track_move_assigned(T *, Values &&...values) { + auto &cst = ConstructorStats::get(); + cst.move_assignments++; + cst.value(std::forward(values)...); +} +template +void track_default_created(T *inst, Values &&...values) { + auto &cst = ConstructorStats::get(); + cst.default_created(inst); + cst.value(std::forward(values)...); +} +template +void track_created(T *inst, Values &&...values) { + auto &cst = ConstructorStats::get(); + cst.created(inst); + cst.value(std::forward(values)...); +} +template +void track_destroyed(T *inst) { + ConstructorStats::get().destroyed(inst); +} +template +void track_values(T *, Values &&...values) { + ConstructorStats::get().value(std::forward(values)...); +} + +/// Don't cast pointers to Python, print them as strings +inline const char *format_ptrs(const char *p) { return p; } +template +py::str format_ptrs(T *p) { + return "{:#x}"_s.format(reinterpret_cast(p)); +} +template +auto format_ptrs(T &&x) -> decltype(std::forward(x)) { + return std::forward(x); +} + +template +void print_constr_details(T *inst, const std::string &action, Output &&...output) { + py::print("###", + py::type_id(), + "@", + format_ptrs(inst), + action, + format_ptrs(std::forward(output))...); +} + +// Verbose versions of the above: +template +void print_copy_created(T *inst, + Values &&...values) { // NB: this prints, but doesn't store, given values + print_constr_details(inst, "created via copy constructor", values...); + track_copy_created(inst); +} +template +void print_move_created(T *inst, + Values &&...values) { // NB: this prints, but doesn't store, given values + print_constr_details(inst, "created via move constructor", values...); + track_move_created(inst); +} +template +void print_copy_assigned(T *inst, Values &&...values) { + print_constr_details(inst, "assigned via copy assignment", values...); + track_copy_assigned(inst, values...); +} +template +void print_move_assigned(T *inst, Values &&...values) { + print_constr_details(inst, "assigned via move assignment", values...); + track_move_assigned(inst, values...); +} +template +void print_default_created(T *inst, Values &&...values) { + print_constr_details(inst, "created via default constructor", values...); + track_default_created(inst, values...); +} +template +void print_created(T *inst, Values &&...values) { + print_constr_details(inst, "created", values...); + track_created(inst, values...); +} +template +void print_destroyed(T *inst, Values &&...values) { // Prints but doesn't store given values + print_constr_details(inst, "destroyed", values...); + track_destroyed(inst); +} +template +void print_values(T *inst, Values &&...values) { + print_constr_details(inst, ":", values...); + track_values(inst, values...); +} diff --git a/third_party/CityFlow/extern/pybind11/tests/cross_module_gil_utils.cpp b/third_party/CityFlow/extern/pybind11/tests/cross_module_gil_utils.cpp index 7c20849dd93dfe11f97d6b450add6a353e899062..074bebfcf7cc1eff9ab5d5c2047cb176d58551fa 100644 --- a/third_party/CityFlow/extern/pybind11/tests/cross_module_gil_utils.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/cross_module_gil_utils.cpp @@ -1,108 +1,108 @@ -/* - tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module - - Copyright (c) 2019 Google LLC - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ -#if defined(PYBIND11_INTERNALS_VERSION) -# undef PYBIND11_INTERNALS_VERSION -#endif -#define PYBIND11_INTERNALS_VERSION 21814642 // Ensure this module has its own `internals` instance. -#include - -#include -#include -#include - -// This file mimics a DSO that makes pybind11 calls but does not define a -// PYBIND11_MODULE. The purpose is to test that such a DSO can create a -// py::gil_scoped_acquire when the running thread is in a GIL-released state. -// -// Note that we define a Python module here for convenience, but in general -// this need not be the case. The typical scenario would be a DSO that implements -// shared logic used internally by multiple pybind11 modules. - -namespace { - -namespace py = pybind11; - -void gil_acquire() { py::gil_scoped_acquire gil; } - -std::string gil_multi_acquire_release(unsigned bits) { - if ((bits & 0x1u) != 0u) { - py::gil_scoped_acquire gil; - } - if ((bits & 0x2u) != 0u) { - py::gil_scoped_release gil; - } - if ((bits & 0x4u) != 0u) { - py::gil_scoped_acquire gil; - } - if ((bits & 0x8u) != 0u) { - py::gil_scoped_release gil; - } - return PYBIND11_INTERNALS_ID; -} - -struct CustomAutoGIL { - CustomAutoGIL() : gstate(PyGILState_Ensure()) {} - ~CustomAutoGIL() { PyGILState_Release(gstate); } - - PyGILState_STATE gstate; -}; -struct CustomAutoNoGIL { - CustomAutoNoGIL() : save(PyEval_SaveThread()) {} - ~CustomAutoNoGIL() { PyEval_RestoreThread(save); } - - PyThreadState *save; -}; - -template -void gil_acquire_inner() { - Acquire acquire_outer; - Acquire acquire_inner; - Release release; -} - -template -void gil_acquire_nested() { - Acquire acquire_outer; - Acquire acquire_inner; - Release release; - auto thread = std::thread(&gil_acquire_inner); - thread.join(); -} - -constexpr char kModuleName[] = "cross_module_gil_utils"; - -struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr}; - -} // namespace - -#define ADD_FUNCTION(Name, ...) \ - PyModule_AddObject(m, Name, PyLong_FromVoidPtr(reinterpret_cast(&__VA_ARGS__))); - -extern "C" PYBIND11_EXPORT PyObject *PyInit_cross_module_gil_utils() { - - PyObject *m = PyModule_Create(&moduledef); - - if (m != nullptr) { - static_assert(sizeof(&gil_acquire) == sizeof(void *), - "Function pointer must have the same size as void*"); - ADD_FUNCTION("gil_acquire_funcaddr", gil_acquire) - ADD_FUNCTION("gil_multi_acquire_release_funcaddr", gil_multi_acquire_release) - ADD_FUNCTION("gil_acquire_inner_custom_funcaddr", - gil_acquire_inner) - ADD_FUNCTION("gil_acquire_nested_custom_funcaddr", - gil_acquire_nested) - ADD_FUNCTION("gil_acquire_inner_pybind11_funcaddr", - gil_acquire_inner) - ADD_FUNCTION("gil_acquire_nested_pybind11_funcaddr", - gil_acquire_nested) - } - - return m; -} +/* + tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module + + Copyright (c) 2019 Google LLC + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ +#if defined(PYBIND11_INTERNALS_VERSION) +# undef PYBIND11_INTERNALS_VERSION +#endif +#define PYBIND11_INTERNALS_VERSION 21814642 // Ensure this module has its own `internals` instance. +#include + +#include +#include +#include + +// This file mimics a DSO that makes pybind11 calls but does not define a +// PYBIND11_MODULE. The purpose is to test that such a DSO can create a +// py::gil_scoped_acquire when the running thread is in a GIL-released state. +// +// Note that we define a Python module here for convenience, but in general +// this need not be the case. The typical scenario would be a DSO that implements +// shared logic used internally by multiple pybind11 modules. + +namespace { + +namespace py = pybind11; + +void gil_acquire() { py::gil_scoped_acquire gil; } + +std::string gil_multi_acquire_release(unsigned bits) { + if ((bits & 0x1u) != 0u) { + py::gil_scoped_acquire gil; + } + if ((bits & 0x2u) != 0u) { + py::gil_scoped_release gil; + } + if ((bits & 0x4u) != 0u) { + py::gil_scoped_acquire gil; + } + if ((bits & 0x8u) != 0u) { + py::gil_scoped_release gil; + } + return PYBIND11_INTERNALS_ID; +} + +struct CustomAutoGIL { + CustomAutoGIL() : gstate(PyGILState_Ensure()) {} + ~CustomAutoGIL() { PyGILState_Release(gstate); } + + PyGILState_STATE gstate; +}; +struct CustomAutoNoGIL { + CustomAutoNoGIL() : save(PyEval_SaveThread()) {} + ~CustomAutoNoGIL() { PyEval_RestoreThread(save); } + + PyThreadState *save; +}; + +template +void gil_acquire_inner() { + Acquire acquire_outer; + Acquire acquire_inner; + Release release; +} + +template +void gil_acquire_nested() { + Acquire acquire_outer; + Acquire acquire_inner; + Release release; + auto thread = std::thread(&gil_acquire_inner); + thread.join(); +} + +constexpr char kModuleName[] = "cross_module_gil_utils"; + +struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr}; + +} // namespace + +#define ADD_FUNCTION(Name, ...) \ + PyModule_AddObject(m, Name, PyLong_FromVoidPtr(reinterpret_cast(&__VA_ARGS__))); + +extern "C" PYBIND11_EXPORT PyObject *PyInit_cross_module_gil_utils() { + + PyObject *m = PyModule_Create(&moduledef); + + if (m != nullptr) { + static_assert(sizeof(&gil_acquire) == sizeof(void *), + "Function pointer must have the same size as void*"); + ADD_FUNCTION("gil_acquire_funcaddr", gil_acquire) + ADD_FUNCTION("gil_multi_acquire_release_funcaddr", gil_multi_acquire_release) + ADD_FUNCTION("gil_acquire_inner_custom_funcaddr", + gil_acquire_inner) + ADD_FUNCTION("gil_acquire_nested_custom_funcaddr", + gil_acquire_nested) + ADD_FUNCTION("gil_acquire_inner_pybind11_funcaddr", + gil_acquire_inner) + ADD_FUNCTION("gil_acquire_nested_pybind11_funcaddr", + gil_acquire_nested) + } + + return m; +} diff --git a/third_party/CityFlow/extern/pybind11/tests/cross_module_interleaved_error_already_set.cpp b/third_party/CityFlow/extern/pybind11/tests/cross_module_interleaved_error_already_set.cpp index 3493a7e61551704cd9610fd63c766af9e5abc946..f4a9cdca38fd67967f8b81947a8f5e7b40009fd9 100644 --- a/third_party/CityFlow/extern/pybind11/tests/cross_module_interleaved_error_already_set.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/cross_module_interleaved_error_already_set.cpp @@ -1,51 +1,51 @@ -/* - Copyright (c) 2022 Google LLC - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include - -// This file mimics a DSO that makes pybind11 calls but does not define a PYBIND11_MODULE, -// so that the first call of cross_module_error_already_set() triggers the first call of -// pybind11::detail::get_internals(). - -namespace { - -namespace py = pybind11; - -void interleaved_error_already_set() { - py::set_error(PyExc_RuntimeError, "1st error."); - try { - throw py::error_already_set(); - } catch (const py::error_already_set &) { - // The 2nd error could be conditional in a real application. - py::set_error(PyExc_RuntimeError, "2nd error."); - } // Here the 1st error is destroyed before the 2nd error is fetched. - // The error_already_set dtor triggers a pybind11::detail::get_internals() - // call via pybind11::gil_scoped_acquire. - if (PyErr_Occurred()) { - throw py::error_already_set(); - } -} - -constexpr char kModuleName[] = "cross_module_interleaved_error_already_set"; - -struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr}; - -} // namespace - -extern "C" PYBIND11_EXPORT PyObject *PyInit_cross_module_interleaved_error_already_set() { - PyObject *m = PyModule_Create(&moduledef); - if (m != nullptr) { - static_assert(sizeof(&interleaved_error_already_set) == sizeof(void *), - "Function pointer must have the same size as void *"); - PyModule_AddObject( - m, - "funcaddr", - PyLong_FromVoidPtr(reinterpret_cast(&interleaved_error_already_set))); - } - return m; -} +/* + Copyright (c) 2022 Google LLC + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include + +// This file mimics a DSO that makes pybind11 calls but does not define a PYBIND11_MODULE, +// so that the first call of cross_module_error_already_set() triggers the first call of +// pybind11::detail::get_internals(). + +namespace { + +namespace py = pybind11; + +void interleaved_error_already_set() { + py::set_error(PyExc_RuntimeError, "1st error."); + try { + throw py::error_already_set(); + } catch (const py::error_already_set &) { + // The 2nd error could be conditional in a real application. + py::set_error(PyExc_RuntimeError, "2nd error."); + } // Here the 1st error is destroyed before the 2nd error is fetched. + // The error_already_set dtor triggers a pybind11::detail::get_internals() + // call via pybind11::gil_scoped_acquire. + if (PyErr_Occurred()) { + throw py::error_already_set(); + } +} + +constexpr char kModuleName[] = "cross_module_interleaved_error_already_set"; + +struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr}; + +} // namespace + +extern "C" PYBIND11_EXPORT PyObject *PyInit_cross_module_interleaved_error_already_set() { + PyObject *m = PyModule_Create(&moduledef); + if (m != nullptr) { + static_assert(sizeof(&interleaved_error_already_set) == sizeof(void *), + "Function pointer must have the same size as void *"); + PyModule_AddObject( + m, + "funcaddr", + PyLong_FromVoidPtr(reinterpret_cast(&interleaved_error_already_set))); + } + return m; +} diff --git a/third_party/CityFlow/extern/pybind11/tests/eigen_tensor_avoid_stl_array.cpp b/third_party/CityFlow/extern/pybind11/tests/eigen_tensor_avoid_stl_array.cpp index eacc9e9bd61e49c0e481771ea6617c383475aa61..79eb8513bafb8133fe5837ec626282315ec0aac9 100644 --- a/third_party/CityFlow/extern/pybind11/tests/eigen_tensor_avoid_stl_array.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/eigen_tensor_avoid_stl_array.cpp @@ -1,14 +1,14 @@ -/* - tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#ifndef EIGEN_AVOID_STL_ARRAY -# define EIGEN_AVOID_STL_ARRAY -#endif - -#include "test_eigen_tensor.inl" - -PYBIND11_MODULE(eigen_tensor_avoid_stl_array, m) { eigen_tensor_test::test_module(m); } +/* + tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#ifndef EIGEN_AVOID_STL_ARRAY +# define EIGEN_AVOID_STL_ARRAY +#endif + +#include "test_eigen_tensor.inl" + +PYBIND11_MODULE(eigen_tensor_avoid_stl_array, m) { eigen_tensor_test::test_module(m); } diff --git a/third_party/CityFlow/extern/pybind11/tests/env.py b/third_party/CityFlow/extern/pybind11/tests/env.py index 7eea5a3b3b720254a0b07098df17e3b84e849cbb..5cc23ae86c6ac4a746de820fb9a7da18cd47c2db 100644 --- a/third_party/CityFlow/extern/pybind11/tests/env.py +++ b/third_party/CityFlow/extern/pybind11/tests/env.py @@ -1,27 +1,27 @@ -import platform -import sys - -import pytest - -LINUX = sys.platform.startswith("linux") -MACOS = sys.platform.startswith("darwin") -WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin") - -CPYTHON = platform.python_implementation() == "CPython" -PYPY = platform.python_implementation() == "PyPy" - - -def deprecated_call(): - """ - pytest.deprecated_call() seems broken in pytest<3.9.x; concretely, it - doesn't work on CPython 3.8.0 with pytest==3.3.2 on Ubuntu 18.04 (#2922). - - This is a narrowed reimplementation of the following PR :( - https://github.com/pytest-dev/pytest/pull/4104 - """ - # TODO: Remove this when testing requires pytest>=3.9. - pieces = pytest.__version__.split(".") - pytest_major_minor = (int(pieces[0]), int(pieces[1])) - if pytest_major_minor < (3, 9): - return pytest.warns((DeprecationWarning, PendingDeprecationWarning)) - return pytest.deprecated_call() +import platform +import sys + +import pytest + +LINUX = sys.platform.startswith("linux") +MACOS = sys.platform.startswith("darwin") +WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin") + +CPYTHON = platform.python_implementation() == "CPython" +PYPY = platform.python_implementation() == "PyPy" + + +def deprecated_call(): + """ + pytest.deprecated_call() seems broken in pytest<3.9.x; concretely, it + doesn't work on CPython 3.8.0 with pytest==3.3.2 on Ubuntu 18.04 (#2922). + + This is a narrowed reimplementation of the following PR :( + https://github.com/pytest-dev/pytest/pull/4104 + """ + # TODO: Remove this when testing requires pytest>=3.9. + pieces = pytest.__version__.split(".") + pytest_major_minor = (int(pieces[0]), int(pieces[1])) + if pytest_major_minor < (3, 9): + return pytest.warns((DeprecationWarning, PendingDeprecationWarning)) + return pytest.deprecated_call() diff --git a/third_party/CityFlow/extern/pybind11/tests/local_bindings.h b/third_party/CityFlow/extern/pybind11/tests/local_bindings.h index 01d2785353ec006307078404f6116adb64021dc5..03129ba929cf407f37b2db9a5512d9f0bbb3b0bd 100644 --- a/third_party/CityFlow/extern/pybind11/tests/local_bindings.h +++ b/third_party/CityFlow/extern/pybind11/tests/local_bindings.h @@ -1,92 +1,92 @@ -#pragma once -#include "pybind11_tests.h" - -#include - -/// Simple class used to test py::local: -template -class LocalBase { -public: - explicit LocalBase(int i) : i(i) {} - int i = -1; -}; - -/// Registered with py::module_local in both main and secondary modules: -using LocalType = LocalBase<0>; -/// Registered without py::module_local in both modules: -using NonLocalType = LocalBase<1>; -/// A second non-local type (for stl_bind tests): -using NonLocal2 = LocalBase<2>; -/// Tests within-module, different-compilation-unit local definition conflict: -using LocalExternal = LocalBase<3>; -/// Mixed: registered local first, then global -using MixedLocalGlobal = LocalBase<4>; -/// Mixed: global first, then local -using MixedGlobalLocal = LocalBase<5>; - -/// Registered with py::module_local only in the secondary module: -using ExternalType1 = LocalBase<6>; -using ExternalType2 = LocalBase<7>; - -using LocalVec = std::vector; -using LocalVec2 = std::vector; -using LocalMap = std::unordered_map; -using NonLocalVec = std::vector; -using NonLocalVec2 = std::vector; -using NonLocalMap = std::unordered_map; -using NonLocalMap2 = std::unordered_map; - -// Exception that will be caught via the module local translator. -class LocalException : public std::exception { -public: - explicit LocalException(const char *m) : message{m} {} - const char *what() const noexcept override { return message.c_str(); } - -private: - std::string message = ""; -}; - -// Exception that will be registered with register_local_exception_translator -class LocalSimpleException : public std::exception { -public: - explicit LocalSimpleException(const char *m) : message{m} {} - const char *what() const noexcept override { return message.c_str(); } - -private: - std::string message = ""; -}; - -PYBIND11_MAKE_OPAQUE(LocalVec); -PYBIND11_MAKE_OPAQUE(LocalVec2); -PYBIND11_MAKE_OPAQUE(LocalMap); -PYBIND11_MAKE_OPAQUE(NonLocalVec); -// PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 -PYBIND11_MAKE_OPAQUE(NonLocalMap); -PYBIND11_MAKE_OPAQUE(NonLocalMap2); - -// Simple bindings (used with the above): -template -py::class_ bind_local(Args &&...args) { - return py::class_(std::forward(args)...).def(py::init()).def("get", [](T &i) { - return i.i + Adjust; - }); -}; - -// Simulate a foreign library base class (to match the example in the docs): -namespace pets { -class Pet { -public: - explicit Pet(std::string name) : name_(std::move(name)) {} - std::string name_; - const std::string &name() const { return name_; } -}; -} // namespace pets - -struct MixGL { - int i; - explicit MixGL(int i) : i{i} {} -}; -struct MixGL2 { - int i; - explicit MixGL2(int i) : i{i} {} -}; +#pragma once +#include "pybind11_tests.h" + +#include + +/// Simple class used to test py::local: +template +class LocalBase { +public: + explicit LocalBase(int i) : i(i) {} + int i = -1; +}; + +/// Registered with py::module_local in both main and secondary modules: +using LocalType = LocalBase<0>; +/// Registered without py::module_local in both modules: +using NonLocalType = LocalBase<1>; +/// A second non-local type (for stl_bind tests): +using NonLocal2 = LocalBase<2>; +/// Tests within-module, different-compilation-unit local definition conflict: +using LocalExternal = LocalBase<3>; +/// Mixed: registered local first, then global +using MixedLocalGlobal = LocalBase<4>; +/// Mixed: global first, then local +using MixedGlobalLocal = LocalBase<5>; + +/// Registered with py::module_local only in the secondary module: +using ExternalType1 = LocalBase<6>; +using ExternalType2 = LocalBase<7>; + +using LocalVec = std::vector; +using LocalVec2 = std::vector; +using LocalMap = std::unordered_map; +using NonLocalVec = std::vector; +using NonLocalVec2 = std::vector; +using NonLocalMap = std::unordered_map; +using NonLocalMap2 = std::unordered_map; + +// Exception that will be caught via the module local translator. +class LocalException : public std::exception { +public: + explicit LocalException(const char *m) : message{m} {} + const char *what() const noexcept override { return message.c_str(); } + +private: + std::string message = ""; +}; + +// Exception that will be registered with register_local_exception_translator +class LocalSimpleException : public std::exception { +public: + explicit LocalSimpleException(const char *m) : message{m} {} + const char *what() const noexcept override { return message.c_str(); } + +private: + std::string message = ""; +}; + +PYBIND11_MAKE_OPAQUE(LocalVec); +PYBIND11_MAKE_OPAQUE(LocalVec2); +PYBIND11_MAKE_OPAQUE(LocalMap); +PYBIND11_MAKE_OPAQUE(NonLocalVec); +// PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 +PYBIND11_MAKE_OPAQUE(NonLocalMap); +PYBIND11_MAKE_OPAQUE(NonLocalMap2); + +// Simple bindings (used with the above): +template +py::class_ bind_local(Args &&...args) { + return py::class_(std::forward(args)...).def(py::init()).def("get", [](T &i) { + return i.i + Adjust; + }); +}; + +// Simulate a foreign library base class (to match the example in the docs): +namespace pets { +class Pet { +public: + explicit Pet(std::string name) : name_(std::move(name)) {} + std::string name_; + const std::string &name() const { return name_; } +}; +} // namespace pets + +struct MixGL { + int i; + explicit MixGL(int i) : i{i} {} +}; +struct MixGL2 { + int i; + explicit MixGL2(int i) : i{i} {} +}; diff --git a/third_party/CityFlow/extern/pybind11/tests/object.h b/third_party/CityFlow/extern/pybind11/tests/object.h index 564dd4a7a5dd7e2dd74e023338e8ee6c2ee3171b..e566dfaf9f68ea68fa9b40d07ee241e0f465285d 100644 --- a/third_party/CityFlow/extern/pybind11/tests/object.h +++ b/third_party/CityFlow/extern/pybind11/tests/object.h @@ -1,205 +1,205 @@ -#if !defined(__OBJECT_H) -# define __OBJECT_H - -# include "constructor_stats.h" - -# include - -/// Reference counted object base class -class Object { -public: - /// Default constructor - Object() { print_default_created(this); } - - /// Copy constructor - Object(const Object &) : m_refCount(0) { print_copy_created(this); } - - /// Return the current reference count - int getRefCount() const { return m_refCount; }; - - /// Increase the object's reference count by one - void incRef() const { ++m_refCount; } - - /** \brief Decrease the reference count of - * the object and possibly deallocate it. - * - * The object will automatically be deallocated once - * the reference count reaches zero. - */ - void decRef(bool dealloc = true) const { - --m_refCount; - if (m_refCount == 0 && dealloc) { - delete this; - } else if (m_refCount < 0) { - throw std::runtime_error("Internal error: reference count < 0!"); - } - } - - virtual std::string toString() const = 0; - -protected: - /** \brief Virtual protected deconstructor. - * (Will only be called by \ref ref) - */ - virtual ~Object() { print_destroyed(this); } - -private: - mutable std::atomic m_refCount{0}; -}; - -// Tag class used to track constructions of ref objects. When we track constructors, below, we -// track and print out the actual class (e.g. ref), and *also* add a fake tracker for -// ref_tag. This lets us check that the total number of ref constructors/destructors is -// correct without having to check each individual ref type individually. -class ref_tag {}; - -/** - * \brief Reference counting helper - * - * The \a ref refeference template is a simple wrapper to store a - * pointer to an object. It takes care of increasing and decreasing - * the reference count of the object. When the last reference goes - * out of scope, the associated object will be deallocated. - * - * \ingroup libcore - */ -template -class ref { -public: - /// Create a nullptr reference - ref() : m_ptr(nullptr) { - print_default_created(this); - track_default_created((ref_tag *) this); - } - - /// Construct a reference from a pointer - explicit ref(T *ptr) : m_ptr(ptr) { - if (m_ptr) { - ((Object *) m_ptr)->incRef(); - } - - print_created(this, "from pointer", m_ptr); - track_created((ref_tag *) this, "from pointer"); - } - - /// Copy constructor - ref(const ref &r) : m_ptr(r.m_ptr) { - if (m_ptr) { - ((Object *) m_ptr)->incRef(); - } - - print_copy_created(this, "with pointer", m_ptr); - track_copy_created((ref_tag *) this); - } - - /// Move constructor - ref(ref &&r) noexcept : m_ptr(r.m_ptr) { - r.m_ptr = nullptr; - - print_move_created(this, "with pointer", m_ptr); - track_move_created((ref_tag *) this); - } - - /// Destroy this reference - ~ref() { - if (m_ptr) { - ((Object *) m_ptr)->decRef(); - } - - print_destroyed(this); - track_destroyed((ref_tag *) this); - } - - /// Move another reference into the current one - ref &operator=(ref &&r) noexcept { - print_move_assigned(this, "pointer", r.m_ptr); - track_move_assigned((ref_tag *) this); - - if (*this == r) { - return *this; - } - if (m_ptr) { - ((Object *) m_ptr)->decRef(); - } - m_ptr = r.m_ptr; - r.m_ptr = nullptr; - return *this; - } - - /// Overwrite this reference with another reference - ref &operator=(const ref &r) { - if (this == &r) { - return *this; - } - print_copy_assigned(this, "pointer", r.m_ptr); - track_copy_assigned((ref_tag *) this); - - if (m_ptr == r.m_ptr) { - return *this; - } - if (m_ptr) { - ((Object *) m_ptr)->decRef(); - } - m_ptr = r.m_ptr; - if (m_ptr) { - ((Object *) m_ptr)->incRef(); - } - return *this; - } - - /// Overwrite this reference with a pointer to another object - ref &operator=(T *ptr) { - print_values(this, "assigned pointer"); - track_values((ref_tag *) this, "assigned pointer"); - - if (m_ptr == ptr) { - return *this; - } - if (m_ptr) { - ((Object *) m_ptr)->decRef(); - } - m_ptr = ptr; - if (m_ptr) { - ((Object *) m_ptr)->incRef(); - } - return *this; - } - - /// Compare this reference with another reference - bool operator==(const ref &r) const { return m_ptr == r.m_ptr; } - - /// Compare this reference with another reference - bool operator!=(const ref &r) const { return m_ptr != r.m_ptr; } - - /// Compare this reference with a pointer - bool operator==(const T *ptr) const { return m_ptr == ptr; } - - /// Compare this reference with a pointer - bool operator!=(const T *ptr) const { return m_ptr != ptr; } - - /// Access the object referenced by this reference - T *operator->() { return m_ptr; } - - /// Access the object referenced by this reference - const T *operator->() const { return m_ptr; } - - /// Return a C++ reference to the referenced object - T &operator*() { return *m_ptr; } - - /// Return a const C++ reference to the referenced object - const T &operator*() const { return *m_ptr; } - - /// Return a pointer to the referenced object - explicit operator T *() { return m_ptr; } - - /// Return a const pointer to the referenced object - T *get_ptr() { return m_ptr; } - - /// Return a pointer to the referenced object - const T *get_ptr() const { return m_ptr; } - -private: - T *m_ptr; -}; - -#endif /* __OBJECT_H */ +#if !defined(__OBJECT_H) +# define __OBJECT_H + +# include "constructor_stats.h" + +# include + +/// Reference counted object base class +class Object { +public: + /// Default constructor + Object() { print_default_created(this); } + + /// Copy constructor + Object(const Object &) : m_refCount(0) { print_copy_created(this); } + + /// Return the current reference count + int getRefCount() const { return m_refCount; }; + + /// Increase the object's reference count by one + void incRef() const { ++m_refCount; } + + /** \brief Decrease the reference count of + * the object and possibly deallocate it. + * + * The object will automatically be deallocated once + * the reference count reaches zero. + */ + void decRef(bool dealloc = true) const { + --m_refCount; + if (m_refCount == 0 && dealloc) { + delete this; + } else if (m_refCount < 0) { + throw std::runtime_error("Internal error: reference count < 0!"); + } + } + + virtual std::string toString() const = 0; + +protected: + /** \brief Virtual protected deconstructor. + * (Will only be called by \ref ref) + */ + virtual ~Object() { print_destroyed(this); } + +private: + mutable std::atomic m_refCount{0}; +}; + +// Tag class used to track constructions of ref objects. When we track constructors, below, we +// track and print out the actual class (e.g. ref), and *also* add a fake tracker for +// ref_tag. This lets us check that the total number of ref constructors/destructors is +// correct without having to check each individual ref type individually. +class ref_tag {}; + +/** + * \brief Reference counting helper + * + * The \a ref refeference template is a simple wrapper to store a + * pointer to an object. It takes care of increasing and decreasing + * the reference count of the object. When the last reference goes + * out of scope, the associated object will be deallocated. + * + * \ingroup libcore + */ +template +class ref { +public: + /// Create a nullptr reference + ref() : m_ptr(nullptr) { + print_default_created(this); + track_default_created((ref_tag *) this); + } + + /// Construct a reference from a pointer + explicit ref(T *ptr) : m_ptr(ptr) { + if (m_ptr) { + ((Object *) m_ptr)->incRef(); + } + + print_created(this, "from pointer", m_ptr); + track_created((ref_tag *) this, "from pointer"); + } + + /// Copy constructor + ref(const ref &r) : m_ptr(r.m_ptr) { + if (m_ptr) { + ((Object *) m_ptr)->incRef(); + } + + print_copy_created(this, "with pointer", m_ptr); + track_copy_created((ref_tag *) this); + } + + /// Move constructor + ref(ref &&r) noexcept : m_ptr(r.m_ptr) { + r.m_ptr = nullptr; + + print_move_created(this, "with pointer", m_ptr); + track_move_created((ref_tag *) this); + } + + /// Destroy this reference + ~ref() { + if (m_ptr) { + ((Object *) m_ptr)->decRef(); + } + + print_destroyed(this); + track_destroyed((ref_tag *) this); + } + + /// Move another reference into the current one + ref &operator=(ref &&r) noexcept { + print_move_assigned(this, "pointer", r.m_ptr); + track_move_assigned((ref_tag *) this); + + if (*this == r) { + return *this; + } + if (m_ptr) { + ((Object *) m_ptr)->decRef(); + } + m_ptr = r.m_ptr; + r.m_ptr = nullptr; + return *this; + } + + /// Overwrite this reference with another reference + ref &operator=(const ref &r) { + if (this == &r) { + return *this; + } + print_copy_assigned(this, "pointer", r.m_ptr); + track_copy_assigned((ref_tag *) this); + + if (m_ptr == r.m_ptr) { + return *this; + } + if (m_ptr) { + ((Object *) m_ptr)->decRef(); + } + m_ptr = r.m_ptr; + if (m_ptr) { + ((Object *) m_ptr)->incRef(); + } + return *this; + } + + /// Overwrite this reference with a pointer to another object + ref &operator=(T *ptr) { + print_values(this, "assigned pointer"); + track_values((ref_tag *) this, "assigned pointer"); + + if (m_ptr == ptr) { + return *this; + } + if (m_ptr) { + ((Object *) m_ptr)->decRef(); + } + m_ptr = ptr; + if (m_ptr) { + ((Object *) m_ptr)->incRef(); + } + return *this; + } + + /// Compare this reference with another reference + bool operator==(const ref &r) const { return m_ptr == r.m_ptr; } + + /// Compare this reference with another reference + bool operator!=(const ref &r) const { return m_ptr != r.m_ptr; } + + /// Compare this reference with a pointer + bool operator==(const T *ptr) const { return m_ptr == ptr; } + + /// Compare this reference with a pointer + bool operator!=(const T *ptr) const { return m_ptr != ptr; } + + /// Access the object referenced by this reference + T *operator->() { return m_ptr; } + + /// Access the object referenced by this reference + const T *operator->() const { return m_ptr; } + + /// Return a C++ reference to the referenced object + T &operator*() { return *m_ptr; } + + /// Return a const C++ reference to the referenced object + const T &operator*() const { return *m_ptr; } + + /// Return a pointer to the referenced object + explicit operator T *() { return m_ptr; } + + /// Return a const pointer to the referenced object + T *get_ptr() { return m_ptr; } + + /// Return a pointer to the referenced object + const T *get_ptr() const { return m_ptr; } + +private: + T *m_ptr; +}; + +#endif /* __OBJECT_H */ diff --git a/third_party/CityFlow/extern/pybind11/tests/pybind11_cross_module_tests.cpp b/third_party/CityFlow/extern/pybind11/tests/pybind11_cross_module_tests.cpp index ad68e9a54fe20bfa0df7d9d1ae34bcf99825ded4..d22d5104bf6bcdb505aeb2216b43038c5b7ea7bc 100644 --- a/third_party/CityFlow/extern/pybind11/tests/pybind11_cross_module_tests.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/pybind11_cross_module_tests.cpp @@ -1,149 +1,149 @@ -/* - tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules - - Copyright (c) 2017 Jason Rhinelander - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include - -#include "local_bindings.h" -#include "pybind11_tests.h" -#include "test_exceptions.h" - -#include -#include - -PYBIND11_MODULE(pybind11_cross_module_tests, m) { - m.doc() = "pybind11 cross-module test module"; - - // test_local_bindings.py tests: - // - // Definitions here are tested by importing both this module and the - // relevant pybind11_tests submodule from a test_whatever.py - - // test_load_external - bind_local(m, "ExternalType1", py::module_local()); - bind_local(m, "ExternalType2", py::module_local()); - - // test_exceptions.py - py::register_local_exception(m, "LocalSimpleException"); - m.def("raise_runtime_error", []() { - py::set_error(PyExc_RuntimeError, "My runtime error"); - throw py::error_already_set(); - }); - m.def("raise_value_error", []() { - py::set_error(PyExc_ValueError, "My value error"); - throw py::error_already_set(); - }); - m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); }); - m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); }); - m.def("throw_stop_iteration", []() { throw py::stop_iteration(); }); - m.def("throw_local_error", []() { throw LocalException("just local"); }); - m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); }); - py::register_exception_translator([](std::exception_ptr p) { - try { - if (p) { - std::rethrow_exception(p); - } - } catch (const shared_exception &e) { - py::set_error(PyExc_KeyError, e.what()); - } - }); - - // translate the local exception into a key error but only in this module - py::register_local_exception_translator([](std::exception_ptr p) { - try { - if (p) { - std::rethrow_exception(p); - } - } catch (const LocalException &e) { - py::set_error(PyExc_KeyError, e.what()); - } - }); - - // test_local_bindings.py - // Local to both: - bind_local(m, "LocalType", py::module_local()).def("get2", [](LocalType &t) { - return t.i + 2; - }); - - // Can only be called with our python type: - m.def("local_value", [](LocalType &l) { return l.i; }); - - // test_nonlocal_failure - // This registration will fail (global registration when LocalFail is already registered - // globally in the main test module): - m.def("register_nonlocal", [m]() { bind_local(m, "NonLocalType"); }); - - // test_stl_bind_local - // stl_bind.h binders defaults to py::module_local if the types are local or converting: - py::bind_vector(m, "LocalVec"); - py::bind_map(m, "LocalMap"); - - // test_stl_bind_global - // and global if the type (or one of the types, for the map) is global (so these will fail, - // assuming pybind11_tests is already loaded): - m.def("register_nonlocal_vec", [m]() { py::bind_vector(m, "NonLocalVec"); }); - m.def("register_nonlocal_map", [m]() { py::bind_map(m, "NonLocalMap"); }); - // The default can, however, be overridden to global using `py::module_local()` or - // `py::module_local(false)`. - // Explicitly made local: - py::bind_vector(m, "NonLocalVec2", py::module_local()); - // Explicitly made global (and so will fail to bind): - m.def("register_nonlocal_map2", - [m]() { py::bind_map(m, "NonLocalMap2", py::module_local(false)); }); - - // test_mixed_local_global - // We try this both with the global type registered first and vice versa (the order shouldn't - // matter). - m.def("register_mixed_global_local", - [m]() { bind_local(m, "MixedGlobalLocal", py::module_local()); }); - m.def("register_mixed_local_global", [m]() { - bind_local(m, "MixedLocalGlobal", py::module_local(false)); - }); - m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); - m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); - - // test_internal_locals_differ - m.def("local_cpp_types_addr", - []() { return (uintptr_t) &py::detail::get_local_internals().registered_types_cpp; }); - - // test_stl_caster_vs_stl_bind - py::bind_vector>(m, "VectorInt"); - - m.def("load_vector_via_binding", - [](std::vector &v) { return std::accumulate(v.begin(), v.end(), 0); }); - - // test_cross_module_calls - m.def("return_self", [](LocalVec *v) { return v; }); - m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); - - class Dog : public pets::Pet { - public: - explicit Dog(std::string name) : Pet(std::move(name)) {} - }; - py::class_(m, "Pet", py::module_local()).def("name", &pets::Pet::name); - // Binding for local extending class: - py::class_(m, "Dog").def(py::init()); - m.def("pet_name", [](pets::Pet &p) { return p.name(); }); - - py::class_(m, "MixGL", py::module_local()).def(py::init()); - m.def("get_gl_value", [](MixGL &o) { return o.i + 100; }); - - py::class_(m, "MixGL2", py::module_local()).def(py::init()); - - // test_vector_bool - // We can't test both stl.h and stl_bind.h conversions of `std::vector` within - // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool` - // is defined here and tested in `test_stl_binders.py`. - py::bind_vector>(m, "VectorBool"); - - // test_missing_header_message - // The main module already includes stl.h, but we need to test the error message - // which appears when this header is missing. - m.def("missing_header_arg", [](const std::vector &) {}); - m.def("missing_header_return", []() { return std::vector(); }); -} +/* + tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules + + Copyright (c) 2017 Jason Rhinelander + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include + +#include "local_bindings.h" +#include "pybind11_tests.h" +#include "test_exceptions.h" + +#include +#include + +PYBIND11_MODULE(pybind11_cross_module_tests, m) { + m.doc() = "pybind11 cross-module test module"; + + // test_local_bindings.py tests: + // + // Definitions here are tested by importing both this module and the + // relevant pybind11_tests submodule from a test_whatever.py + + // test_load_external + bind_local(m, "ExternalType1", py::module_local()); + bind_local(m, "ExternalType2", py::module_local()); + + // test_exceptions.py + py::register_local_exception(m, "LocalSimpleException"); + m.def("raise_runtime_error", []() { + py::set_error(PyExc_RuntimeError, "My runtime error"); + throw py::error_already_set(); + }); + m.def("raise_value_error", []() { + py::set_error(PyExc_ValueError, "My value error"); + throw py::error_already_set(); + }); + m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); }); + m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); }); + m.def("throw_stop_iteration", []() { throw py::stop_iteration(); }); + m.def("throw_local_error", []() { throw LocalException("just local"); }); + m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); }); + py::register_exception_translator([](std::exception_ptr p) { + try { + if (p) { + std::rethrow_exception(p); + } + } catch (const shared_exception &e) { + py::set_error(PyExc_KeyError, e.what()); + } + }); + + // translate the local exception into a key error but only in this module + py::register_local_exception_translator([](std::exception_ptr p) { + try { + if (p) { + std::rethrow_exception(p); + } + } catch (const LocalException &e) { + py::set_error(PyExc_KeyError, e.what()); + } + }); + + // test_local_bindings.py + // Local to both: + bind_local(m, "LocalType", py::module_local()).def("get2", [](LocalType &t) { + return t.i + 2; + }); + + // Can only be called with our python type: + m.def("local_value", [](LocalType &l) { return l.i; }); + + // test_nonlocal_failure + // This registration will fail (global registration when LocalFail is already registered + // globally in the main test module): + m.def("register_nonlocal", [m]() { bind_local(m, "NonLocalType"); }); + + // test_stl_bind_local + // stl_bind.h binders defaults to py::module_local if the types are local or converting: + py::bind_vector(m, "LocalVec"); + py::bind_map(m, "LocalMap"); + + // test_stl_bind_global + // and global if the type (or one of the types, for the map) is global (so these will fail, + // assuming pybind11_tests is already loaded): + m.def("register_nonlocal_vec", [m]() { py::bind_vector(m, "NonLocalVec"); }); + m.def("register_nonlocal_map", [m]() { py::bind_map(m, "NonLocalMap"); }); + // The default can, however, be overridden to global using `py::module_local()` or + // `py::module_local(false)`. + // Explicitly made local: + py::bind_vector(m, "NonLocalVec2", py::module_local()); + // Explicitly made global (and so will fail to bind): + m.def("register_nonlocal_map2", + [m]() { py::bind_map(m, "NonLocalMap2", py::module_local(false)); }); + + // test_mixed_local_global + // We try this both with the global type registered first and vice versa (the order shouldn't + // matter). + m.def("register_mixed_global_local", + [m]() { bind_local(m, "MixedGlobalLocal", py::module_local()); }); + m.def("register_mixed_local_global", [m]() { + bind_local(m, "MixedLocalGlobal", py::module_local(false)); + }); + m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); + m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); + + // test_internal_locals_differ + m.def("local_cpp_types_addr", + []() { return (uintptr_t) &py::detail::get_local_internals().registered_types_cpp; }); + + // test_stl_caster_vs_stl_bind + py::bind_vector>(m, "VectorInt"); + + m.def("load_vector_via_binding", + [](std::vector &v) { return std::accumulate(v.begin(), v.end(), 0); }); + + // test_cross_module_calls + m.def("return_self", [](LocalVec *v) { return v; }); + m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); + + class Dog : public pets::Pet { + public: + explicit Dog(std::string name) : Pet(std::move(name)) {} + }; + py::class_(m, "Pet", py::module_local()).def("name", &pets::Pet::name); + // Binding for local extending class: + py::class_(m, "Dog").def(py::init()); + m.def("pet_name", [](pets::Pet &p) { return p.name(); }); + + py::class_(m, "MixGL", py::module_local()).def(py::init()); + m.def("get_gl_value", [](MixGL &o) { return o.i + 100; }); + + py::class_(m, "MixGL2", py::module_local()).def(py::init()); + + // test_vector_bool + // We can't test both stl.h and stl_bind.h conversions of `std::vector` within + // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool` + // is defined here and tested in `test_stl_binders.py`. + py::bind_vector>(m, "VectorBool"); + + // test_missing_header_message + // The main module already includes stl.h, but we need to test the error message + // which appears when this header is missing. + m.def("missing_header_arg", [](const std::vector &) {}); + m.def("missing_header_return", []() { return std::vector(); }); +} diff --git a/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.cpp b/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.cpp index 81869ebe215eb9d40baa3a4c0b40508e51e5d407..13988d64f69a0d9f58be4ef55f1c79fe2f590b97 100644 --- a/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.cpp @@ -1,129 +1,129 @@ -/* - tests/pybind11_tests.cpp -- pybind example plugin - - Copyright (c) 2016 Wenzel Jakob - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include "pybind11_tests.h" - -#include "constructor_stats.h" - -#include -#include - -/* -For testing purposes, we define a static global variable here in a function that each individual -test .cpp calls with its initialization lambda. It's convenient here because we can just not -compile some test files to disable/ignore some of the test code. - -It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will -be essentially random, which is okay for our test scripts (there are no dependencies between the -individual pybind11 test .cpp files), but most likely not what you want when using pybind11 -productively. - -Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" -section of the documentation for good practice on splitting binding code over multiple files. -*/ -std::list> &initializers() { - static std::list> inits; - return inits; -} - -test_initializer::test_initializer(Initializer init) { initializers().emplace_back(init); } - -test_initializer::test_initializer(const char *submodule_name, Initializer init) { - initializers().emplace_back([=](py::module_ &parent) { - auto m = parent.def_submodule(submodule_name); - init(m); - }); -} - -void bind_ConstructorStats(py::module_ &m) { - py::class_(m, "ConstructorStats") - .def("alive", &ConstructorStats::alive) - .def("values", &ConstructorStats::values) - .def_readwrite("default_constructions", &ConstructorStats::default_constructions) - .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) - .def_readwrite("move_assignments", &ConstructorStats::move_assignments) - .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) - .def_readwrite("move_constructions", &ConstructorStats::move_constructions) - .def_static("get", - (ConstructorStats & (*) (py::object)) & ConstructorStats::get, - py::return_value_policy::reference_internal) - - // Not exactly ConstructorStats, but related: expose the internal pybind number of - // registered instances to allow instance cleanup checks (invokes a GC first) - .def_static("detail_reg_inst", []() { - ConstructorStats::gc(); - return py::detail::get_internals().registered_instances.size(); - }); -} - -const char *cpp_std() { - return -#if defined(PYBIND11_CPP20) - "C++20"; -#elif defined(PYBIND11_CPP17) - "C++17"; -#elif defined(PYBIND11_CPP14) - "C++14"; -#else - "C++11"; -#endif -} - -PYBIND11_MODULE(pybind11_tests, m) { - m.doc() = "pybind11 test module"; - - // Intentionally kept minimal to not create a maintenance chore - // ("just enough" to be conclusive). -#if defined(__VERSION__) - m.attr("compiler_info") = __VERSION__; -#elif defined(_MSC_FULL_VER) - m.attr("compiler_info") = "MSVC " PYBIND11_TOSTRING(_MSC_FULL_VER); -#else - m.attr("compiler_info") = py::none(); -#endif - m.attr("cpp_std") = cpp_std(); - m.attr("PYBIND11_INTERNALS_ID") = PYBIND11_INTERNALS_ID; - m.attr("PYBIND11_SIMPLE_GIL_MANAGEMENT") = -#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT) - true; -#else - false; -#endif - m.attr("PYBIND11_NUMPY_1_ONLY") = -#if defined(PYBIND11_NUMPY_1_ONLY) - true; -#else - false; -#endif - - bind_ConstructorStats(m); - -#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) - m.attr("detailed_error_messages_enabled") = true; -#else - m.attr("detailed_error_messages_enabled") = false; -#endif - - py::class_(m, "UserType", "A `py::class_` type for testing") - .def(py::init<>()) - .def(py::init()) - .def("get_value", &UserType::value, "Get value using a method") - .def("set_value", &UserType::set, "Set value using a method") - .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") - .def("__repr__", [](const UserType &u) { return "UserType({})"_s.format(u.value()); }); - - py::class_(m, "IncType") - .def(py::init<>()) - .def(py::init()) - .def("__repr__", [](const IncType &u) { return "IncType({})"_s.format(u.value()); }); - - for (const auto &initializer : initializers()) { - initializer(m); - } -} +/* + tests/pybind11_tests.cpp -- pybind example plugin + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include "pybind11_tests.h" + +#include "constructor_stats.h" + +#include +#include + +/* +For testing purposes, we define a static global variable here in a function that each individual +test .cpp calls with its initialization lambda. It's convenient here because we can just not +compile some test files to disable/ignore some of the test code. + +It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will +be essentially random, which is okay for our test scripts (there are no dependencies between the +individual pybind11 test .cpp files), but most likely not what you want when using pybind11 +productively. + +Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" +section of the documentation for good practice on splitting binding code over multiple files. +*/ +std::list> &initializers() { + static std::list> inits; + return inits; +} + +test_initializer::test_initializer(Initializer init) { initializers().emplace_back(init); } + +test_initializer::test_initializer(const char *submodule_name, Initializer init) { + initializers().emplace_back([=](py::module_ &parent) { + auto m = parent.def_submodule(submodule_name); + init(m); + }); +} + +void bind_ConstructorStats(py::module_ &m) { + py::class_(m, "ConstructorStats") + .def("alive", &ConstructorStats::alive) + .def("values", &ConstructorStats::values) + .def_readwrite("default_constructions", &ConstructorStats::default_constructions) + .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) + .def_readwrite("move_assignments", &ConstructorStats::move_assignments) + .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) + .def_readwrite("move_constructions", &ConstructorStats::move_constructions) + .def_static("get", + (ConstructorStats & (*) (py::object)) & ConstructorStats::get, + py::return_value_policy::reference_internal) + + // Not exactly ConstructorStats, but related: expose the internal pybind number of + // registered instances to allow instance cleanup checks (invokes a GC first) + .def_static("detail_reg_inst", []() { + ConstructorStats::gc(); + return py::detail::get_internals().registered_instances.size(); + }); +} + +const char *cpp_std() { + return +#if defined(PYBIND11_CPP20) + "C++20"; +#elif defined(PYBIND11_CPP17) + "C++17"; +#elif defined(PYBIND11_CPP14) + "C++14"; +#else + "C++11"; +#endif +} + +PYBIND11_MODULE(pybind11_tests, m) { + m.doc() = "pybind11 test module"; + + // Intentionally kept minimal to not create a maintenance chore + // ("just enough" to be conclusive). +#if defined(__VERSION__) + m.attr("compiler_info") = __VERSION__; +#elif defined(_MSC_FULL_VER) + m.attr("compiler_info") = "MSVC " PYBIND11_TOSTRING(_MSC_FULL_VER); +#else + m.attr("compiler_info") = py::none(); +#endif + m.attr("cpp_std") = cpp_std(); + m.attr("PYBIND11_INTERNALS_ID") = PYBIND11_INTERNALS_ID; + m.attr("PYBIND11_SIMPLE_GIL_MANAGEMENT") = +#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT) + true; +#else + false; +#endif + m.attr("PYBIND11_NUMPY_1_ONLY") = +#if defined(PYBIND11_NUMPY_1_ONLY) + true; +#else + false; +#endif + + bind_ConstructorStats(m); + +#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) + m.attr("detailed_error_messages_enabled") = true; +#else + m.attr("detailed_error_messages_enabled") = false; +#endif + + py::class_(m, "UserType", "A `py::class_` type for testing") + .def(py::init<>()) + .def(py::init()) + .def("get_value", &UserType::value, "Get value using a method") + .def("set_value", &UserType::set, "Set value using a method") + .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") + .def("__repr__", [](const UserType &u) { return "UserType({})"_s.format(u.value()); }); + + py::class_(m, "IncType") + .def(py::init<>()) + .def(py::init()) + .def("__repr__", [](const IncType &u) { return "IncType({})"_s.format(u.value()); }); + + for (const auto &initializer : initializers()) { + initializer(m); + } +} diff --git a/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.h b/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.h index a7c00c2f9bb26b4afb908ad4f2749bd89ff5eeab..a8e79a06d2baaa58ee74875f629f7ea2f3c78495 100644 --- a/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.h +++ b/third_party/CityFlow/extern/pybind11/tests/pybind11_tests.h @@ -1,85 +1,85 @@ -#pragma once - -#include -#include - -namespace py = pybind11; -using namespace pybind11::literals; - -class test_initializer { - using Initializer = void (*)(py::module_ &); - -public: - explicit test_initializer(Initializer init); - test_initializer(const char *submodule_name, Initializer init); -}; - -#define TEST_SUBMODULE(name, variable) \ - void test_submodule_##name(py::module_ &); \ - test_initializer name(#name, test_submodule_##name); \ - void test_submodule_##name(py::module_ &(variable)) - -/// Dummy type which is not exported anywhere -- something to trigger a conversion error -struct UnregisteredType {}; - -/// A user-defined type which is exported and can be used by any test -class UserType { -public: - UserType() = default; - explicit UserType(int i) : i(i) {} - - int value() const { return i; } - void set(int set) { i = set; } - -private: - int i = -1; -}; - -/// Like UserType, but increments `value` on copy for quick reference vs. copy tests -class IncType : public UserType { -public: - using UserType::UserType; - IncType() = default; - IncType(const IncType &other) : IncType(other.value() + 1) {} - IncType(IncType &&) = delete; - IncType &operator=(const IncType &) = delete; - IncType &operator=(IncType &&) = delete; -}; - -/// A simple union for basic testing -union IntFloat { - int i; - float f; -}; - -/// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast -/// context. Used to test recursive casters (e.g. std::tuple, stl containers). -struct RValueCaster {}; -PYBIND11_NAMESPACE_BEGIN(pybind11) -PYBIND11_NAMESPACE_BEGIN(detail) -template <> -class type_caster { -public: - PYBIND11_TYPE_CASTER(RValueCaster, const_name("RValueCaster")); - static handle cast(RValueCaster &&, return_value_policy, handle) { - return py::str("rvalue").release(); - } - static handle cast(const RValueCaster &, return_value_policy, handle) { - return py::str("lvalue").release(); - } -}; -PYBIND11_NAMESPACE_END(detail) -PYBIND11_NAMESPACE_END(pybind11) - -template -void ignoreOldStyleInitWarnings(F &&body) { - py::exec(R"( - message = "pybind11-bound class '.+' is using an old-style placement-new '(?:__init__|__setstate__)' which has been deprecated" - - import warnings - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", message=message, category=FutureWarning) - body() - )", - py::dict(py::arg("body") = py::cpp_function(body))); -} +#pragma once + +#include +#include + +namespace py = pybind11; +using namespace pybind11::literals; + +class test_initializer { + using Initializer = void (*)(py::module_ &); + +public: + explicit test_initializer(Initializer init); + test_initializer(const char *submodule_name, Initializer init); +}; + +#define TEST_SUBMODULE(name, variable) \ + void test_submodule_##name(py::module_ &); \ + test_initializer name(#name, test_submodule_##name); \ + void test_submodule_##name(py::module_ &(variable)) + +/// Dummy type which is not exported anywhere -- something to trigger a conversion error +struct UnregisteredType {}; + +/// A user-defined type which is exported and can be used by any test +class UserType { +public: + UserType() = default; + explicit UserType(int i) : i(i) {} + + int value() const { return i; } + void set(int set) { i = set; } + +private: + int i = -1; +}; + +/// Like UserType, but increments `value` on copy for quick reference vs. copy tests +class IncType : public UserType { +public: + using UserType::UserType; + IncType() = default; + IncType(const IncType &other) : IncType(other.value() + 1) {} + IncType(IncType &&) = delete; + IncType &operator=(const IncType &) = delete; + IncType &operator=(IncType &&) = delete; +}; + +/// A simple union for basic testing +union IntFloat { + int i; + float f; +}; + +/// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast +/// context. Used to test recursive casters (e.g. std::tuple, stl containers). +struct RValueCaster {}; +PYBIND11_NAMESPACE_BEGIN(pybind11) +PYBIND11_NAMESPACE_BEGIN(detail) +template <> +class type_caster { +public: + PYBIND11_TYPE_CASTER(RValueCaster, const_name("RValueCaster")); + static handle cast(RValueCaster &&, return_value_policy, handle) { + return py::str("rvalue").release(); + } + static handle cast(const RValueCaster &, return_value_policy, handle) { + return py::str("lvalue").release(); + } +}; +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(pybind11) + +template +void ignoreOldStyleInitWarnings(F &&body) { + py::exec(R"( + message = "pybind11-bound class '.+' is using an old-style placement-new '(?:__init__|__setstate__)' which has been deprecated" + + import warnings + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=message, category=FutureWarning) + body() + )", + py::dict(py::arg("body") = py::cpp_function(body))); +} diff --git a/third_party/CityFlow/extern/pybind11/tests/pytest.ini b/third_party/CityFlow/extern/pybind11/tests/pytest.ini index 792ba361f722fbc7a830ea935cad26c497557df8..1a181fce1fb6ca9635348dc4cff65274534be4f5 100644 --- a/third_party/CityFlow/extern/pybind11/tests/pytest.ini +++ b/third_party/CityFlow/extern/pybind11/tests/pytest.ini @@ -1,22 +1,22 @@ -[pytest] -minversion = 3.10 -norecursedirs = test_* extra_* -xfail_strict = True -addopts = - # show summary of tests - -ra - # capture only Python print and C++ py::print, but not C output (low-level Python errors) - --capture=sys - # Show local info when a failure occurs - --showlocals -log_cli_level = info -filterwarnings = - # make warnings into errors but ignore certain third-party extension issues - error - # somehow, some DeprecationWarnings do not get turned into errors - always::DeprecationWarning - # importing scipy submodules on some version of Python - ignore::ImportWarning - # bogus numpy ABI warning (see numpy/#432) - ignore:.*numpy.dtype size changed.*:RuntimeWarning - ignore:.*numpy.ufunc size changed.*:RuntimeWarning +[pytest] +minversion = 3.10 +norecursedirs = test_* extra_* +xfail_strict = True +addopts = + # show summary of tests + -ra + # capture only Python print and C++ py::print, but not C output (low-level Python errors) + --capture=sys + # Show local info when a failure occurs + --showlocals +log_cli_level = info +filterwarnings = + # make warnings into errors but ignore certain third-party extension issues + error + # somehow, some DeprecationWarnings do not get turned into errors + always::DeprecationWarning + # importing scipy submodules on some version of Python + ignore::ImportWarning + # bogus numpy ABI warning (see numpy/#432) + ignore:.*numpy.dtype size changed.*:RuntimeWarning + ignore:.*numpy.ufunc size changed.*:RuntimeWarning diff --git a/third_party/CityFlow/extern/pybind11/tests/requirements.txt b/third_party/CityFlow/extern/pybind11/tests/requirements.txt index e056c6fa8a462e43612b56395b97091d464364fb..c86b97d47ab4a858206e337768dcf94661782fe9 100644 --- a/third_party/CityFlow/extern/pybind11/tests/requirements.txt +++ b/third_party/CityFlow/extern/pybind11/tests/requirements.txt @@ -1,15 +1,15 @@ ---only-binary=:all: -build~=0.9; python_version=="3.6" -build~=1.0; python_version>="3.7" -numpy~=1.20.0; python_version=="3.7" and platform_python_implementation=="PyPy" -numpy~=1.23.0; python_version=="3.8" and platform_python_implementation=="PyPy" -numpy~=1.25.0; python_version=="3.9" and platform_python_implementation=='PyPy' -numpy~=1.19.3; platform_python_implementation!="PyPy" and python_version=="3.6" -numpy~=1.21.5; platform_python_implementation!="PyPy" and python_version>="3.7" and python_version<"3.10" -numpy~=1.22.2; platform_python_implementation!="PyPy" and python_version=="3.10" -numpy~=1.26.0; platform_python_implementation!="PyPy" and python_version>="3.11" and python_version<"3.13" -pytest~=7.0 -pytest-timeout -scipy~=1.5.4; platform_python_implementation!="PyPy" and python_version<"3.10" -scipy~=1.8.0; platform_python_implementation!="PyPy" and python_version=="3.10" -scipy~=1.11.1; platform_python_implementation!="PyPy" and python_version>="3.11" and python_version<"3.13" +--only-binary=:all: +build~=0.9; python_version=="3.6" +build~=1.0; python_version>="3.7" +numpy~=1.20.0; python_version=="3.7" and platform_python_implementation=="PyPy" +numpy~=1.23.0; python_version=="3.8" and platform_python_implementation=="PyPy" +numpy~=1.25.0; python_version=="3.9" and platform_python_implementation=='PyPy' +numpy~=1.19.3; platform_python_implementation!="PyPy" and python_version=="3.6" +numpy~=1.21.5; platform_python_implementation!="PyPy" and python_version>="3.7" and python_version<"3.10" +numpy~=1.22.2; platform_python_implementation!="PyPy" and python_version=="3.10" +numpy~=1.26.0; platform_python_implementation!="PyPy" and python_version>="3.11" and python_version<"3.13" +pytest~=7.0 +pytest-timeout +scipy~=1.5.4; platform_python_implementation!="PyPy" and python_version<"3.10" +scipy~=1.8.0; platform_python_implementation!="PyPy" and python_version=="3.10" +scipy~=1.11.1; platform_python_implementation!="PyPy" and python_version>="3.11" and python_version<"3.13" diff --git a/third_party/CityFlow/extern/pybind11/tests/test_async.cpp b/third_party/CityFlow/extern/pybind11/tests/test_async.cpp index a5d7224657298d159269838ab63607cb8d8e75a5..dee9330351537128e87ce2b45589d2ccd309651c 100644 --- a/third_party/CityFlow/extern/pybind11/tests/test_async.cpp +++ b/third_party/CityFlow/extern/pybind11/tests/test_async.cpp @@ -1,25 +1,25 @@ -/* - tests/test_async.cpp -- __await__ support - - Copyright (c) 2019 Google Inc. - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include "pybind11_tests.h" - -TEST_SUBMODULE(async_module, m) { - struct DoesNotSupportAsync {}; - py::class_(m, "DoesNotSupportAsync").def(py::init<>()); - struct SupportsAsync {}; - py::class_(m, "SupportsAsync") - .def(py::init<>()) - .def("__await__", [](const SupportsAsync &self) -> py::object { - static_cast(self); - py::object loop = py::module_::import("asyncio.events").attr("get_event_loop")(); - py::object f = loop.attr("create_future")(); - f.attr("set_result")(5); - return f.attr("__await__")(); - }); -} +/* + tests/test_async.cpp -- __await__ support + + Copyright (c) 2019 Google Inc. + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include "pybind11_tests.h" + +TEST_SUBMODULE(async_module, m) { + struct DoesNotSupportAsync {}; + py::class_(m, "DoesNotSupportAsync").def(py::init<>()); + struct SupportsAsync {}; + py::class_(m, "SupportsAsync") + .def(py::init<>()) + .def("__await__", [](const SupportsAsync &self) -> py::object { + static_cast(self); + py::object loop = py::module_::import("asyncio.events").attr("get_event_loop")(); + py::object f = loop.attr("create_future")(); + f.attr("set_result")(5); + return f.attr("__await__")(); + }); +} diff --git a/third_party/CityFlow/extern/rapidjson/.git.bak b/third_party/CityFlow/extern/rapidjson/.git.bak index 3a56b2256f7201b4486f81649ece415709aaa2c8..1a0b8ca6659a974e4c239de21cb6bc3b118c7cdb 100644 --- a/third_party/CityFlow/extern/rapidjson/.git.bak +++ b/third_party/CityFlow/extern/rapidjson/.git.bak @@ -1 +1 @@ -gitdir: ../../.git/modules/extern/rapidjson +gitdir: ../../.git/modules/extern/rapidjson diff --git a/third_party/CityFlow/src/utility/barrier.h b/third_party/CityFlow/src/utility/barrier.h index edf2b043aea0d7a6171dc877b7b2b388baae545c..8870c505f56b8680895c3fa8704d15f17ec0a529 100644 --- a/third_party/CityFlow/src/utility/barrier.h +++ b/third_party/CityFlow/src/utility/barrier.h @@ -1,38 +1,38 @@ -#ifndef CITYFLOW_BARRIER_H -#define CITYFLOW_BARRIER_H -#include -#include -#include -#include -#include - -namespace CityFlow { - class Barrier { - public: - Barrier(std::size_t nb_threads) : m_threads(nb_threads), currCounter(&counter[0]) { - assert(0u != m_threads); - counter[0] = m_threads; - counter[1] = 0; - } - - Barrier(const Barrier& barrier) = delete; - - Barrier(Barrier&& barrier) = delete; - - Barrier& operator=(const Barrier& barrier) = delete; - - Barrier& operator=(Barrier&& barrier) = delete; - - void wait(); - - private: - std::mutex m_mutex; - std::condition_variable m_condition; - const size_t m_threads; - size_t counter[2], * currCounter; - }; -} - - - -#endif //CITYFLOW_BARRIER_H +#ifndef CITYFLOW_BARRIER_H +#define CITYFLOW_BARRIER_H +#include +#include +#include +#include +#include + +namespace CityFlow { + class Barrier { + public: + Barrier(std::size_t nb_threads) : m_threads(nb_threads), currCounter(&counter[0]) { + assert(0u != m_threads); + counter[0] = m_threads; + counter[1] = 0; + } + + Barrier(const Barrier& barrier) = delete; + + Barrier(Barrier&& barrier) = delete; + + Barrier& operator=(const Barrier& barrier) = delete; + + Barrier& operator=(Barrier&& barrier) = delete; + + void wait(); + + private: + std::mutex m_mutex; + std::condition_variable m_condition; + const size_t m_threads; + size_t counter[2], * currCounter; + }; +} + + + +#endif //CITYFLOW_BARRIER_H diff --git a/third_party/CityFlow/src/utility/config.h b/third_party/CityFlow/src/utility/config.h index f7b514cb616d2a088cadafbdb4a014f4fdce1e1f..e8a33b0d2ba39f5af2f747015ec9175ddb413504 100644 --- a/third_party/CityFlow/src/utility/config.h +++ b/third_party/CityFlow/src/utility/config.h @@ -1,8 +1,8 @@ -#ifndef CITYFLOW_CONFIG_H -#define CITYFLOW_CONFIG_H - -namespace CityFlow { - const int MAX_NUM_CARS_ON_SEGMENT = 10; -} - -#endif //CITYFLOW_CONFIG_H +#ifndef CITYFLOW_CONFIG_H +#define CITYFLOW_CONFIG_H + +namespace CityFlow { + const int MAX_NUM_CARS_ON_SEGMENT = 10; +} + +#endif //CITYFLOW_CONFIG_H diff --git a/third_party/CityFlow/src/utility/optionparser.h b/third_party/CityFlow/src/utility/optionparser.h index 666e8096e2c3710bbd1ccb642e1ea83fd0291cbe..e99200fe94fd2234213e114698c4b9b75674f904 100644 --- a/third_party/CityFlow/src/utility/optionparser.h +++ b/third_party/CityFlow/src/utility/optionparser.h @@ -1,562 +1,562 @@ -//----------------------------------------------------------------------------- -// optionparser.h -- A Header-Only commandline argument parser -// Author: Luke de Oliveira -// License: MIT -//----------------------------------------------------------------------------- - -#ifndef OPTIONPARSER_H_ -#define OPTIONPARSER_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -const std::string ARGS_END = "- "; - -namespace optionparser { - - enum StorageMode { STORE_TRUE, STORE_VALUE, STORE_MULT_VALUES }; - - enum OptionType { LONG_OPT = 0, SHORT_OPT, POSITIONAL_OPT, EMPTY_OPT }; - - struct DictionaryEntry { - unsigned int pos; - std::string name; - }; - - struct Option { - Option() {} - void help_doc() { - std::string h = " "; - if (m_long_flag != "") { - h += m_long_flag; - if (m_short_flag != "") { - h += ", "; - } - } - if (m_short_flag != "") { - h += m_short_flag; - } - - printf("%-25s%s\n", h.c_str(), m_help.c_str()); - } - - bool &found() { return m_found; } - - Option &required(bool req) { - m_required = req; - return *this; - } - bool &required() { return m_required; } - - std::string &short_flag() { return m_short_flag; } - - std::string &long_flag() { return m_long_flag; } - std::string &pos_flag() { return m_pos_flag; } - std::string m_short_flag = "", m_long_flag = "", m_pos_flag = ""; - - StorageMode &mode() { return m_mode; } - - Option &mode(const StorageMode &mode) { - m_mode = mode; - return *this; - } - - std::string &help() { return m_help; } - - Option &help(const std::string &help) { - m_help = help; - return *this; - } - - std::string &dest() { return m_dest; } - - Option &dest(const std::string &dest) { - m_dest = dest; - return *this; - } - - std::string &default_value() { return m_default_value; } - - Option &default_value(const std::string &default_value) { - m_default_value = default_value; - return *this; - } - - Option &default_value(const char *default_value) { - m_default_value = std::string(default_value); - return *this; - } - - template - Option &default_value(const T &default_value) { - m_default_value = std::to_string(default_value); - return *this; - } - - bool m_found = false; - bool m_required = false; - StorageMode m_mode = STORE_TRUE; - std::string m_help = ""; - std::string m_dest = ""; - std::string m_default_value = ""; - - static OptionType get_type(std::string opt); - static std::string get_destination(std::string opt1, std::string opt2, - OptionType ft, OptionType st); - }; -//---------------------------------------------------------------------------- - std::string remove_character(std::string str, const char c) { - // dummy way to remove -- and - from args - auto pos = str.find("--"); - - if (pos == 0) { - str.erase(0, 2); - } - - pos = str.find('-'); - if (pos == 0) { - str.erase(0, 1); - } - - return str; - } - - typedef std::map> Archive; - typedef std::map Dictionary; - - OptionType Option::get_type(std::string opt) { - if (opt == "") { - return OptionType::EMPTY_OPT; - } - - if (opt[0] == '-') { - if (opt.size() == 2) { - return OptionType::SHORT_OPT; - } - - else { - return OptionType::LONG_OPT; - } - } - return OptionType::POSITIONAL_OPT; - } - std::string Option::get_destination(std::string first_option, - std::string second_option, - OptionType first_opt_type, - OptionType second_opt_type) { - std::string dest; - - if (first_opt_type == OptionType::LONG_OPT) { - dest = remove_character(first_option, '-'); - } else if (second_opt_type == OptionType::LONG_OPT) { - dest = remove_character(second_option, '-'); - } else { - if (first_opt_type == OptionType::SHORT_OPT) { - dest = remove_character(first_option, '-') + "_option"; - } else if (second_opt_type == OptionType::SHORT_OPT) { - dest = remove_character(second_option, '-') + "_option"; - } else { - if (first_opt_type == OptionType::POSITIONAL_OPT) { - dest = first_option; - } else if (second_opt_type == OptionType::POSITIONAL_OPT) { - dest = second_option; - } - } - } - - return dest; - } -//----------------------------------------------------------------------------- -// OptionParser Class -//----------------------------------------------------------------------------- - class OptionParser { - public: - OptionParser(std::string description = "", bool create_help = true) - : m_options(0), m_description(description) { - if (create_help) { - add_option("--help", "-h").help("Display this help message and exit."); - } - } - - ~OptionParser() = default; - - void eat_arguments(unsigned int argc, char const *argv[]); - - Option &add_option(std::string first_option, std::string second_option = ""); - - template - T get_value(std::string key); - - void help(); - - private: - Option &add_option_internal(std::string longoption, std::string shortoption); - - void error(const std::string &e); - - Archive m_values; - std::vector