File: gnatcoll-python.adb

package info (click to toggle)
libgnatcoll-bindings 25.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,412 kB
  • sloc: ada: 18,696; python: 1,597; ansic: 1,422; cpp: 581; makefile: 147; sh: 114
file content (1162 lines) | stat: -rw-r--r-- 35,558 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
------------------------------------------------------------------------------
--                             G N A T C O L L                              --
--                                                                          --
--                     Copyright (C) 2003-2022, AdaCore                     --
--                                                                          --
-- This library is free software;  you can redistribute it and/or modify it --
-- under terms of the  GNU General Public License  as published by the Free --
-- Software  Foundation;  either version 3,  or (at your  option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY;  without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.                            --
--                                                                          --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception,   --
-- version 3.1, as published by the Free Software Foundation.               --
--                                                                          --
-- You should have received a copy of the GNU General Public License and    --
-- a copy of the GCC Runtime Library Exception along with this program;     --
-- see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see    --
-- <http://www.gnu.org/licenses/>.                                          --
--                                                                          --
------------------------------------------------------------------------------

with System;               use System;
with Interfaces.C.Strings; use Interfaces.C.Strings;

package body GNATCOLL.Python is

   No_Method_Def : constant PyMethodDef :=
     (Name  => Null_Ptr,
      Func  => null,
      Flags => METH_VARGS or METH_KEYWORDS,
      Doc   => Null_Ptr);

   type Methods_Access is access PyMethodDef_Array;
   type MethodDef_Access is access PyMethodDef;
   pragma Convention (C, MethodDef_Access);

   function PyCFunction_New
     (MethodDef : MethodDef_Access;
      Self      : PyObject;
      Module    : PyObject := null) return PyObject;
   pragma Import (C, PyCFunction_New, "PyCFunction_NewEx");
   --  Create a new callable object, which, when called from python, will call
   --  the Ada subprogram.
   --  Self is the first argument that will be passed to the Ada subprogram.
   --  Module is the value of the __module__ attribute for the new function.

   ------------------------
   -- PyRun_SimpleString --
   ------------------------

   function PyRun_SimpleString (Cmd : String) return Boolean is
      function Internal (Cmd : String) return Integer;
      pragma Import (C, Internal, "PyRun_SimpleString");
   begin
      return Internal (Cmd & ASCII.NUL) = 0;
   end PyRun_SimpleString;

   ------------------------
   -- PyImport_AddModule --
   ------------------------

   function PyImport_AddModule (Module_Name : String) return PyObject is
      function Internal (Name : String) return PyObject;
      pragma Import (C, Internal, "PyImport_AddModule");
   begin
      return Internal (Module_Name & ASCII.NUL);
   end PyImport_AddModule;

   ---------------------------
   -- PyImport_ImportModule --
   ---------------------------

   function PyImport_ImportModule (Module_Name : String) return PyObject is
      function Internal (Name : String) return PyObject;
      pragma Import (C, Internal, "PyImport_ImportModule");
   begin
      return Internal (Module_Name & ASCII.NUL);
   end PyImport_ImportModule;

   ------------------
   -- PyRun_String --
   ------------------

   function PyRun_String
     (Str     : String;
      Start   : Interpreter_State;
      Globals : PyObject;
      Locals  : PyObject) return PyObject
   is
      function Internal
        (Str     : String;
         Start   : Interpreter_State;
         Globals : PyObject;
         Locals  : PyObject) return PyObject;
      pragma Import (C, Internal, "PyRun_String");
   begin
      return Internal (Str & ASCII.LF, Start, Globals, Locals);
   end PyRun_String;

   ----------------------
   -- PyArg_ParseTuple --
   ----------------------

   function PyArg_ParseTuple
     (Arg    : PyObject;
      Format : String;
      Value1 : System.Address) return Boolean
   is
      function Internal
        (Arg : PyObject; Format : String; V1 : System.Address) return Integer;
      pragma Import (C, Internal, "ada_py_arg_parsetuple_ptr");
   begin
      return Internal (Arg, Format & ASCII.NUL, Value1) = 1;
   end PyArg_ParseTuple;

   function PyArg_ParseTuple
     (Arg    : PyObject;
      Format : String;
      Value1, Value2 : System.Address) return Boolean
   is
      function Internal
        (Arg : PyObject; Format : String; V1, V2 : System.Address)
         return Integer;
      pragma Import (C, Internal, "ada_py_arg_parsetuple_ptr2");
   begin
      return Internal (Arg, Format & ASCII.NUL, Value1, Value2) = 1;
   end PyArg_ParseTuple;

   function PyArg_ParseTuple
     (Arg    : PyObject;
      Format : String;
      Value1, Value2, Value3 : System.Address) return Boolean
   is
      function Internal
        (Arg : PyObject; Format : String; V1, V2, V3 : System.Address)
         return Integer;
      pragma Import (C, Internal, "ada_py_arg_parsetuple_ptr3");
   begin
      return Internal (Arg, Format & ASCII.NUL, Value1, Value2, Value3) = 1;
   end PyArg_ParseTuple;

   function PyArg_ParseTuple
     (Arg    : PyObject;
      Format : String;
      Value1, Value2, Value3, Value4 : System.Address) return Boolean
   is
      function Internal
        (Arg : PyObject; Format : String; V1, V2, V3, V4 : System.Address)
         return Integer;
      pragma Import (C, Internal, "ada_py_arg_parsetuple_ptr4");
   begin
      return Internal
        (Arg, Format & ASCII.NUL, Value1, Value2, Value3, Value4) = 1;
   end PyArg_ParseTuple;

   function PyArg_ParseTuple
     (Arg    : PyObject;
      Format : String;
      Value1, Value2, Value3, Value4, Value5 : System.Address) return Boolean
   is
      function Internal
        (Arg : PyObject; Format : String; V1, V2, V3, V4, V5 : System.Address)
         return Integer;
      pragma Import (C, Internal, "ada_py_arg_parsetuple_ptr5");
   begin
      return Internal
        (Arg, Format & ASCII.NUL, Value1, Value2, Value3, Value4, Value5) = 1;
   end PyArg_ParseTuple;

   ----------------------
   -- PyFunction_Check --
   ----------------------

   function PyFunction_Check (Func : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyfunction_check");
   begin
      return Internal (Func) = 1;
   end PyFunction_Check;

   ----------------------
   -- PyCallable_Check --
   ----------------------

   function PyCallable_Check (Func : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "PyCallable_Check");
   begin
      return Internal (Func) = 1;
   end PyCallable_Check;

   --------------------
   -- PyString_Check --
   --------------------

   function PyString_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pystring_check");
   begin
      return Internal (Obj) = 1;
   end PyString_Check;

   ---------------------
   -- PyUnicode_Check --
   ---------------------

   function PyUnicode_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyunicode_check");
   begin
      return Internal (Obj) = 1;
   end PyUnicode_Check;

   ------------------------
   -- PyBaseString_Check --
   ------------------------

   function PyBaseString_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pybasestring_check");
   begin
      return Internal (Obj) = 1;
   end PyBaseString_Check;

   ------------------
   -- PyList_Check --
   ------------------

   function PyList_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pylist_check");
   begin
      return Internal (Obj) = 1;
   end PyList_Check;

   ------------------
   -- PyIter_Check --
   ------------------

   function PyIter_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyiter_check");
   begin
      return Internal (Obj) = 1;
   end PyIter_Check;

   -----------------
   -- PyInt_Check --
   -----------------

   function PyInt_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyint_check");
   begin
      return Internal (Obj) = 1;
   end PyInt_Check;

   ------------------
   -- PyLong_Check --
   ------------------

   function PyLong_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pylong_check");
   begin
      return Internal (Obj) = 1;
   end PyLong_Check;

   -------------------
   -- PyFloat_Check --
   -------------------

   function PyFloat_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyfloat_check");
   begin
      return Internal (Obj) = 1;
   end PyFloat_Check;

   ------------------------
   -- PyBool_FromBoolean --
   ------------------------

   function PyBool_FromBoolean (Value : Boolean) return PyObject is
      function PyTrue return PyObject;
      pragma Import (C, PyTrue, "ada_py_true");

      function PyFalse return PyObject;
      pragma Import (C, PyFalse, "ada_py_false");

      Result : PyObject;
   begin
      if Value then
         Result := PyTrue;
      else
         Result := PyFalse;
      end if;

      Py_INCREF (Result);
      return Result;
   end PyBool_FromBoolean;

   ------------------
   -- PyBool_Check --
   ------------------

   function PyBool_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pybool_check");
   begin
      return Internal (Obj) = 1;
   end PyBool_Check;

   --------------------
   -- PyBool_Is_True --
   --------------------

   function PyBool_Is_True (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pybool_is_true");
   begin
      return Internal (Obj) = 1;
   end PyBool_Is_True;

   -------------------
   -- PyTuple_Check --
   -------------------

   function PyTuple_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pytuple_check");
   begin
      return Internal (Obj) = 1;
   end PyTuple_Check;

   ----------------------
   -- PyObject_GetItem --
   ----------------------

   function PyObject_GetItem (Obj : PyObject; Key : Integer) return PyObject is
      K      : PyObject;
      Result : PyObject;
   begin
      K := PyInt_FromLong (Interfaces.C.long (Key));
      Result := PyObject_GetItem (Obj, K);
      Py_DECREF (K);
      return Result;
   end PyObject_GetItem;

   ----------------------
   -- PyObject_SetItem --
   ----------------------

   procedure PyObject_SetItem
     (Obj : PyObject; Key : Integer; Value : PyObject)
   is
      K      : PyObject;
      Result : Integer;
      pragma Unreferenced (Result);
   begin
      K := PyInt_FromLong (Interfaces.C.long (Key));
      Result := PyObject_SetItem (Obj, K, Value);
      Py_DECREF (K);
   end PyObject_SetItem;

   -----------------------
   -- PyString_AsString --
   -----------------------

   function PyString_AsString (Str : PyObject) return String is
      function Low (Str : PyObject) return Interfaces.C.Strings.chars_ptr;
      pragma Import (C, Low, "ada_PyString_AsString");
      --  Returns a NULL terminated representation of the contents of string.
      --  Result value must be freed.

      C : constant Interfaces.C.Strings.chars_ptr := Low (Str);
   begin
      if C = Null_Ptr then
         return "";
      else
         declare
            R : constant String := Value (C);

            procedure C_Free (S : chars_ptr);
            pragma Import (C, C_Free, "free");

         begin
            --  Since C was allocated by ada_PyString_AsString via strdup(),
            --  and not via System.Memory, we should not be using
            --  Interfaces.C.Strings.Free which goes through System.Memory.
            --  So we call free() directly instead.
            C_Free (C);
            return R;
         end;
      end if;
   end PyString_AsString;

   -------------------------
   -- PyString_FromString --
   -------------------------

   function PyString_FromString (Str : String) return PyObject is
      function Internal (Str : String; Size : Integer) return PyObject;
      pragma Import (C, Internal, "PyString_FromStringAndSize");
   begin
      return Internal (Str, Str'Length);
   end PyString_FromString;

   --------------------------
   -- PyUnicode_FromString --
   --------------------------

   function PyUnicode_FromString (Str : String) return PyObject is
      function Internal (Str : String) return PyObject;
      pragma Import (C, Internal, "ada_PyUnicode_FromString");
   begin
      return Internal (Str & ASCII.NUL);
   end PyUnicode_FromString;

   -------------------------------
   -- PyUnicode_AsEncodedString --
   -------------------------------

   function PyUnicode_AsEncodedString
     (Unicode  : PyObject;
      Encoding : String;
      Errors   : Unicode_Error_Handling := Strict)
      return PyObject
   is
      function Internal
        (Unicode : PyObject; Encoding, Errors : String) return PyObject;
      pragma Import (C, Internal, "ada_PyUnicode_AsEncodedString");
   begin
      case Errors is
         when Strict =>
            return Internal
              (Unicode, Encoding & ASCII.NUL, "strict" & ASCII.NUL);
         when Ignore =>
            return Internal
              (Unicode, Encoding & ASCII.NUL, "ignore" & ASCII.NUL);
         when Replace =>
            return Internal
              (Unicode, Encoding & ASCII.NUL, "replace" & ASCII.NUL);
      end case;
   end PyUnicode_AsEncodedString;

   ----------------------
   -- Unicode_AsString --
   ----------------------

   function Unicode_AsString
     (Str : PyObject; Encoding : String := "utf-8") return String
   is
      S : constant PyObject := PyUnicode_AsEncodedString
        (Unicode => Str, Encoding => Encoding, Errors => Replace);
      Result : constant String := PyString_AsString (S);
   begin
      Py_DECREF (S);
      return Result;
   end Unicode_AsString;

   ---------------------
   -- PySys_SetObject --
   ---------------------

   procedure PySys_SetObject (Name : String; Object : PyObject) is
      procedure Internal (Name : String; Object : PyObject);
      pragma Import (C, Internal, "PySys_SetObject");
   begin
      Internal (Name & ASCII.NUL, Object);
   end PySys_SetObject;

   ---------------------
   -- PySys_GetObject --
   ---------------------

   function PySys_GetObject (Name : String) return PyObject is
      function Internal (Name : String) return PyObject;
      pragma Import (C, Internal, "PySys_GetObject");
   begin
      return Internal (Name & ASCII.NUL);
   end PySys_GetObject;

   -------------------------
   -- PyObject_CallMethod --
   -------------------------

   function PyObject_CallMethod
     (Object : PyObject; Name : String) return PyObject
   is
      function Internal (Object : PyObject; Name : String) return PyObject;
      pragma Import (C, Internal, "ada_py_object_callmethod");
   begin
      return Internal (Object, Name & ASCII.NUL);
   end PyObject_CallMethod;

   function PyObject_CallMethod
     (Object : PyObject; Name : String; Arg1 : PyObject) return PyObject
   is
      function Internal
        (Object : PyObject; Name : String; Arg : PyObject) return PyObject;
      pragma Import (C, Internal, "ada_py_object_callmethod_obj");
   begin
      return Internal (Object, Name & ASCII.NUL, Arg1);
   end PyObject_CallMethod;

   function PyObject_CallMethod
     (Object : PyObject; Name : String; Arg1 : Integer) return PyObject
   is
      function Internal
        (Object : PyObject; Name : String; Arg : Integer) return PyObject;
      pragma Import (C, Internal, "ada_py_object_callmethod_int");
   begin
      return Internal (Object, Name & ASCII.NUL, Arg1);
   end PyObject_CallMethod;

   ----------------------
   -- Py_CompileString --
   ----------------------

   function Py_CompileString
     (Cmd : String; Name : String; State : Interpreter_State)
      return PyCodeObject
   is
      function Internal (Cmd, Name : String; State : Interpreter_State)
         return PyCodeObject;
      pragma Import (C, Internal, "Py_CompileString");
   begin
      return Internal (Cmd & ASCII.NUL, Name & ASCII.NUL, State);
   end Py_CompileString;

   ------------------
   -- PyDict_Check --
   ------------------

   function PyDict_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pydict_check");
   begin
      return Internal (Obj) /= 0;
   end PyDict_Check;

   --------------------
   -- PyAnySet_Check --
   --------------------

   function PyAnySet_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pyanyset_check");
   begin
      return Internal (Obj) /= 0;
   end PyAnySet_Check;

   --------------------------
   -- PyDict_SetItemString --
   --------------------------

   procedure PyDict_SetItemString
     (Dict : PyDictObject; Key : String; Obj : PyObject)
   is
      S      : chars_ptr := New_String (Key);
      Result : constant Integer := PyDict_SetItemString (Dict, S, Obj);
      pragma Unreferenced (Result);
   begin
      Free (S);
   end PyDict_SetItemString;

   ------------------------
   -- PyModule_AddObject --
   ------------------------

   function PyModule_AddObject
     (Module : PyObject; Name : String;  Object : PyObject) return Integer
   is
      S      : chars_ptr := New_String (Name);
      Result : Integer;
   begin
      Result := PyModule_AddObject (Module, S, Object);
      Free (S);
      return Result;
   end PyModule_AddObject;

   --------------------------
   -- PyDict_GetItemString --
   --------------------------

   function PyDict_GetItemString
     (Dict : PyDictObject; Key : String) return PyObject
   is
      S      : chars_ptr := New_String (Key);
      Result : constant PyObject := PyDict_GetItemString (Dict, S);
   begin
      Free (S);
      return Result;
   end PyDict_GetItemString;

   ------------------
   -- Create_Tuple --
   ------------------

   function Create_Tuple (Objects : PyObject_Array) return PyObject is
      Tuple : constant PyObject := PyTuple_New (Objects'Length);
   begin
      for O in Objects'Range loop
         PyTuple_SetItem (Tuple, O - Objects'First, Objects (O));
      end loop;
      return Tuple;
   end Create_Tuple;

   ------------------------
   -- PyErr_NewException --
   ------------------------

   function PyErr_NewException
     (Name : String; Base : PyObject := null; Dict : PyObject := null)
      return PyObject
   is
      function Internal (Name : String; Base, Dict : PyObject) return PyObject;
      pragma Import (C, Internal, "PyErr_NewException");
   begin
      return Internal (Name & ASCII.NUL, Base, Dict);
   end PyErr_NewException;

   ---------------------
   -- PyErr_SetString --
   ---------------------

   procedure PyErr_SetString (Except : PyObject; Msg : String) is
      procedure Internal (Except : PyObject; Msg : String);
      pragma Import (C, Internal, "PyErr_SetString");
   begin
      Internal (Except, Msg & ASCII.NUL);
   end PyErr_SetString;

   ----------------------------
   -- PyObject_GetAttrString --
   ----------------------------

   function PyObject_GetAttrString
     (Object : PyObject; Name : String) return PyObject
   is
      function Internal (Object : PyObject; S : String) return PyObject;
      pragma Import (C, Internal, "PyObject_GetAttrString");
   begin
      return Internal (Object, Name & ASCII.NUL);
   end PyObject_GetAttrString;

   ----------------------------
   -- PyObject_HasAttrString --
   ----------------------------

   function PyObject_HasAttrString
     (Obj : PyObject; Attr_Name : String) return Boolean
   is
      function Internal (Object : PyObject; S : String) return Integer;
      pragma Import (C, Internal, "PyObject_HasAttrString");
   begin
      return Boolean'Val (Internal (Obj, Attr_Name & ASCII.NUL));
   end PyObject_HasAttrString;

   ----------------------------
   -- PyObject_SetAttrString --
   ----------------------------

   procedure PyObject_SetAttrString
     (Obj : PyObject; Attr_Name : String; Value : PyObject)
   is
      procedure Internal (Obj : PyObject; Name : String; Val : PyObject);
      pragma Import (C, Internal, "PyObject_SetAttrString");
   begin
      Internal (Obj, Attr_Name & ASCII.NUL, Value);
   end PyObject_SetAttrString;

   ----------------------------
   -- PyObject_SetAttrString --
   ----------------------------

   function PyObject_SetAttrString
     (Obj : PyObject; Attr_Name : String; Value : PyObject) return Integer
   is
      function Internal
        (Obj : PyObject; Name : String; Val : PyObject) return Integer;
      pragma Import (C, Internal, "PyObject_SetAttrString");
   begin
      return Internal (Obj, Attr_Name & ASCII.NUL, Value);
   end PyObject_SetAttrString;

   -----------------------------------
   -- PyObject_GenericSetAttrString --
   -----------------------------------

   function PyObject_GenericSetAttrString
     (Object : PyObject;
      Name   : String;
      Attr   : PyObject) return Integer
   is
      N : constant PyObject := PyString_FromString (Name);
      Result : Integer;
   begin
      Result := PyObject_GenericSetAttr (Object, N, Attr);
      Py_DECREF (N);
      return Result;
   end PyObject_GenericSetAttrString;

   ---------------------
   -- PyDict_Contains --
   ---------------------

   function PyDict_Contains
     (Dict : PyDictObject; Key : PyObject) return Boolean
   is
      function Internal (Dict : PyObject; Key : PyObject) return Integer;
      pragma Import (C, Internal, "PyDict_Contains");

   begin
      return Internal (Dict, Key) = 1;
   end PyDict_Contains;

   -----------------
   -- PyDict_Next --
   -----------------

   procedure PyDict_Next
     (Dict  : PyObject;
      Pos   : in out Integer;
      Key   : out PyObject;
      Value : out PyObject)
   is
      function Internal
        (Dict : PyObject; Pos, Key, Value : System.Address) return Integer;
      pragma Import (C, Internal, "PyDict_Next");

      P : Interfaces.C.size_t := Interfaces.C.size_t (Pos);

   begin
      if Internal (Dict, P'Address, Key'Address, Value'Address) = 0 then
         Pos := -1;
      else
         Pos := Integer (P);
      end if;
   end PyDict_Next;

   --------------------
   -- Print_Refcount --
   --------------------

   procedure Print_Refcount (Obj : PyObject; Msg : String) is
      procedure Internal (Obj : PyObject; Msg : String);
      pragma Import (C, Internal, "ada_py_print_refcount");
   begin
      Internal (Obj, Msg & ASCII.NUL);
   end Print_Refcount;

   ------------------------
   -- PyFile_WriteString --
   ------------------------

   function PyFile_WriteString
     (Text : String; File : PyObject) return Boolean
   is
      function Internal (Text : String; File : PyObject) return Integer;
      pragma Import (C, Internal, "PyFile_WriteString");
   begin
      return Internal (Text & ASCII.NUL, File) /= 0;
   end PyFile_WriteString;

   -----------------------
   -- PyFile_FromString --
   -----------------------

   function PyFile_FromString (File_Name, Mode : String) return PyObject is
      function Internal (N, M : String) return PyObject;
      pragma Import (C, Internal, "PyFile_FromString");
   begin
      return Internal (File_Name & ASCII.NUL, Mode & ASCII.NUL);
   end PyFile_FromString;

   -------------------
   -- Py_InitModule --
   -------------------

   function Py_InitModule
     (Module_Name : String;
      Methods     : PyMethodDef_Array := No_MethodDef_Array;
      Doc         : String := "") return PyObject
   is
      function Internal
        (N       : String;
         Methods : System.Address;
         Doc     : String;
         Self    : PyObject := null) return PyObject;
      pragma Import (C, Internal, "ada_Py_InitModule4");

      M : Methods_Access;
   begin
      if Methods /= No_MethodDef_Array then
         --  ??? Memory is never freed, but Python is not supposed to be killed
         --  before the end of the application
         M := new PyMethodDef_Array'(Methods & No_Method_Def);
         return Internal
           (Module_Name & ASCII.NUL, M.all'Address,
            Doc & ASCII.NUL);

      else
         return Internal
           (Module_Name & ASCII.NUL, System.Null_Address,
            Doc & ASCII.NUL);
      end if;
   end Py_InitModule;

   ----------
   -- Free --
   ----------

   procedure Free (Method : in out PyMethodDef) is
      procedure C_Free (C : Interfaces.C.Strings.chars_ptr);
      pragma Import (C, C_Free, "free");

   begin
      C_Free (Method.Name);
      C_Free (Method.Doc);
      Method.Name := Null_Ptr;
      Method.Doc := Null_Ptr;
   end Free;

   ----------
   -- Free --
   ----------

   procedure Free (Methods : in out PyMethodDef_Array) is
   begin
      for M in Methods'Range loop
         Free (Methods (M));
      end loop;
   end Free;

   ------------------
   -- PyModule_New --
   ------------------

   function PyModule_New (Module_Name : String) return PyObject is
      function Internal (N : String) return PyObject;
      pragma Import (C, Internal, "PyModule_New");
   begin
      return Internal (Module_Name & ASCII.NUL);
   end PyModule_New;

   ----------------------
   -- PyModule_Getname --
   ----------------------

   function PyModule_Getname (Module : PyObject) return String is
      function Internal (M : PyObject) return Interfaces.C.Strings.chars_ptr;
      pragma Import (C, Internal, "PyModule_GetName");
   begin
      return Value (Internal (Module));
   end PyModule_Getname;

   ------------------
   -- Add_Function --
   ------------------

   procedure Add_Function
     (Module : PyObject; Func : PyMethodDef; Self : PyObject := null)
   is
      C_Func : PyObject;
      Result : Integer;
      pragma Unreferenced (Result);
      Def : constant MethodDef_Access := new PyMethodDef'(Func);
   begin
      Def.Flags := Def.Flags or METH_KEYWORDS or METH_VARGS;
      if Self /= null then
         C_Func := PyCFunction_New
           (Def, Self,
            PyString_FromString (PyModule_Getname (Module)));
      else
         C_Func := PyCFunction_New
           (Def, Module,
            PyString_FromString (PyModule_Getname (Module)));
      end if;

      if C_Func /= null then
         Result := PyModule_AddObject (Module, Func.Name, C_Func);
      end if;
   end Add_Function;

   ----------------
   -- Add_Method --
   ----------------

   procedure Add_Method
     (Class : PyObject;
      Func  : PyMethodDef;
      Self  : PyObject := null;
      Module : PyObject)
   is
      procedure Add_Method
        (Func   : MethodDef_Access;
         Self   : PyObject;
         Class  : PyObject;
         Module : PyObject);
      pragma Import (C, Add_Method, "ada_py_add_method");
      Def : constant MethodDef_Access := new PyMethodDef'(Func);
   begin
      Def.Flags := Def.Flags or METH_KEYWORDS or METH_VARGS;
      Add_Method (Def, Self, Class, Module);
   end Add_Method;

   -----------------------
   -- Add_Static_Method --
   -----------------------

   procedure Add_Static_Method
     (Class : PyObject; Func : PyMethodDef; Self : PyObject := null;
      Module : PyObject)
   is
      function PyStaticMethod_New (Method : PyObject) return PyObject;
      pragma Import (C, PyStaticMethod_New, "PyStaticMethod_New");

      Def    : constant MethodDef_Access := new PyMethodDef'(Func);
      C_Func : PyObject;
      Static : PyObject;
      Result : Integer;
      pragma Unreferenced (Result);
   begin
      if Self = null then
         --  Declare the method static only if self is set to null. If the
         --  function is declared METH_STATIC self will never be passed.
         --  GNATCOLL.Scripts.Python uses self to pass user data to the
         --  called function (i.e: to simulate a closure).
         --  WARNING: There is no warranty that in future Python version this
         --  will work as expected.
         Def.Flags := Def.Flags or METH_STATIC;
      end if;

      C_Func := PyCFunction_New
        (Def, Self, PyString_FromString (PyModule_Getname (Module)));

      if C_Func /= null then
         --  The PyStaticMeThod_New does not seems to be mandatory and not
         --  documented in the public API, but still used internally by
         --  Python 3.8.x. Does it play a role regarding memory ?
         Static := PyStaticMethod_New (C_Func);
         Result := PyObject_SetAttrString (Class, Func.Name, Static);
         Py_DECREF (Static);
      end if;
   end Add_Static_Method;

   ----------------------
   -- Add_Class_Method --
   ----------------------

   procedure Add_Class_Method
     (Class : PyObject; Func : PyMethodDef; Module : PyObject)
   is
      function PyClassMethod_New (Method : PyObject) return PyObject;
      pragma Import (C, PyClassMethod_New, "PyClassMethod_New");

      Def    : constant MethodDef_Access := new PyMethodDef'(Func);
      C_Func : PyObject;
      Result : Integer;
      Meth   : PyObject;
      pragma Unreferenced (Result);
   begin
      Def.Flags := Def.Flags or METH_CLASS;

      C_Func := PyCFunction_New
        (Def, null, PyString_FromString (PyModule_Getname (Module)));
      if C_Func /= null then
         Meth := PyClassMethod_New (C_Func);
         Result := PyObject_SetAttrString (Class, Func.Name, Meth);
         Py_DECREF (Meth);
      end if;
   end Add_Class_Method;

   -----------------------
   -- PyDescr_NewGetSet --
   -----------------------

   function PyDescr_NewGetSet
     (Typ     : PyObject;
      Name    : String;
      Setter  : C_Setter := null;
      Getter  : C_Getter := null;
      Doc     : String   := "";
      Closure : System.Address := System.Null_Address) return Boolean
   is
      function To_Callback is new Standard.Ada.Unchecked_Conversion
        (C_Getter, C_Callback);
      function To_Callback is new Standard.Ada.Unchecked_Conversion
        (C_Setter, C_Callback);

      function Internal
        (Typ : PyObject; Name : chars_ptr;
         Setter, Getter : C_Callback; Doc : chars_ptr;
         Closure : System.Address) return Integer;
      pragma Import (C, Internal, "ada_pydescr_newGetSet");
   begin
      return Internal
        (Typ, New_String (Name), To_Callback (Setter),
         To_Callback (Getter), New_String (Doc), Closure) /= 0;
   end PyDescr_NewGetSet;

   -----------------------
   -- Create_Method_Def --
   -----------------------

   function Create_Method_Def
     (Name : String;
      Func : C_Method_Vargs;
      Doc  : String := "")
      return PyMethodDef is
   begin
      return (Name  => New_String (Name),
              Func  => To_Callback (Func),
              Flags => METH_KEYWORDS or METH_VARGS,
              Doc   => New_String (Doc));
   end Create_Method_Def;

   -----------------------
   -- Create_Method_Def --
   -----------------------

   function Create_Method_Def
     (Name : String;
      Func : C_Method_Keywords;
      Doc  : String := "")
      return PyMethodDef
   is
      D : chars_ptr := Null_Ptr;
   begin
      if Doc /= "" then
         D := New_String (Doc);
      end if;

      return (Name  => New_String (Name),
              Func  => To_Callback (Func),
              Flags => METH_KEYWORDS or METH_VARGS,
              Doc   => D);
   end Create_Method_Def;

   -------------------
   -- Lookup_Object --
   -------------------

   function Lookup_Object
     (Module : String; Name : String) return PyObject is
   begin
      return Lookup_Object (PyImport_AddModule (Module), Name);
   end Lookup_Object;

   -------------------
   -- Lookup_Object --
   -------------------

   function Lookup_Object
     (Module : PyObject; Name : String) return PyObject
   is
      Dict   : PyObject;
   begin
      if Module /= null then
         Dict := PyModule_GetDict (Module);
         return PyDict_GetItemString (Dict, Name);
      end if;
      return null;
   end Lookup_Object;

   --------------------
   -- PyMethod_Check --
   --------------------

   function PyMethod_Check (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "ada_pymethod_check");
   begin
      return Internal (Obj) = 1;
   end PyMethod_Check;

   -------------------
   -- Py_IsSubclass --
   -------------------

   function Py_IsSubclass
     (Class : PyObject; Base : PyObject) return Boolean
   is
      function Internal (Class, Base : PyObject) return Integer;
      pragma Import (C, Internal, "ada_is_subclass");
   begin
      return Internal (Class, Base) /= 0;
   end Py_IsSubclass;

   --------------
   -- Type_New --
   --------------

   function Type_New
     (Name     : String;
      Bases    : PyTuple;
      Dict     : PyObject;
      Metatype : PyTypeObject := null) return PyObject
   is
      function Internal
        (Meta  : PyTypeObject;
         Name  : Interfaces.C.Strings.chars_ptr;
         Bases : PyObject;
         Dict  : PyObject) return PyObject;
      pragma Import (C, Internal, "ada_type_new");

      C : chars_ptr := New_String (Name);
      Result : PyObject;

   begin
      Result := Internal (Metatype, C, Bases, Dict);
      Free (C);
      return Result;
   end Type_New;

   ---------
   -- Name --
   ----------

   function Name (Obj : PyTypeObject) return String is
      function Internal (Obj : PyTypeObject) return chars_ptr;
      pragma Import (C, Internal, "ada_tp_name");

   begin
      return Value (Internal (Obj));
   end Name;

   -------------------------
   -- PyObject_IsInstance --
   -------------------------

   function PyObject_IsInstance
     (Inst : PyObject; Cls : PyObject) return Boolean
   is
      function Internal (Inst, Cls : PyObject) return Integer;
      pragma Import (C, Internal, "PyObject_IsInstance");
   begin
      return Internal (Inst, Cls) /= 0;
   end PyObject_IsInstance;

   ---------------------
   -- PyObject_IsTrue --
   ---------------------

   function PyObject_IsTrue (Obj : PyObject) return Boolean is
      function Internal (Obj : PyObject) return Integer;
      pragma Import (C, Internal, "PyObject_IsTrue");
      Val : Integer;
   begin
      Val := Internal (Obj);
      if Val = -1 then
         return False;  --  An error
      else
         return Val /= 0;
      end if;
   end PyObject_IsTrue;

end GNATCOLL.Python;