/
clipsmodule.c
19657 lines (17599 loc) · 575 KB
/
clipsmodule.c
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
/* clipsmodule.c
*
* Python module to embed CLIPS into Python.
* $Id: clipsmodule.c 345 2008-02-22 17:44:54Z Franz $
* (c) 2002-2008 - Francesco Garosi/JKS
*/
/* LICENSE INFORMATION
# (c) 2002-2008 Francesco Garosi/JKS
# The author's copyright is expressed through the following notice, thus
# giving effective rights to copy and use this software to anyone, as shown
# in the license text.
#
# NOTICE:
# This software is released under the terms of the GNU Lesser General Public
# license; a copy of the text has been released with this package (see file
# _license.py, where the license text also appears), and can be found on the
# GNU web site, at the following address:
#
# http://www.gnu.org/copyleft/lesser.html
#
# Please refer to the license text for any license information. This notice
# has to be considered part of the license, and should be kept on every copy
# integral or modified, of the source files. The removal of the reference to
# the license will be considered an infringement of the license itself.
*/
#include "clipsmodule.h"
/* some configuration values that should generally not be changed */
#define MIN_PPBUFFER_SIZE 256 /* minimum pretty print buffer size */
/* the module documentation string, in perfect Python style */
static char clips__doc__[] =
"_clips - a low-level portable interface to the CLIPS system for Python\n"
" (c) 2002-2008 Francesco Garosi/JKS";
/* the release string, in case it should be used someday */
static char *clips__revision__ =
"$Id: clipsmodule.c 345 2008-02-22 17:44:54Z Franz $";
/* module scope exception */
PyObject *PyExc_ClipsError = NULL;
PyObject *PyExc_ClipsMemoryError = NULL;
/* module scope router dictionary */
static PyDictObject *clips_Streams = NULL;
/* module scope functions dictionary */
static PyDictObject *clips_PythonFunctions = NULL;
/* literal helpers */
/* this is to fail uniformly, assuming there is a "fail:" label */
#define FAIL() do { goto fail; } while(0)
#define BEGIN_FAIL fail:
#define END_FAIL return NULL;
/* to add manifest integer constants to module dictionary */
#define ADD_MANIFEST_CONSTANT(dict, name) \
PyDict_SetItemString((dict), #name, PyInt_FromLong((long)(name)))
/* I always define this */
#define SKIP()
/* this also might be useful */
#define TRACE(s) fprintf(stderr, s "\n");
/* perform all the job to return the None object and other standard things */
#define RETURN_PYOBJECT(_p) do { return (PyObject *)(_p); } while(0)
#define RETURN_INT(_i) do { return Py_BuildValue("i", (_i)); } while(0)
#define RETURN_BOOL(_i) do { return Py_BuildValue("i", (_i) ? 1 : 0); } while(0)
#define RETURN_STR(_s) do { return Py_BuildValue("s", (_s)); } while(0)
/* this is not defined for Python < 2.4 */
#ifdef Py_RETURN_NONE
#define RETURN_NONE() Py_RETURN_NONE
#else
#define RETURN_NONE() do { Py_INCREF(Py_None); return Py_None; } while(0)
#endif /* Py_RETURN_NONE */
/* inlining might be useful in some cases */
#ifdef __GNUC__
#define F_INLINE __inline__
#else
#ifdef _MSC_VER
#define F_INLINE __inline
#else
#define F_INLINE
#endif /* _MSC_VER */
#endif /* __GNUC__ */
/* some common strings to save space */
static char _error_object_creation[] = "P01: object could not be created";
/* static char _error_clips_generic[] = "C00: generic clips error"; */ /* NOT USED */
static char _error_clips_creation[] = "C01: system object could not be created";
static char _error_clips_notfound[] = "C02: construct or object could not be found";
static char _error_clips_readonly[] = "C03: object cannot be modified";
static char _error_clips_fileio[] = "C04: could not open file";
static char _error_clips_noenv[] = "C05: could not get current environment";
static char _error_clips_retval[] = "C06: unable to retrieve value";
static char _error_clips_parsefile[] = "C07: unable to parse file";
static char _error_clips_parseexpr[] = "C08: syntax error, or unable to parse expression";
static char _error_clips_parsearg[] = "C09: unable to understand argument";
static char _error_clips_evalexpr[] = "C10: unable to evaluate expression";
static char _error_clips_remove[] = "C11: could not remove construct or object";
static char _error_clips_assert[] = "C12: could not assert";
/* static char _error_clips_beyond[] = "C13: beyond last element"; */ /* NOT USED */
static char _error_clips_funccall[] = "C14: unsuccessful function call";
static char _error_clips_reassert[] = "C15: cannot reassert or modify fact";
static char _error_clips_unimplemented[] = "C98: unimplemented feature/function";
static char _error_clips_impossible[] = "C99: could not perform operation";
/* static char _error_clipssys_generic[] = "S00: generic engine error"; */ /* NOT USED */
static char _error_clipssys_garbfact[] = "S01: fact does not exist anymore";
static char _error_clipssys_garbinstance[] = "S02: instance does not exist anymore";
static char _error_clipssys_envnoclear[] = "S03: environment could not be cleared";
static char _error_clipssys_badenv[] = "S04: environment is invalid";
static char _error_clipssys_curenv[] = "S05: aliasing current environment might corrupt system";
static char _error_clipssys_maxenv[] = "S06: maximum number of environments reached";
static char _error_clipssys_cleanup[] = "S07: cannot force cleanup while rules are executing";
/* static char _error_clipsmem_generic[] = "X00: generic memory error"; */ /* NOT USED */
static char _error_clipsmem_out[] = "X01: out of memory, system may be inconsistent";
static char _error_router_invalid[] = "R01: invalid logical buffer operation";
static char _error_router_nostream[] = "R02: logical buffer not found";
static char _error_router_readonly[] = "R03: buffer is read-only";
/* common helpers for common exceptions */
#define ERROR_CLIPS(s) PyErr_SetString(PyExc_ClipsError, (s))
#define ERROR_CLIPS_MEMORY(s) PyErr_SetString(PyExc_ClipsMemoryError, (s))
#define ERROR_VALUE(s) PyErr_SetString(PyExc_ValueError, (s))
#define ERROR_TYPE(s) PyErr_SetString(PyExc_TypeError, (s))
#define ERROR_IO(s) PyErr_SetString(PyExc_IOError, (s))
#define ERROR_MEMORY(s) PyErr_SetString(PyExc_MemoryError, (s))
#define ERROR_MEMORY_CREATION() ERROR_MEMORY(_error_object_creation)
#define ERROR_UNIMPLEMENTED() ERROR_CLIPS(_error_clips_unimplemented)
#define ERROR_CLIPS_IMPOSSIBLE() ERROR_CLIPS(_error_clips_impossible)
#define ERROR_CLIPS_GENERIC() ERROR_CLIPS(_error_clips_generic)
#define ERROR_CLIPS_CREATION() ERROR_CLIPS(_error_clips_creation)
#define ERROR_CLIPS_NOTFOUND() ERROR_CLIPS(_error_clips_notfound)
#define ERROR_CLIPS_READONLY() ERROR_CLIPS(_error_clips_readonly)
#define ERROR_CLIPS_IO() ERROR_IO(_error_clips_fileio)
#define ERROR_CLIPS_NOENV() ERROR_CLIPS(_error_clips_noenv)
#define ERROR_CLIPS_RETVAL() ERROR_CLIPS(_error_clips_retval)
#define ERROR_CLIPS_PARSEF() ERROR_CLIPS(_error_clips_parsefile)
#define ERROR_CLIPS_PARSEX() ERROR_CLIPS(_error_clips_parseexpr)
#define ERROR_CLIPS_PARSEA() ERROR_CLIPS(_error_clips_parsearg)
#define ERROR_CLIPS_EVALX() ERROR_CLIPS(_error_clips_evalexpr)
#define ERROR_CLIPS_REMOVE() ERROR_CLIPS(_error_clips_remove)
#define ERROR_CLIPS_ASSERT() ERROR_CLIPS(_error_clips_assert)
#define ERROR_CLIPS_FUNCCALL() ERROR_CLIPS(_error_clips_funccall)
#define ERROR_CLIPS_REASSERT() ERROR_CLIPS(_error_clips_reassert)
#define ERROR_CLIPS_OTHER(s) ERROR_CLIPS("C90: " s)
#define ERROR_CLIPSSYS_GENERIC() ERROR_CLIPS(_error_clipssys_generic)
#define ERROR_CLIPSSYS_GARBFACT() ERROR_CLIPS(_error_clipssys_garbfact)
#define ERROR_CLIPSSYS_GARBINSTANCE() ERROR_CLIPS(_error_clipssys_garbinstance)
#define ERROR_CLIPSSYS_ENVUNINIT() ERROR_CLIPS(_error_clipssys_envuninit)
#define ERROR_CLIPSSYS_ENVNOCLEAR() ERROR_CLIPS(_error_clipssys_envnoclear)
#define ERROR_CLIPSSYS_BADENV() ERROR_CLIPS(_error_clipssys_badenv)
#define ERROR_CLIPSSYS_CURENV() ERROR_CLIPS(_error_clipssys_curenv)
#define ERROR_CLIPSSYS_MAXENV() ERROR_CLIPS(_error_clipssys_maxenv)
#define ERROR_CLIPSSYS_CLEANUP() ERROR_CLIPS(_error_clipssys_cleanup)
#define ERROR_CLIPSMEM_OUT() ERROR_CLIPS_MEMORY(_error_clipsmem_out)
#define ERROR_ROUTER_INVALID() ERROR_CLIPS(_error_router_invalid)
#define ERROR_ROUTER_NOSTREAM() ERROR_CLIPS(_error_router_nostream)
#define ERROR_ROUTER_READONLY() ERROR_CLIPS(_error_router_readonly)
/* unimplemented function builder */
#define UNIMPLEMENT(s, sn) \
static char sn##__doc__[] = \
"unimplemented feature/function"; \
static PyObject *sn(PyObject *_self, PyObject *_args) { \
ERROR_UNIMPLEMENTED(); \
return NULL; \
}
/* invalid CLIPS version function builder: the error string is hardcoded
* in order to avoid a warning
*/
#define UNIMPLEMENT_VERSION(s, sn) \
static char sn##__doc__[] = \
"higher engine version required for feature/function"; \
static PyObject *sn(PyObject *_self, PyObject *_args) { \
ERROR_CLIPS("C97: higher engine version required"); \
return NULL; \
}
/* simplify writing entries in the method map */
#define MMAP_ENTRY(s, sn) { #s, sn, METH_VARARGS, sn##__doc__ }
/* check for no argument and fail if not */
#define CHECK_NOARGS(_a) do { \
if(!PyArg_ParseTuple((_a), "")) FAIL(); } while(0)
#ifdef ALLOW_CURRENT_ENVIRONMENT_ALIASING
#define CHECK_NOCURENV(_e)
#else
/* check for environment not to be current and fail if it is */
#define CHECK_NOCURENV(_e) do { \
if(clips_environment_value(_e) == GetCurrentEnvironment()) { \
ERROR_CLIPSSYS_CURENV(); \
FAIL(); \
} \
} while(0)
#endif /* ALLOW_CURRENT_ENVIRONMENT_ALIASING */
/* Macros to enable/disable memory checking on a per-function basis:
* note that the second macro must always be used when the first is
* used, and immediately after each memory allocating function has
* been called. A good point to call the RELEASE part is just before
* returning control to Python, while a good point to call ACQUIRE
* is at the beginning of the memory allocating function.
*/
#ifdef USE_MEMORY_ERROR_HANDLER
#define ACQUIRE_MEMORY_ERROR() do { \
if(setjmp(env_OutOfMemory)) { \
env_OutOfMemory_isSet = FALSE; \
ERROR_CLIPSMEM_OUT(); \
FAIL(); \
} else \
env_OutOfMemory_isSet = TRUE; \
} while(0)
#define RELEASE_MEMORY_ERROR() env_OutOfMemory_isSet = FALSE
#else
#define ACQUIRE_MEMORY_ERROR()
#define RELEASE_MEMORY_ERROR()
#endif /* USE_MEMORY_ERROR_HANDLER */
/* status function builder */
#define FUNC_GET_ONLY(_py, _sn, _api, _type) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
int _i = 0; \
CHECK_NOARGS(_args); \
ACQUIRE_MEMORY_ERROR(); \
_i = _api(); \
RELEASE_MEMORY_ERROR(); \
return Py_BuildValue(_type, _i); \
BEGIN_FAIL \
END_FAIL \
}
#define STATUS_FUNC_GET FUNC_GET_ONLY
#define STATUS_FUNC_GET_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "() -> bool\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
int _i = 0; \
CHECK_NOARGS(_args); \
ACQUIRE_MEMORY_ERROR(); \
_i = _api(); \
RELEASE_MEMORY_ERROR(); \
return Py_BuildValue("i", _i ? 1 : 0); \
BEGIN_FAIL \
END_FAIL \
}
#define STATUS_FUNC_SET_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "(bool)"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
PyObject *_o = NULL; \
if(!PyArg_ParseTuple(_args, "O", &_o)) \
FAIL(); \
ACQUIRE_MEMORY_ERROR(); \
_api(PyObject_IsTrue(_o)); \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
#define FUNC_VOID_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
CHECK_NOARGS(_args); \
ACQUIRE_MEMORY_ERROR(); \
if(!_api()) { \
RELEASE_MEMORY_ERROR(); \
ERROR_CLIPS(_error_clips_impossible); \
FAIL(); \
} \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
#define FUNC_VOID_ONLY(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
CHECK_NOARGS(_args); \
ACQUIRE_MEMORY_ERROR(); \
_api(); \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
/* environment-version macros */
/* status function builder */
#define E_FUNC_GET_ONLY(_py, _sn, _api, _type) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
clips_EnvObject *_env = NULL; \
int _i = 0; \
if(!PyArg_ParseTuple(_args, "O!", &clips_EnvType, &_env)) \
FAIL(); \
ACQUIRE_MEMORY_ERROR(); \
_i = _api(clips_environment_value(_env)); \
RELEASE_MEMORY_ERROR(); \
return Py_BuildValue(_type, _i); \
BEGIN_FAIL \
END_FAIL \
}
#define E_STATUS_FUNC_GET E_FUNC_GET_ONLY
#define E_STATUS_FUNC_GET_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "() -> bool\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
clips_EnvObject *_env = NULL; \
int _i = 0; \
if(!PyArg_ParseTuple(_args, "O!", &clips_EnvType, &_env)) \
FAIL(); \
ACQUIRE_MEMORY_ERROR(); \
_i = _api(clips_environment_value(_env)); \
RELEASE_MEMORY_ERROR(); \
return Py_BuildValue("i", _i ? 1 : 0); \
BEGIN_FAIL \
END_FAIL \
}
#define E_STATUS_FUNC_SET_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "(bool)"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
PyObject *_o = NULL; \
clips_EnvObject *_env = NULL; \
if(!PyArg_ParseTuple(_args, "O!O", &clips_EnvType, &_env, &_o)) \
FAIL(); \
CHECK_NOCURENV(_env); \
ACQUIRE_MEMORY_ERROR(); \
_api(clips_environment_value(_env), PyObject_IsTrue(_o)); \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
#define E_FUNC_VOID_BOOL(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
clips_EnvObject *_env = NULL; \
if(!PyArg_ParseTuple(_args, "O!", &clips_EnvType, &_env)) \
FAIL(); \
CHECK_NOCURENV(_env); \
ACQUIRE_MEMORY_ERROR(); \
if(!_api(clips_environment_value(_env))) { \
ERROR_CLIPS(_error_clips_impossible); \
RELEASE_MEMORY_ERROR(); \
FAIL(); \
} \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
#define E_FUNC_VOID_ONLY(_py, _sn, _api) \
static char _sn##__doc__[] = \
"" #_py "()\nequivalent of C API " #_api "()"; \
static PyObject *_sn(PyObject *_self, PyObject *_args) { \
clips_EnvObject *_env = NULL; \
if(!PyArg_ParseTuple(_args, "O!", &clips_EnvType, &_env)) \
FAIL(); \
CHECK_NOCURENV(_env); \
ACQUIRE_MEMORY_ERROR(); \
_api(clips_environment_value(_env)); \
RELEASE_MEMORY_ERROR(); \
RETURN_NONE(); \
BEGIN_FAIL \
END_FAIL \
}
/* macros used to verify if objects are being garbaged */
#define CHECK_VALID_FACT(_o) do { \
if(!FactExistp(clips_fact_value(_o))) { \
ERROR_CLIPSSYS_GARBFACT(); \
FAIL(); \
} \
} while(0)
#define ENV_CHECK_VALID_FACT(_e, _o) do { \
if(!EnvFactExistp(_e, clips_fact_value(_o))) { \
ERROR_CLIPSSYS_GARBFACT(); \
FAIL(); \
} \
} while(0)
#define CHECK_VALID_INSTANCE(_o) do { \
if(!ValidInstanceAddress(clips_instance_value(_o))) { \
ERROR_CLIPSSYS_GARBINSTANCE(); \
FAIL(); \
} \
} while(0)
#define ENV_CHECK_VALID_INSTANCE(_e, _o) do { \
if(!EnvValidInstanceAddress(_e, clips_instance_value(_o))) { \
ERROR_CLIPSSYS_GARBINSTANCE(); \
FAIL(); \
} \
} while(0)
/* the following can be helpful when allocating objects */
#ifdef USE_PYTHON_MEMMGR
#ifdef NEW
#undef NEW
#endif /* NEW */
#define NEW(x) PyMem_New(x, 1)
#ifdef NEW_ARRAY
#undef NEW_ARRAY
#endif /* NEW_ARRAY */
#define NEW_ARRAY(x, n) PyMem_New(x, (n))
#ifdef DELETE
#undef DELETE
#endif /* DELETE */
#define DELETE(x) PyMem_Del(x)
#ifdef REALLOC
#undef REALLOC
#endif /* REALLOC */
#define REALLOC(p, n) PyMem_Realloc((p), (n))
#ifdef MALLOC
#undef MALLOC
#endif /* MALLOC */
#define MALLOC(s) PyMem_Malloc(s)
#ifdef FREE
#undef FREE
#endif /* FREE */
#define FREE(p) PyMem_Free(p)
#else
#ifdef NEW
#undef NEW
#endif /* NEW */
#define NEW(x) (((x) *)malloc(sizeof(x)))
#ifdef NEW_ARRAY
#undef NEW_ARRAY
#endif /* NEW_ARRAY */
#define NEW_ARRAY(x, n) ((x *)malloc((n) * sizeof(x)))
#ifdef DELETE
#undef DELETE
#endif /* DELETE */
#define DELETE(x) free(x)
#ifdef REALLOC
#undef REALLOC
#endif /* REALLOC */
#define REALLOC(p, n) realloc((p), (n))
#ifdef MALLOC
#undef MALLOC
#endif /* MALLOC */
#define MALLOC(s) malloc(s)
#ifdef FREE
#undef FREE
#endif /* FREE */
#define FREE(p) free(p)
#endif
#ifdef BYTE
#undef BYTE
#define BYTE unsigned char
#endif
/* the boolean values */
#ifndef BOOL
#define BOOL int
#define TRUE 1
#define FALSE 0
#endif
/* maximum supported references */
#define MAX_REFERENCES (INT_MAX - 1)
/* position of stray fact pointer in CLIPS environment */
#ifdef USE_NONASSERT_CLIPSGCLOCK
#define STRAYFACTS_DATA (USER_ENVIRONMENT_DATA + 0)
#endif /* USE_NONASSERT_CLIPSGCLOCK */
/* length of buffers used for string operations */
static size_t ppbuffer_size = INITIAL_PPBUFFER_SIZE;
/* flag to state whether or not fatal environment errors must be shown */
static BOOL clips_ShowEnvironmentFatalErrors = FALSE;
/* Part One: module internals and helpers */
/* The following jump point is used to ensure memory error handling */
#ifdef USE_MEMORY_ERROR_HANDLER
static jmp_buf env_OutOfMemory;
static BOOL env_OutOfMemory_isSet = FALSE;
#endif /* USE_MEMORY_ERROR_HANDLER */
/* This function should be used instead of the standard memory allocator
* within CLIPS in order to let memory errors to be correctly reported by
* Python instead of exiting abnormally. This function is tightly coupled
* with the "out of memory function" implemented here, that jumps back to
* the above defined jump point.
*/
void *PyCLIPS_Malloc(size_t s) {
#ifdef USE_MEMORY_ERROR_HANDLER
void *p = MALLOC(s);
if(!p && env_OutOfMemory_isSet)
longjmp(env_OutOfMemory, 1);
return p;
#else
return MALLOC(s);
#endif /* USE_MEMORY_ERROR_HANDLER */
}
void PyCLIPS_Free(void *p) {
FREE(p);
}
/* The following function queries the above defined flag to test whether or
* not to show fatal environment errors on stderr (on a patched CLIPS source,
* of course: the unpatched source will have the usual behaviour to write a
* message on stdout) and is called directly by CLIPS before writing anything.
*/
int PyCLIPS_EnableFatal(void) {
#ifdef USE_FATAL_ERROR_INHIBITION
return clips_ShowEnvironmentFatalErrors;
#else
return TRUE;
#endif /* USE_FATAL_ERROR_INHIBITION */
}
/* THE FOLLOWING ARE DEFINED HERE AS IN CLIPS main.c */
/*********************************************************/
/* UserFunctions: Informs the expert system environment */
/* of any user defined functions. In the default case, */
/* there are no user defined functions. To define */
/* functions, either this function must be replaced by */
/* a function with the same name within this file, or */
/* this function can be deleted from this file and */
/* included in another file. */
/*********************************************************/
void UserFunctions(void) { }
/***********************************************************/
/* EnvUserFunctions: Informs the expert system environment */
/* of any user defined functions. In this case, there is */
/* only a function which invokes real Python functions. */
/***********************************************************/
void EnvPythonExternalCall(void *, DATA_OBJECT_PTR);
void EnvUserFunctions(void *env) {
EnvDefineFunction2(env, "python-call", 'u', PTIEF EnvPythonExternalCall,
"EnvPythonExternalCall", "1*uw");
}
/* NOTE:
* The following literally included file contains a rough implementation
* of an hash-table driven method of storing pointers in order to possibly
* apply a function to all contained elements. This is done in order to
* avoid access violations when accessing fact objects after a call to the
* CLIPS Clear() function. The behaviour of CLIPS in this occasion is known
* and not considered a bug; however there is no way to determine whether
* or not a fact has still valid slots or not. Keeping track of which facts
* have still not been asserted seemed the only way to determine when they
* could be corrupted. Of course this is a time consuming operation, but
* handling it via the structure define in "loptr.c" seemed a way to keep
* the time overhead as small as possible. Most of the "time waste" occurs
* when either Assert() or CreateFact() or Clear() are called.
*/
#ifdef USE_NONASSERT_CLIPSGCLOCK
#include "loptr.c"
#endif /* USE_NONASSERT_CLIPSGCLOCK */
/* a Python type representing a standalone CLIPS environment */
staticforward PyTypeObject clips_EnvType;
typedef struct {
PyObject_HEAD
void *value;
BOOL valid;
#ifdef USE_NONASSERT_CLIPSGCLOCK
unsigned long clips_NotAssertedFacts;
BOOL clips_GCLocked;
LOPTR_HASH_TABLE(clips_StrayFacts);
#endif /* USE_NONASSERT_CLIPSGCLOCK */
} clips_EnvObject;
#define clips_environment_value(v) (((clips_EnvObject *)(v))->value)
#define clips_environment_valid(v) (((clips_EnvObject *)(v))->valid)
#define clips_environment_check(v) \
(((v)->ob_type == &clips_EnvType) && clips_environment_valid(v))
#ifdef USE_NONASSERT_CLIPSGCLOCK
#define clips_environment_New(p) \
do { \
p = PyObject_New(clips_EnvObject, &clips_EnvType); \
if(p) { \
clips_environment_valid(p) = TRUE; \
p->clips_NotAssertedFacts = 0;\
p->clips_GCLocked = FALSE; \
INIT_LOPTR_HASH_TABLE(p->clips_StrayFacts); \
} \
} while(0)
#define CLEAR_LOST_FACTS() LOPTR_reset_hash_table(clips_StrayFacts)
#define ENV_CLEAR_LOST_FACTS(_pe) \
LOPTR_reset_hash_table((_pe)->clips_StrayFacts)
#else
#define clips_environment_New(p) \
do { \
p = PyObject_New(clips_EnvObject, &clips_EnvType); \
if(p) \
clips_environment_valid(p) = TRUE; \
} while(0)
#define CLEAR_LOST_FACTS()
#define ENV_CLEAR_LOST_FACTS(_pe)
#endif /* USE_NONASSERT_CLIPSGCLOCK */
static void clips_EnvObject_dealloc(PyObject *self) {
/* only the Python object is destroyed: environments are forever */
ENV_CLEAR_LOST_FACTS((clips_EnvObject *)self);
PyObject_Del(self);
}
static PyTypeObject clips_EnvType = {
PyObject_HEAD_INIT(NULL)
0,
"environment",
sizeof(clips_EnvObject),
0,
clips_EnvObject_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
};
/* a Python Type representing a CLIPS deftemplate object */
staticforward PyTypeObject clips_DeftemplType;
typedef struct {
PyObject_HEAD
void *value;
} clips_DeftemplObject;
#define clips_deftemplate_check(v) ((v)->ob_type == &clips_DeftemplType)
#define clips_deftemplate_value(v) (((clips_DeftemplObject *)(v))->value)
#define clips_deftemplate_New(p) \
p = PyObject_New(clips_DeftemplObject, &clips_DeftemplType)
static void clips_DeftemplObject_dealloc(PyObject *self) {
PyObject_Del(self);
}
static PyTypeObject clips_DeftemplType = {
PyObject_HEAD_INIT(NULL)
0,
"deftemplate",
sizeof(clips_DeftemplObject),
0,
clips_DeftemplObject_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
};
/* a Python Type representing a CLIPS fact object */
staticforward PyTypeObject clips_FactType;
typedef struct {
PyObject_HEAD
BOOL readonly;
BOOL locked;
void *value;
void *creation_env;
#ifdef USE_NONASSERT_CLIPSGCLOCK
BOOL lost;
#endif /* USE_NONASSERT_CLIPSGCLOCK */
} clips_FactObject;
#define clips_fact_check(v) ((v)->ob_type == &clips_FactType)
#define clips_fact_value(v) (((clips_FactObject *)(v))->value)
#define clips_fact_env(v) (((clips_FactObject *)(v))->creation_env)
#define clips_fact_readonly(v) (((clips_FactObject *)(v))->readonly)
#define clips_fact_verify(v) (!((struct fact *) \
(((clips_FactObject *)(v))->value))->garbage)
/* assign a pointer to a CLIPS fact to this object */
#define clips_fact_assign(e, p) do { \
EnvIncrementFactCount(clips_fact_env(e), p); \
clips_fact_value(e) = p; \
} while(0)
/* Move a pointer to a CLIPS fact without incrementing the reference count.
Same as clips_fact_assign(), except ownership is being transfered. */
#define clips_fact_move(e, p) do { \
clips_fact_value(e) = p; \
} while(0)
/* lock/unlock a fact object */
#define clips_fact_locked(v) (((clips_FactObject *)(v))->locked)
#define clips_fact_lock(v) do { \
((clips_FactObject *)(v))->locked = TRUE; \
} while(0)
#define clips_fact_unlock(v) do { \
((clips_FactObject *)(v))->locked = FALSE; \
} while(0)
/* facts behave differently than instances upon call to Clear */
#ifdef USE_NONASSERT_CLIPSGCLOCK
#define clips_fact_lost(v) (((clips_FactObject *)(v))->lost)
#define clips_fact_New(e, p) do { \
p = PyObject_New(clips_FactObject, &clips_FactType); \
clips_fact_readonly(p) = FALSE; \
clips_fact_lost(p) = FALSE; \
clips_fact_env(p) = e; \
clips_fact_value(p) = NULL; \
clips_fact_locked(p) = FALSE; \
} while(0)
/* This function will be called for every not asserted fact upon clear:
* it has to be a function (and not an inlineable one) because its address
* will be passed to a function that calls it for each fact that is
* supposedly lost. Moreover, although we actually don't need it, the
* function has to be a BOOL()(void *), since this is the accepted type
* for the final calling function.
*/
static BOOL lose_fact(void *p) {
clips_fact_lost(p) = TRUE; /* explicitly casts to clips_FactObject */
return TRUE;
}
#else
#define clips_fact_New(e, p) do { \
p = PyObject_New(clips_FactObject, &clips_FactType); \
clips_fact_readonly(p) = FALSE; \
clips_fact_env(p) = e; \
clips_fact_value(p) = NULL; \
clips_fact_locked(p) = FALSE; \
} while(0)
#endif /* USE_NONASSERT_CLIPSGCLOCK */
#ifdef USE_NONASSERT_CLIPSGCLOCK
/* allow to assert facts without losing defined but non asserted ones */
static unsigned long clips_NotAssertedFacts = 0;
static BOOL clips_GCLocked = FALSE;
LOPTR_HASH_TABLE(clips_StrayFacts) = { 0 };
F_INLINE void clips_lock_gc(clips_EnvObject *pyenv) {
if(pyenv) {
if(!pyenv->clips_GCLocked && pyenv->clips_NotAssertedFacts > 0) {
EnvIncrementGCLocks(clips_environment_value(pyenv));
pyenv->clips_GCLocked = TRUE;
}
} else {
if(!clips_GCLocked && clips_NotAssertedFacts > 0) {
IncrementGCLocks();
clips_GCLocked = TRUE;
}
}
}
F_INLINE void clips_unlock_gc(clips_EnvObject *pyenv) {
if(pyenv) {
if(pyenv->clips_GCLocked && pyenv->clips_NotAssertedFacts == 0) {
pyenv->clips_GCLocked = FALSE;
EnvDecrementGCLocks(clips_environment_value(pyenv));
}
} else {
if(clips_GCLocked && clips_NotAssertedFacts == 0) {
clips_GCLocked = FALSE;
DecrementGCLocks();
}
}
}
F_INLINE BOOL add_FactObject_lock(clips_EnvObject *pyenv) {
if(pyenv)
pyenv->clips_NotAssertedFacts++;
else
clips_NotAssertedFacts++;
return TRUE;
}
F_INLINE BOOL remove_FactObject_lock(clips_EnvObject *pyenv) {
if(pyenv) {
if(pyenv->clips_NotAssertedFacts > 0) {
pyenv->clips_NotAssertedFacts--;
return TRUE;
}
} else {
if(clips_NotAssertedFacts > 0) {
clips_NotAssertedFacts--;
return TRUE;
}
}
return FALSE;
}
F_INLINE BOOL reset_FactObject_lock(clips_EnvObject *pyenv) {
if(pyenv) {
if(pyenv->clips_NotAssertedFacts > 0) {
pyenv->clips_NotAssertedFacts = 0;
if(pyenv->clips_GCLocked) {
pyenv->clips_GCLocked = FALSE;
EnvDecrementGCLocks(clips_environment_value(pyenv));
}
return TRUE;
}
} else {
if(clips_NotAssertedFacts > 0) {
clips_NotAssertedFacts = 0;
if(clips_GCLocked) {
clips_GCLocked = FALSE;
DecrementGCLocks();
}
return TRUE;
}
}
return FALSE;
}
/* through the loptr.c utility we can check whether or not a fact is lost */
#define APPEND_HASH_FACT(_p) LOPTR_append(clips_StrayFacts, (void *)(_p))
#define REMOVE_HASH_FACT(_p) LOPTR_remove(clips_StrayFacts, (void *)(_p))
#define LOSE_HASH_FACTS() LOPTR_apply(clips_StrayFacts, lose_fact)
#define ENV_APPEND_HASH_FACT(_pe, _p) \
LOPTR_append((_pe)->clips_StrayFacts, (void *)(_p))
#define ENV_REMOVE_HASH_FACT(_pe, _p) \
LOPTR_remove((_pe)->clips_StrayFacts, (void *)(_p))
#define ENV_LOSE_HASH_FACTS(_pe) \
LOPTR_apply((_pe)->clips_StrayFacts, lose_fact)
/* the following is needed for facts to auto-deregister */
#define SPEC_REMOVE_HASH_FACT(_sfl, _p) LOPTR_remove((_sfl), (void *)(_p))
/* check if a fact is lost: the ENV version is for completeness only */
#define CHECK_LOST_FACT(_o) do { \
if(clips_fact_lost(_o)) { \
ERROR_CLIPSSYS_GARBFACT(); \
FAIL(); \
} \
} while(0)
#define ENV_CHECK_LOST_FACT(_e, _o) do { \
if(clips_fact_lost(_o)) { \
ERROR_CLIPSSYS_GARBFACT(); \
FAIL(); \
} \
} while(0)
/* and these are needed to inform the system about creation or assertion */
#define ADD_NONASSERTED_FACT() add_FactObject_lock(NULL)
#define REMOVE_JUSTASSERTED_FACT() remove_FactObject_lock(NULL)
#define ENV_ADD_NONASSERTED_FACT(_pe) add_FactObject_lock(_pe)
#define ENV_REMOVE_JUSTASSERTED_FACT(_pe) remove_FactObject_lock(_pe)
#define RESET_ASSERTED_FACTS() reset_FactObject_lock(NULL)
#define ENV_RESET_ASSERTED_FACTS(_pe) reset_FactObject_lock(_pe)
#define CLIPS_LOCK_GC() clips_lock_gc(NULL)
#define CLIPS_UNLOCK_GC() clips_unlock_gc(NULL)
#define ENV_CLIPS_LOCK_GC(_pe) clips_lock_gc(_pe)
#define ENV_CLIPS_UNLOCK_GC(_pe) clips_unlock_gc(_pe)
#define COPY_ADDITIONAL_ENVIRONMENT_DATA(_pe) do \
{ \
clips_NotAssertedFacts = (_pe)->clips_NotAssertedFacts; \
clips_GCLocked = (_pe)->clips_GCLocked; \
COPY_LOPTR_HASH_TABLE(clips_StrayFacts, (_pe)->clips_StrayFacts); \
} while(0)
#define INJECT_ADDITIONAL_ENVIRONMENT_DATA(_pe) do \
{ \
(_pe)->clips_NotAssertedFacts = clips_NotAssertedFacts; \
(_pe)->clips_GCLocked = clips_GCLocked; \
COPY_LOPTR_HASH_TABLE((_pe)->clips_StrayFacts, clips_StrayFacts); \
} while(0)
#else
/* symbols to always force that garbage collector in CLIPS to be locked */
#ifdef USE_CLIPSGCLOCK
#define CLIPS_LOCK_GC() IncrementGCLocks()
#define CLIPS_UNLOCK_GC() DecrementGCLocks()
#define ENV_CLIPS_LOCK_GC(_pe) EnvIncrementGCLocks(clips_environment_value(_pe))
#define ENV_CLIPS_UNLOCK_GC(_pe) EnvDecrementGCLocks(clips_environment_value(_pe))
#else
#define CLIPS_LOCK_GC()
#define CLIPS_UNLOCK_GC()
#define ENV_CLIPS_LOCK_GC(_pe)
#define ENV_CLIPS_UNLOCK_GC(_pe)
#endif /* USE_CLIPSGCLOCK */
#define ADD_NONASSERTED_FACT()
#define REMOVE_JUSTASSERTED_FACT()
#define RESET_ASSERTED_FACTS()
#define ENV_ADD_NONASSERTED_FACT(_pe)
#define ENV_REMOVE_JUSTASSERTED_FACT(_pe)
#define ENV_RESET_ASSERTED_FACTS(_pe)
#define COPY_ADDITIONAL_ENVIRONMENT_DATA(_pe)
#define INJECT_ADDITIONAL_ENVIRONMENT_DATA(_pe)
#define APPEND_HASH_FACT(_p)
#define REMOVE_HASH_FACT(_p)
#define LOSE_HASH_FACTS()
#define ENV_APPEND_HASH_FACT(_pe, _p)
#define ENV_REMOVE_HASH_FACT(_pe, _p)
#define SPEC_REMOVE_HASH_FACT(_sfl, _p)
#define ENV_LOSE_HASH_FACTS(_pe)
#define CHECK_LOST_FACT(_o)
#define ENV_CHECK_LOST_FACT(_e, _o)
#endif /* USE_NONASSERT_CLIPSGCLOCK */
/* The fact removal process might seem tricky. However there is a reason
* for this complicated routine: when a fact is created, and before its
* assertion, it is put in the fact hash map in order to be invalidated
* during actions that would cause a CLIPS garbage collection (see comments
* above). Whenever a Python Fact object is destroyed, it has to deregister
* itself from the corresponding hash map. Information about the said hash
* map is carried along with the CLIPS managed environment, via specifically
* allocated data - which just contains a pointer to the corresponding map.
* That a fact at the end contains information about its hash map is not a
* problem when environments are made current: all data in the Environment
* object (note the capital E, for Python corresponding objects) is copied
* to the current Environment, including the hash map (clips_StrayFacts),
* and everything remains consistent.
*/
static void clips_FactObject_dealloc(PyObject *self) {
void *p = clips_fact_value(self);
#ifdef USE_NONASSERT_CLIPSGCLOCK
LOPTR_ITEM ***hm =
(LOPTR_ITEM ***)GetEnvironmentData(
clips_fact_env(self), STRAYFACTS_DATA);
SPEC_REMOVE_HASH_FACT(*hm, self);
#endif /* USE_NONASSERT_CLIPSGCLOCK */
if(p)
EnvDecrementFactCount(clips_fact_env(self), p);
clips_fact_unlock(self);
PyObject_Del(self);
}
static PyTypeObject clips_FactType = {
PyObject_HEAD_INIT(NULL)
0,
"fact",
sizeof(clips_FactObject),
0,
clips_FactObject_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/