clips-sys 0.4.0

Bindgen generated wrapper for CLIPS (clipsrules.net)
Documentation
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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*            CLIPS Version 6.40  11/07/17             */
   /*                                                     */
   /*               INSTANCE FUNCTIONS MODULE             */
   /*******************************************************/

/*************************************************************/
/* Purpose:  Internal instance manipulation routines         */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Contributing Programmer(s):                               */
/*                                                           */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*      6.23: Correction for FalseSymbol/TrueSymbol. DR0859  */
/*                                                           */
/*            Changed name of variable log to logName        */
/*            because of Unix compiler warnings of shadowed  */
/*            definitions.                                   */
/*                                                           */
/*            Changed name of variable exp to theExp         */
/*            because of Unix compiler warnings of shadowed  */
/*            definitions.                                   */
/*                                                           */
/*      6.24: Link error occurs for the SlotExistError       */
/*            function when OBJECT_SYSTEM is set to 0 in     */
/*            setup.h. DR0865                                */
/*                                                           */
/*            Converted INSTANCE_PATTERN_MATCHING to         */
/*            DEFRULE_CONSTRUCT.                             */
/*                                                           */
/*            Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*            Moved EvaluateAndStoreInDataObject to          */
/*            evaluatn.c                                     */
/*                                                           */
/*      6.30: Removed conditional code for unsupported       */
/*            compilers/operating systems (IBM_MCW,          */
/*            MAC_MCW, and IBM_TBC).                         */
/*                                                           */
/*            Changed integer type/precision.                */
/*                                                           */
/*            Changed garbage collection algorithm.          */
/*                                                           */
/*            Support for long long integers.                */
/*                                                           */
/*            Added const qualifiers to remove C++           */
/*            deprecation warnings.                          */
/*                                                           */
/*            Converted API macros to function calls.        */
/*                                                           */
/*            Fixed slot override default ?NONE bug.         */
/*                                                           */
/*            Instances of the form [<name>] are now         */
/*            searched for in all modules.                   */
/*                                                           */
/*      6.40: Added Env prefix to GetEvaluationError and     */
/*            SetEvaluationError functions.                  */
/*                                                           */
/*            Pragma once and other inclusion changes.       */
/*                                                           */
/*            Added support for booleans with <stdbool.h>.   */
/*                                                           */
/*            Removed use of void pointers for specific      */
/*            data structures.                               */
/*                                                           */
/*            ALLOW_ENVIRONMENT_GLOBALS no longer supported. */
/*                                                           */
/*            UDF redesign.                                  */
/*                                                           */
/*************************************************************/

/* =========================================
   *****************************************
               EXTERNAL DEFINITIONS
   =========================================
   ***************************************** */

#include <stdlib.h>

#include "setup.h"

#if OBJECT_SYSTEM

#include "argacces.h"
#include "classcom.h"
#include "classfun.h"
#include "cstrnchk.h"
#if DEFRULE_CONSTRUCT
#include "drive.h"
#include "objrtmch.h"
#endif
#include "engine.h"
#include "envrnmnt.h"
#include "inscom.h"
#include "insmngr.h"
#include "memalloc.h"
#include "modulutl.h"
#include "msgcom.h"
#include "msgfun.h"
#include "prccode.h"
#include "prntutil.h"
#include "router.h"
#include "utility.h"

#include "insfun.h"

/* =========================================
   *****************************************
                   CONSTANTS
   =========================================
   ***************************************** */
#define BIG_PRIME    11329

/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/

   static Instance               *FindImportedInstance(Environment *,Defmodule *,Defmodule *,Instance *);

#if DEFRULE_CONSTRUCT
   static void                    NetworkModifyForSharedSlot(Environment *,int,Defclass *,SlotDescriptor *);
#endif

/* =========================================
   *****************************************
          EXTERNALLY VISIBLE FUNCTIONS
   =========================================
   ***************************************** */

/***************************************************/
/* IncrementInstanceCallback: Increments the       */
/*   number of references to a specified instance. */
/***************************************************/
void IncrementInstanceCallback(
  Environment *theEnv,
  Instance *theInstance)
  {
#if MAC_XCD
#pragma unused(theEnv)
#endif
   if (theInstance == NULL) return;

   theInstance->busy++;
  }

/***************************************************/
/* DecrementInstanceCallback: Decrements the       */
/*   number of references to a specified instance. */
/***************************************************/
void DecrementInstanceCallback(
  Environment *theEnv,
  Instance *theInstance)
  {
#if MAC_XCD
#pragma unused(theEnv)
#endif
   if (theInstance == NULL) return;

   theInstance->busy--;
  }

/***************************************************
  NAME         : RetainInstance
  DESCRIPTION  : Increments instance busy count -
                   prevents it from being deleted
  INPUTS       : The address of the instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Count set
  NOTES        : None
 ***************************************************/
void RetainInstance(
  Instance *theInstance)
  {
   if (theInstance == NULL) return;
   
   theInstance->busy++;
  }

/***************************************************
  NAME         : ReleaseInstance
  DESCRIPTION  : Decrements instance busy count -
                   might allow it to be deleted
  INPUTS       : The address of the instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Count set
  NOTES        : None
 ***************************************************/
void ReleaseInstance(
  Instance *theInstance)
  {
   if (theInstance == NULL) return;

   theInstance->busy--;
  }

/***************************************************
  NAME         : InitializeInstanceTable
  DESCRIPTION  : Initializes instance hash table
                  to all NULL addresses
  INPUTS       : None
  RETURNS      : Nothing useful
  SIDE EFFECTS : Hash table initialized
  NOTES        : None
 ***************************************************/
void InitializeInstanceTable(
  Environment *theEnv)
  {
   int i;

   InstanceData(theEnv)->InstanceTable = (Instance **)
                    gm2(theEnv,sizeof(Instance *) * INSTANCE_TABLE_HASH_SIZE);
   for (i = 0 ; i < INSTANCE_TABLE_HASH_SIZE ; i++)
     InstanceData(theEnv)->InstanceTable[i] = NULL;
  }

/*******************************************************
  NAME         : CleanupInstances
  DESCRIPTION  : Iterates through instance garbage
                   list looking for nodes that
                   have become unused - and purges
                   them
  INPUTS       : None
  RETURNS      : Nothing useful
  SIDE EFFECTS : Non-busy instance garbage nodes deleted
  NOTES        : None
 *******************************************************/
void CleanupInstances(
  Environment *theEnv,
  void *context)
  {
   IGARBAGE *gprv,*gtmp,*dump;

   if (InstanceData(theEnv)->MaintainGarbageInstances)
     return;
   gprv = NULL;
   gtmp = InstanceData(theEnv)->InstanceGarbageList;
   while (gtmp != NULL)
     {
#if DEFRULE_CONSTRUCT
      if ((gtmp->ins->busy == 0)
          && (gtmp->ins->patternHeader.busyCount == 0))
#else
      if (gtmp->ins->busy == 0)
#endif
        {
         ReleaseLexeme(theEnv,gtmp->ins->name);
         rtn_struct(theEnv,instance,gtmp->ins);
         if (gprv == NULL)
           InstanceData(theEnv)->InstanceGarbageList = gtmp->nxt;
         else
           gprv->nxt = gtmp->nxt;
         dump = gtmp;
         gtmp = gtmp->nxt;
         rtn_struct(theEnv,igarbage,dump);
        }
      else
        {
         gprv = gtmp;
         gtmp = gtmp->nxt;
        }
     }
  }

/*******************************************************
  NAME         : HashInstance
  DESCRIPTION  : Generates a hash index for a given
                 instance name
  INPUTS       : The address of the instance name SYMBOL_HN
  RETURNS      : The hash index value
  SIDE EFFECTS : None
  NOTES        : Counts on the fact that the symbol
                 has already been hashed into the
                 symbol table - uses that hash value
                 multiplied by a prime for a new hash
 *******************************************************/
unsigned HashInstance(
  CLIPSLexeme *cname)
  {
   unsigned long tally;

   tally = ((unsigned long) cname->bucket) * BIG_PRIME;
   return (unsigned) (tally % INSTANCE_TABLE_HASH_SIZE);
  }

/***************************************************
  NAME         : DestroyAllInstances
  DESCRIPTION  : Deallocates all instances,
                  reinitializes hash table and
                  resets class instance pointers
  INPUTS       : None
  RETURNS      : Nothing useful
  SIDE EFFECTS : All instances deallocated
  NOTES        : None
 ***************************************************/
void DestroyAllInstances(
  Environment *theEnv,
  void *context)
  {
   Instance *iptr;
   bool svmaintain;

   SaveCurrentModule(theEnv);
   svmaintain = InstanceData(theEnv)->MaintainGarbageInstances;
   InstanceData(theEnv)->MaintainGarbageInstances = true;
   iptr = InstanceData(theEnv)->InstanceList;
   while (iptr != NULL)
     {
      SetCurrentModule(theEnv,iptr->cls->header.whichModule->theModule);
      DirectMessage(theEnv,MessageHandlerData(theEnv)->DELETE_SYMBOL,iptr,NULL,NULL);
      iptr = iptr->nxtList;
      while ((iptr != NULL) ? iptr->garbage : false)
        iptr = iptr->nxtList;
     }
   InstanceData(theEnv)->MaintainGarbageInstances = svmaintain;
   RestoreCurrentModule(theEnv);
  }

/******************************************************
  NAME         : RemoveInstanceData
  DESCRIPTION  : Deallocates all the data objects
                 in instance slots and then dealloactes
                 the slots themeselves
  INPUTS       : The instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Instance slots removed
  NOTES        : An instance made with CopyInstanceData
                 will have shared values removed
                 in all cases because they are not
                 "real" instances.
                 Instance class busy count decremented
 ******************************************************/
void RemoveInstanceData(
  Environment *theEnv,
  Instance *ins)
  {
   long i;
   InstanceSlot *sp;

   DecrementDefclassBusyCount(theEnv,ins->cls);
   for (i = 0 ; i < ins->cls->instanceSlotCount ; i++)
     {
      sp = ins->slotAddresses[i];
      if ((sp == &sp->desc->sharedValue) ?
          (--sp->desc->sharedCount == 0) : true)
        {
         if (sp->desc->multiple)
           {
            ReleaseMultifield(theEnv,sp->multifieldValue);
            AddToMultifieldList(theEnv,sp->multifieldValue);
           }
         else
           AtomDeinstall(theEnv,sp->type,sp->value);
         sp->value = NULL;
        }
     }
   if (ins->cls->instanceSlotCount != 0)
     {
      rm(theEnv,ins->slotAddresses,
         (ins->cls->instanceSlotCount * sizeof(InstanceSlot *)));
      if (ins->cls->localInstanceSlotCount != 0)
        rm(theEnv,ins->slots,
           (ins->cls->localInstanceSlotCount * sizeof(InstanceSlot)));
     }
   ins->slots = NULL;
   ins->slotAddresses = NULL;
  }

/***************************************************************************
  NAME         : FindInstanceBySymbol
  DESCRIPTION  : Looks up a specified instance in the instance hash table
  INPUTS       : The symbol for the name of the instance
  RETURNS      : The address of the found instance, NULL otherwise
  SIDE EFFECTS : None
  NOTES        : An instance is searched for by name first in the
                 current module - then in imported modules according
                 to the order given in the current module's definition.
                 Instances of the form [<name>] are now searched for in
                 all modules.
 ***************************************************************************/
Instance *FindInstanceBySymbol(
  Environment *theEnv,
  CLIPSLexeme *moduleAndInstanceName)
  {
   unsigned modulePosition;
   bool searchImports;
   CLIPSLexeme *moduleName, *instanceName;
   Defmodule *currentModule,*theModule;

   currentModule = GetCurrentModule(theEnv);

   /* =======================================
      Instance names of the form [<name>] are
      searched for only in the current module
      ======================================= */
   modulePosition = FindModuleSeparator(moduleAndInstanceName->contents);
   if (modulePosition == 0)
     {
      Instance *ins;
      if (moduleAndInstanceName->header.type == SYMBOL_TYPE)
        { moduleAndInstanceName = CreateInstanceName(theEnv,moduleAndInstanceName->contents); }

      ins = InstanceData(theEnv)->InstanceTable[HashInstance(moduleAndInstanceName)];
      while (ins != NULL)
        {
         if (ins->name == moduleAndInstanceName)
           { return ins; }
         ins = ins->nxtHash;
        }
      return NULL;
     }

   /* =========================================
      Instance names of the form [::<name>] are
      searched for in the current module and
      imported modules in the definition order
      ========================================= */
   else if (modulePosition == 1)
     {
      theModule = currentModule;
      instanceName = ExtractConstructName(theEnv,modulePosition,moduleAndInstanceName->contents,INSTANCE_NAME_TYPE);
      searchImports = true;
     }

   /* =============================================
      Instance names of the form [<module>::<name>]
      are searched for in the specified module
      ============================================= */
   else
     {
      moduleName = ExtractModuleName(theEnv,modulePosition,moduleAndInstanceName->contents);
      theModule = FindDefmodule(theEnv,moduleName->contents);
      instanceName = ExtractConstructName(theEnv,modulePosition,moduleAndInstanceName->contents,INSTANCE_NAME_TYPE);
      if (theModule == NULL)
        return NULL;
      searchImports = false;
     }
   return(FindInstanceInModule(theEnv,instanceName,theModule,currentModule,searchImports));
  }

/***************************************************
  NAME         : FindInstanceInModule
  DESCRIPTION  : Finds an instance of the given name
                 in the given module in scope of
                 the given current module
                 (will also search imported modules
                  if specified)
  INPUTS       : 1) The instance name (no module)
                 2) The module to search
                 3) The currently active module
                 4) A flag indicating whether
                    to search imported modules of
                    given module as well
  RETURNS      : The instance (NULL if none found)
  SIDE EFFECTS : None
  NOTES        : The class no longer needs to be in
                 scope of the current module if the
                 instance's module name has been specified.
 ***************************************************/
Instance *FindInstanceInModule(
  Environment *theEnv,
  CLIPSLexeme *instanceName,
  Defmodule *theModule,
  Defmodule *currentModule,
  bool searchImports)
  {
   Instance *startInstance,*ins;

   /* ===============================
      Find the first instance of the
      correct name in the hash chain
      =============================== */
   startInstance = InstanceData(theEnv)->InstanceTable[HashInstance(instanceName)];
   while (startInstance != NULL)
     {
      if (startInstance->name == instanceName)
        break;
      startInstance = startInstance->nxtHash;
     }

   if (startInstance == NULL)
     return NULL;

   /* ===========================================
      Look for the instance in the specified
      module - if the class of the found instance
      is in scope of the current module, we have
      found the instance
      =========================================== */
   for (ins = startInstance ;
        (ins != NULL) ? (ins->name == startInstance->name) : false ;
        ins = ins->nxtHash)
     //if ((ins->cls->header.whichModule->theModule == theModule) &&
     //     DefclassInScope(theEnv,ins->cls,currentModule))
     if (ins->cls->header.whichModule->theModule == theModule)
       return(ins);

   /* ================================
      For ::<name> formats, we need to
      search imported modules too
      ================================ */
   if (searchImports == false)
     return NULL;
   MarkModulesAsUnvisited(theEnv);
   return(FindImportedInstance(theEnv,theModule,currentModule,startInstance));
  }

/********************************************************************
  NAME         : FindInstanceSlot
  DESCRIPTION  : Finds an instance slot by name
  INPUTS       : 1) The address of the instance
                 2) The symbolic name of the slot
  RETURNS      : The address of the slot, NULL if not found
  SIDE EFFECTS : None
  NOTES        : None
 ********************************************************************/
InstanceSlot *FindInstanceSlot(
  Environment *theEnv,
  Instance *ins,
  CLIPSLexeme *sname)
  {
   int i;

   i = FindInstanceTemplateSlot(theEnv,ins->cls,sname);
   return (i != -1) ? ins->slotAddresses[i] : NULL;
  }

/********************************************************************
  NAME         : FindInstanceTemplateSlot
  DESCRIPTION  : Performs a search on an class's instance
                   template slot array to find a slot by name
  INPUTS       : 1) The address of the class
                 2) The symbolic name of the slot
  RETURNS      : The index of the slot, -1 if not found
  SIDE EFFECTS : None
  NOTES        : The slot's unique id is used as index into
                 the slot map array.
 ********************************************************************/
int FindInstanceTemplateSlot(
  Environment *theEnv,
  Defclass *cls,
  CLIPSLexeme *sname)
  {
   unsigned short sid;

   sid = FindSlotNameID(theEnv,sname);
   if (sid == SLOT_NAME_NOT_FOUND)
     return -1;
     
   if (sid > cls->maxSlotNameID)
     return -1;
     
   return((int) cls->slotNameMap[sid] - 1);
  }

/*******************************************************
  NAME         : PutSlotValue
  DESCRIPTION  : Evaluates new slot-expression and
                   stores it as a multifield
                   variable for the slot.
  INPUTS       : 1) The address of the instance
                    (NULL if no trace-messages desired)
                 2) The address of the slot
                 3) The address of the value
                 4) UDFValue pointer to store the
                    set value
                 5) The command doing the put-
  RETURNS      : False on errors, or true
  SIDE EFFECTS : Old value deleted and new one allocated
                 Old value symbols deinstalled
                 New value symbols installed
  NOTES        : None
 *******************************************************/
PutSlotError PutSlotValue(
  Environment *theEnv,
  Instance *ins,
  InstanceSlot *sp,
  UDFValue *val,
  UDFValue *setVal,
  const char *theCommand)
  {
   PutSlotError rv;
   if ((rv = ValidSlotValue(theEnv,val,sp->desc,ins,theCommand)) != PSE_NO_ERROR)
     {
      setVal->value = FalseSymbol(theEnv);
      return rv;
     }
   return DirectPutSlotValue(theEnv,ins,sp,val,setVal);
  }

/*******************************************************
  NAME         : DirectPutSlotValue
  DESCRIPTION  : Evaluates new slot-expression and
                   stores it as a multifield
                   variable for the slot.
  INPUTS       : 1) The address of the instance
                    (NULL if no trace-messages desired)
                 2) The address of the slot
                 3) The address of the value
                 4) UDFValue pointer to store the
                    set value
  RETURNS      : False on errors, or true
  SIDE EFFECTS : Old value deleted and new one allocated
                 Old value symbols deinstalled
                 New value symbols installed
  NOTES        : None
 *******************************************************/
PutSlotError DirectPutSlotValue(
  Environment *theEnv,
  Instance *ins,
  InstanceSlot *sp,
  UDFValue *val,
  UDFValue *setVal)
  {
   size_t i,j; /* 6.04 Bug Fix */
#if DEFRULE_CONSTRUCT
   int sharedTraversalID;
   InstanceSlot *bsp,**spaddr;
#endif
   UDFValue tmpVal;

   setVal->value = FalseSymbol(theEnv);
   if (val == NULL)
     {
      SystemError(theEnv,"INSFUN",1);
      ExitRouter(theEnv,EXIT_FAILURE);
     }
   else if (val->value == ProceduralPrimitiveData(theEnv)->NoParamValue)
     {
      if (sp->desc->dynamicDefault)
        {
         val = &tmpVal;
         if (!EvaluateAndStoreInDataObject(theEnv,sp->desc->multiple,
                                           (Expression *) sp->desc->defaultValue,val,true))
           return PSE_EVALUATION_ERROR;
        }
      else if (sp->desc->defaultValue != NULL)
        { val = (UDFValue *) sp->desc->defaultValue; }
      else
        {
         PrintErrorID(theEnv,"INSMNGR",14,false);
         WriteString(theEnv,STDERR,"Override required for slot '");
         WriteString(theEnv,STDERR,sp->desc->slotName->name->contents);
         WriteString(theEnv,STDERR,"' in instance [");
         WriteString(theEnv,STDERR,ins->name->contents);
         WriteString(theEnv,STDERR,"].\n");
         SetEvaluationError(theEnv,true);
         return PSE_EVALUATION_ERROR;
        }
     }
#if DEFRULE_CONSTRUCT
   if (EngineData(theEnv)->JoinOperationInProgress && sp->desc->reactive &&
       (ins->cls->reactive || sp->desc->shared))
     {
      PrintErrorID(theEnv,"INSFUN",5,false);
      WriteString(theEnv,STDERR,"Cannot modify reactive instance slots while ");
      WriteString(theEnv,STDERR,"pattern-matching is in process.\n");
      SetEvaluationError(theEnv,true);
      return PSE_RULE_NETWORK_ERROR;
     }

   /* =============================================
      If we are about to change a slot of an object
      which is a basis for a firing rule, we need
      to make sure that slot is copied first
      ============================================= */
   if (ins->basisSlots != NULL)
     {
      spaddr = &ins->slotAddresses[ins->cls->slotNameMap[sp->desc->slotName->id] - 1];
      bsp = ins->basisSlots + (spaddr - ins->slotAddresses);
      if (bsp->value == NULL)
        {
         bsp->type = sp->type;
         bsp->value = sp->value;
         if (sp->desc->multiple)
           RetainMultifield(theEnv,bsp->multifieldValue);
         else
           AtomInstall(theEnv,bsp->type,bsp->value);
        }
     }

#endif
   if (sp->desc->multiple == 0)
     {
      AtomDeinstall(theEnv,sp->type,sp->value);

      /* ======================================
         Assumed that multfield already checked
         to be of cardinality 1
         ====================================== */
      if (val->header->type == MULTIFIELD_TYPE)
        {
         sp->type = val->multifieldValue->contents[val->begin].header->type;
         sp->value = val->multifieldValue->contents[val->begin].value;
        }
      else
        {
         sp->type = val->header->type;
         sp->value = val->value;
        }
      AtomInstall(theEnv,sp->type,sp->value);
      setVal->value = sp->value;
     }
   else
     {
      ReleaseMultifield(theEnv,sp->multifieldValue);
      AddToMultifieldList(theEnv,sp->multifieldValue);
      sp->type = MULTIFIELD_TYPE;
      if (val->header->type == MULTIFIELD_TYPE)
        {
         sp->value = CreateUnmanagedMultifield(theEnv,(unsigned long) val->range);
         for (i = 0 , j = val->begin ; i < val->range ; i++ , j++)
           {
            sp->multifieldValue->contents[i].value = val->multifieldValue->contents[j].value;
           }
        }
      else
        {
         sp->multifieldValue = CreateUnmanagedMultifield(theEnv,1L);
         sp->multifieldValue->contents[0].value = val->value;
        }
      RetainMultifield(theEnv,sp->multifieldValue);
      setVal->value = sp->value;
      setVal->begin = 0;
      setVal->range = sp->multifieldValue->length;
     }
   /* ==================================================
      6.05 Bug fix - any slot set directly or indirectly
      by a slot override or other side-effect during an
      instance initialization should not have its
      default value set
      ================================================== */

   sp->override = ins->initializeInProgress;

#if DEBUGGING_FUNCTIONS
   if (ins->cls->traceSlots &&
       (! ConstructData(theEnv)->ClearReadyInProgress) &&
       (! ConstructData(theEnv)->ClearInProgress))
     {
      if (sp->desc->shared)
        WriteString(theEnv,STDOUT,"::= shared slot ");
      else
        WriteString(theEnv,STDOUT,"::= local slot ");
      WriteString(theEnv,STDOUT,sp->desc->slotName->name->contents);
      WriteString(theEnv,STDOUT," in instance ");
      WriteString(theEnv,STDOUT,ins->name->contents);
      WriteString(theEnv,STDOUT," <- ");
      if (sp->type != MULTIFIELD_TYPE)
        PrintAtom(theEnv,STDOUT,sp->type,sp->value);
      else
        PrintMultifieldDriver(theEnv,STDOUT,sp->multifieldValue,0,
                              sp->multifieldValue->length,true);
      WriteString(theEnv,STDOUT,"\n");
     }
#endif
   InstanceData(theEnv)->ChangesToInstances = true;

#if DEFRULE_CONSTRUCT
   if (ins->cls->reactive && sp->desc->reactive)
     {
      /* ============================================
         If we have changed a shared slot, we need to
         perform a Rete update for every instance
         which contains this slot
         ============================================ */
      if (sp->desc->shared)
        {
         sharedTraversalID = GetTraversalID(theEnv);
         if (sharedTraversalID != -1)
           {
            NetworkModifyForSharedSlot(theEnv,sharedTraversalID,sp->desc->cls,sp->desc);
            ReleaseTraversalID(theEnv);
           }
         else
           {
            PrintErrorID(theEnv,"INSFUN",6,false);
            WriteString(theEnv,STDERR,"Unable to pattern-match on shared slot '");
            WriteString(theEnv,STDERR,sp->desc->slotName->name->contents);
            WriteString(theEnv,STDERR,"' in class '");
            WriteString(theEnv,STDERR,DefclassName(sp->desc->cls));
            WriteString(theEnv,STDERR,"'.\n");
            return PSE_RULE_NETWORK_ERROR;
           }
        }
      else
        ObjectNetworkAction(theEnv,OBJECT_MODIFY,ins,(int) sp->desc->slotName->id);
     }
#endif

   return PSE_NO_ERROR;
  }

/*******************************************************************
  NAME         : ValidSlotValue
  DESCRIPTION  : Determines if a value is appropriate
                   for a slot-value
  INPUTS       : 1) The value buffer
                 2) Slot descriptor
                 3) Instance for which slot is being checked
                    (can be NULL)
                 4) Buffer holding printout of the offending command
                    (if NULL assumes message-handler is executing
                     and calls PrintHandler for CurrentCore instead)
  RETURNS      : True if value is OK, false otherwise
  SIDE EFFECTS : Sets EvaluationError if slot is not OK
  NOTES        : Examines all fields of a multi-field
 *******************************************************************/
PutSlotError ValidSlotValue(
  Environment *theEnv,
  UDFValue *val,
  SlotDescriptor *sd,
  Instance *ins,
  const char *theCommand)
  {
   ConstraintViolationType violationCode;

   /* ===================================
      Special NoParamValue means to reset
      slot to default value
      =================================== */
   if (val->value == ProceduralPrimitiveData(theEnv)->NoParamValue)
     return PSE_NO_ERROR;
   if ((sd->multiple == 0) && (val->header->type == MULTIFIELD_TYPE) &&
                              (val->range != 1))
     {
      PrintErrorID(theEnv,"INSFUN",7,false);
      WriteString(theEnv,STDERR,"The value ");
      WriteUDFValue(theEnv,STDERR,val);
      WriteString(theEnv,STDERR," is illegal for single-field ");
      PrintSlot(theEnv,STDERR,sd,ins,theCommand);
      WriteString(theEnv,STDERR,".\n");
      SetEvaluationError(theEnv,true);
      return PSE_CARDINALITY_ERROR;
     }
   if (val->header->type == VOID_TYPE)
     {
      PrintErrorID(theEnv,"INSFUN",8,false);
      WriteString(theEnv,STDERR,"Void function illegal value for ");
      PrintSlot(theEnv,STDERR,sd,ins,theCommand);
      WriteString(theEnv,STDERR,".\n");
      SetEvaluationError(theEnv,true);
      return PSE_CARDINALITY_ERROR;
     }
   if (GetDynamicConstraintChecking(theEnv))
     {
      violationCode = ConstraintCheckDataObject(theEnv,val,sd->constraint);
      if (violationCode != NO_VIOLATION)
        {
         PrintErrorID(theEnv,"CSTRNCHK",1,false);
         WriteString(theEnv,STDERR,"The value ");
         if ((val->header->type == MULTIFIELD_TYPE) && (sd->multiple == 0))
           PrintAtom(theEnv,STDERR,val->multifieldValue->contents[val->begin].header->type,
                                   val->multifieldValue->contents[val->begin].value);
         else
           WriteUDFValue(theEnv,STDERR,val);
         WriteString(theEnv,STDERR," for ");
         PrintSlot(theEnv,STDERR,sd,ins,theCommand);
         ConstraintViolationErrorMessage(theEnv,NULL,NULL,0,0,NULL,0,
                                         violationCode,sd->constraint,false);
         SetEvaluationError(theEnv,true);

         switch(violationCode)
           {
            case NO_VIOLATION:
              SystemError(theEnv,"FACTMNGR",2);
              ExitRouter(theEnv,EXIT_FAILURE);
              break;
        
            case FUNCTION_RETURN_TYPE_VIOLATION:
            case TYPE_VIOLATION:
              return PSE_TYPE_ERROR;
              
            case RANGE_VIOLATION:
              return PSE_RANGE_ERROR;
              
            case ALLOWED_VALUES_VIOLATION:
              return PSE_ALLOWED_VALUES_ERROR;
              
            case CARDINALITY_VIOLATION:
              return PSE_CARDINALITY_ERROR;
            
            case ALLOWED_CLASSES_VIOLATION:
              return PSE_ALLOWED_CLASSES_ERROR;
           }
        }
     }
   return PSE_NO_ERROR;
  }

/********************************************************
  NAME         : CheckInstance
  DESCRIPTION  : Checks to see if the first argument to
                 a function is a valid instance
  INPUTS       : Name of the calling function
  RETURNS      : The address of the instance
  SIDE EFFECTS : EvaluationError set and messages printed
                 on errors
  NOTES        : Used by Initialize and ModifyInstance
 ********************************************************/
Instance *CheckInstance(
  UDFContext *context)
  {
   Instance *ins;
   UDFValue temp;
   Environment *theEnv = context->environment;

   UDFFirstArgument(context,ANY_TYPE_BITS,&temp);
   if (temp.header->type == INSTANCE_ADDRESS_TYPE)
     {
      ins = temp.instanceValue;
      if (ins->garbage == 1)
        {
         StaleInstanceAddress(theEnv,UDFContextFunctionName(context),0);
         SetEvaluationError(theEnv,true);
         return NULL;
        }
     }
   else if (temp.header->type == INSTANCE_NAME_TYPE)
     {
      ins = FindInstanceBySymbol(theEnv,temp.lexemeValue);
      if (ins == NULL)
        {
         NoInstanceError(theEnv,temp.lexemeValue->contents,UDFContextFunctionName(context));
         return NULL;
        }
     }
   else if (temp.header->type == SYMBOL_TYPE)
     {
      temp.value = CreateInstanceName(theEnv,temp.lexemeValue->contents);
      ins = FindInstanceBySymbol(theEnv,temp.lexemeValue);
      if (ins == NULL)
        {
         NoInstanceError(theEnv,temp.lexemeValue->contents,UDFContextFunctionName(context));
         return NULL;
        }
     }
   else
     {
      PrintErrorID(theEnv,"INSFUN",1,false);
      WriteString(theEnv,STDERR,"Expected a valid instance in function '");
      WriteString(theEnv,STDERR,UDFContextFunctionName(context));
      WriteString(theEnv,STDERR,"'.\n");
      SetEvaluationError(theEnv,true);
      return NULL;
     }
   return(ins);
  }

/***************************************************
  NAME         : NoInstanceError
  DESCRIPTION  : Prints out an appropriate error
                  message when an instance cannot be
                  found for a function
  INPUTS       : 1) The instance name
                 2) The function name
  RETURNS      : Nothing useful
  SIDE EFFECTS : None
  NOTES        : None
 ***************************************************/
void NoInstanceError(
  Environment *theEnv,
  const char *iname,
  const char *func)
  {
   PrintErrorID(theEnv,"INSFUN",2,false);
   WriteString(theEnv,STDERR,"No such instance [");
   WriteString(theEnv,STDERR,iname);
   WriteString(theEnv,STDERR,"] in function '");
   WriteString(theEnv,STDERR,func);
   WriteString(theEnv,STDERR,"'.\n");
   SetEvaluationError(theEnv,true);
  }

/***************************************************
  NAME         : StaleInstanceAddress
  DESCRIPTION  : Prints out an appropriate error
                  message when an instance address
                  is no longer valid
  INPUTS       : The function name
  RETURNS      : Nothing useful
  SIDE EFFECTS : None
  NOTES        : None
 ***************************************************/
void StaleInstanceAddress(
  Environment *theEnv,
  const char *func,
  int whichArg)
  {
   PrintErrorID(theEnv,"INSFUN",4,false);
   WriteString(theEnv,STDERR,"Invalid instance-address in function '");
   WriteString(theEnv,STDERR,func);
   WriteString(theEnv,STDERR,"'");
   if (whichArg > 0)
     {
      WriteString(theEnv,STDERR,", argument #");
      WriteInteger(theEnv,STDERR,whichArg);
     }
   WriteString(theEnv,STDERR,".\n");
  }

/**********************************************************************
  NAME         : GetInstancesChanged
  DESCRIPTION  : Returns whether instances have changed
                   (any were added/deleted or slot values were changed)
                   since last time flag was set to false
  INPUTS       : None
  RETURNS      : The instances-changed flag
  SIDE EFFECTS : None
  NOTES        : Used by interfaces to update instance windows
 **********************************************************************/
bool GetInstancesChanged(
  Environment *theEnv)
  {
   return InstanceData(theEnv)->ChangesToInstances;
  }

/*******************************************************
  NAME         : SetInstancesChanged
  DESCRIPTION  : Sets instances-changed flag (see above)
  INPUTS       : The value (true or false)
  RETURNS      : Nothing useful
  SIDE EFFECTS : The flag is set
  NOTES        : None
 *******************************************************/
void SetInstancesChanged(
  Environment *theEnv,
  bool changed)
  {
   InstanceData(theEnv)->ChangesToInstances = changed;
  }

/*******************************************************************
  NAME         : PrintSlot
  DESCRIPTION  : Displays the name and origin of a slot
  INPUTS       : 1) The logical output name
                 2) The slot descriptor
                 3) The instance source (can be NULL)
                 4) Buffer holding printout of the offending command
                    (if NULL assumes message-handler is executing
                     and calls PrintHandler for CurrentCore instead)
  RETURNS      : Nothing useful
  SIDE EFFECTS : Message printed
  NOTES        : None
 *******************************************************************/
void PrintSlot(
  Environment *theEnv,
  const char *logName,
  SlotDescriptor *sd,
  Instance *ins,
  const char *theCommand)
  {
   WriteString(theEnv,logName,"slot '");
   WriteString(theEnv,logName,sd->slotName->name->contents);
   WriteString(theEnv,logName,"'");
   if (ins != NULL)
     {
      WriteString(theEnv,logName," of instance [");
      WriteString(theEnv,logName,ins->name->contents);
      WriteString(theEnv,logName,"]");
     }
   else if (sd->cls != NULL)
     {
      WriteString(theEnv,logName," of class '");
      WriteString(theEnv,logName,DefclassName(sd->cls));
      WriteString(theEnv,logName," of class '");
     }
   WriteString(theEnv,logName," found in ");
   if (theCommand != NULL)
     WriteString(theEnv,logName,theCommand);
   else
     PrintHandler(theEnv,logName,MessageHandlerData(theEnv)->CurrentCore->hnd,true,false);
  }

/*****************************************************
  NAME         : PrintInstanceNameAndClass
  DESCRIPTION  : Displays an instance's name and class
  INPUTS       : 1) Logical name of output
                 2) The instance
                 3) Flag indicating whether to
                    print carriage-return at end
  RETURNS      : Nothing useful
  SIDE EFFECTS : Instnace name and class printed
  NOTES        : None
 *****************************************************/
void PrintInstanceNameAndClass(
  Environment *theEnv,
  const char *logicalName,
  Instance *theInstance,
  bool linefeedFlag)
  {
   WriteString(theEnv,logicalName,"[");
   WriteString(theEnv,logicalName,InstanceName(theInstance));
   WriteString(theEnv,logicalName,"] of ");
   PrintClassName(theEnv,logicalName,theInstance->cls,false,linefeedFlag);
  }

/***************************************************
  NAME         : PrintInstanceName
  DESCRIPTION  : Used by the rule system commands
                 such as (matches) and (agenda)
                 to print out the name of an instance
  INPUTS       : 1) The logical output name
                 2) A pointer to the instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Name of instance printed
  NOTES        : None
 ***************************************************/
void PrintInstanceName(
  Environment *theEnv,
  const char *logName,
  Instance *theInstance)
  {
   if (theInstance->garbage)
     {
      WriteString(theEnv,logName,"<stale instance [");
      WriteString(theEnv,logName,theInstance->name->contents);
      WriteString(theEnv,logName,"]>");
     }
   else
     {
      WriteString(theEnv,logName,"[");
      WriteString(theEnv,logName,GetFullInstanceName(theEnv,theInstance)->contents);
      WriteString(theEnv,logName,"]");
     }
  }

/***************************************************
  NAME         : PrintInstanceLongForm
  DESCRIPTION  : Used by kernel to print
                 instance addresses
  INPUTS       : 1) The logical output name
                 2) A pointer to the instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Address of instance printed
  NOTES        : None
 ***************************************************/
void PrintInstanceLongForm(
  Environment *theEnv,
  const char *logName,
  Instance *theInstance)
  {
   if (PrintUtilityData(theEnv)->InstanceAddressesToNames)
     {
      if (theInstance == &InstanceData(theEnv)->DummyInstance)
        WriteString(theEnv,logName,"\"<Dummy Instance>\"");
      else
        {
         WriteString(theEnv,logName,"[");
         WriteString(theEnv,logName,GetFullInstanceName(theEnv,theInstance)->contents);
         WriteString(theEnv,logName,"]");
        }
     }
   else
     {
      if (PrintUtilityData(theEnv)->AddressesToStrings)
        WriteString(theEnv,logName,"\"");
      if (theInstance == &InstanceData(theEnv)->DummyInstance)
        WriteString(theEnv,logName,"<Dummy Instance>");
      else if (theInstance->garbage)
        {
         WriteString(theEnv,logName,"<Stale Instance-");
         WriteString(theEnv,logName,theInstance->name->contents);
         WriteString(theEnv,logName,">");
        }
      else
        {
         WriteString(theEnv,logName,"<Instance-");
         WriteString(theEnv,logName,GetFullInstanceName(theEnv,theInstance)->contents);
         WriteString(theEnv,logName,">");
        }
      if (PrintUtilityData(theEnv)->AddressesToStrings)
        WriteString(theEnv,logName,"\"");
     }
  }

#if DEFRULE_CONSTRUCT

/***************************************************
  NAME         : DecrementObjectBasisCount
  DESCRIPTION  : Decrements the basis count of an
                 object indicating that it is in
                 use by the partial match of the
                 currently executing rule
  INPUTS       : The instance address
  RETURNS      : Nothing useful
  SIDE EFFECTS : Basis count decremented and
                 basis copy (possibly) deleted
  NOTES        : When the count goes to zero, the
                 basis copy of the object (if any)
                 is deleted.
 ***************************************************/
void DecrementObjectBasisCount(
  Environment *theEnv,
  Instance *theInstance)
  {
   long i;

   theInstance->patternHeader.busyCount--;
   if (theInstance->patternHeader.busyCount == 0)
     {
      if (theInstance->garbage)
        RemoveInstanceData(theEnv,theInstance);
      if (theInstance->cls->instanceSlotCount != 0)
        {
         for (i = 0 ; i < theInstance->cls->instanceSlotCount ; i++)
           if (theInstance->basisSlots[i].value != NULL)
             {
              if (theInstance->basisSlots[i].desc->multiple)
                ReleaseMultifield(theEnv,theInstance->basisSlots[i].multifieldValue);
              else
                AtomDeinstall(theEnv,theInstance->basisSlots[i].type,
                              theInstance->basisSlots[i].value);
             }
         rm(theEnv,theInstance->basisSlots,
            (theInstance->cls->instanceSlotCount * sizeof(InstanceSlot)));
         theInstance->basisSlots = NULL;
        }
     }
  }

/***************************************************
  NAME         : IncrementObjectBasisCount
  DESCRIPTION  : Increments the basis count of an
                 object indicating that it is in
                 use by the partial match of the
                 currently executing rule

                 If this the count was zero,
                 allocate an array of extra
                 instance slots for use by
                 slot variables
  INPUTS       : The instance address
  RETURNS      : Nothing useful
  SIDE EFFECTS : Basis count incremented
  NOTES        : None
 ***************************************************/
void IncrementObjectBasisCount(
  Environment *theEnv,
  Instance *theInstance)
  {
   long i;

   if (theInstance->patternHeader.busyCount == 0)
     {
      if (theInstance->cls->instanceSlotCount != 0)
        {
         theInstance->basisSlots = (InstanceSlot *)
                            gm2(theEnv,(sizeof(InstanceSlot) * theInstance->cls->instanceSlotCount));
         for (i = 0 ; i < theInstance->cls->instanceSlotCount ; i++)
           {
            theInstance->basisSlots[i].desc = theInstance->slotAddresses[i]->desc;
            theInstance->basisSlots[i].value = NULL;
           }
        }
     }
   theInstance->patternHeader.busyCount++;
  }

/***************************************************
  NAME         : MatchObjectFunction
  DESCRIPTION  : Filters an instance through the
                 object pattern network
                 Used for incremental resets in
                 binary loads and run-time modules
  INPUTS       : The instance
  RETURNS      : Nothing useful
  SIDE EFFECTS : Instance pattern-matched
  NOTES        : None
 ***************************************************/
void MatchObjectFunction(
  Environment *theEnv,
  Instance *theInstance)
  {
   ObjectNetworkAction(theEnv,OBJECT_ASSERT,theInstance,-1);
  }

/***************************************************
  NAME         : NetworkSynchronized
  DESCRIPTION  : Determines if state of instance is
                 consistent with last push through
                 pattern-matching network
  INPUTS       : The instance
  RETURNS      : True if instance has not
                 changed since last push through the
                 Rete network, false otherwise
  SIDE EFFECTS : None
  NOTES        : None
 ***************************************************/
bool NetworkSynchronized(
  Environment *theEnv,
  Instance *theInstance)
  {
#if MAC_XCD
#pragma unused(theEnv)
#endif

   return theInstance->reteSynchronized;
  }

/***************************************************
  NAME         : InstanceIsDeleted
  DESCRIPTION  : Determines if an instance has been
                 deleted
  INPUTS       : The instance
  RETURNS      : True if instance has been deleted,
                 false otherwise
  SIDE EFFECTS : None
  NOTES        : None
 ***************************************************/
bool InstanceIsDeleted(
  Environment *theEnv,
  Instance *theInstance)
  {
#if MAC_XCD
#pragma unused(theEnv)
#endif

   return theInstance->garbage;
  }
#endif

/* =========================================
   *****************************************
          INTERNALLY VISIBLE FUNCTIONS
   =========================================
   ***************************************** */

/*****************************************************
  NAME         : FindImportedInstance
  DESCRIPTION  : Searches imported modules for an
                 instance of the correct name
                 The imports are searched recursively
                 in the order of the module definition
  INPUTS       : 1) The module for which to
                    search imported modules
                 2) The currently active module
                 3) The first instance of the
                    correct name (cannot be NULL)
  RETURNS      : An instance of the correct name
                 imported from another module which
                 is in scope of the current module
  SIDE EFFECTS : None
  NOTES        : None
 *****************************************************/
static Instance *FindImportedInstance(
  Environment *theEnv,
  Defmodule *theModule,
  Defmodule *currentModule,
  Instance *startInstance)
  {
   struct portItem *importList;
   Instance *ins;

   if (theModule->visitedFlag)
     return NULL;
   theModule->visitedFlag = true;
   importList = theModule->importList;
   while (importList != NULL)
     {
      theModule = FindDefmodule(theEnv,importList->moduleName->contents);
      for (ins = startInstance ;
           (ins != NULL) ? (ins->name == startInstance->name) : false ;
           ins = ins->nxtHash)
        if ((ins->cls->header.whichModule->theModule == theModule) &&
             DefclassInScope(theEnv,ins->cls,currentModule))
          return(ins);
      ins = FindImportedInstance(theEnv,theModule,currentModule,startInstance);
      if (ins != NULL)
        return(ins);
      importList = importList->next;
     }

   /* ========================================================
      Make sure instances of system classes are always visible
      ======================================================== */
   for (ins = startInstance ;
        (ins != NULL) ? (ins->name == startInstance->name) : false ;
        ins = ins->nxtHash)
     if (ins->cls->system)
       return(ins);

   return NULL;
  }

#if DEFRULE_CONSTRUCT

/*****************************************************
  NAME         : NetworkModifyForSharedSlot
  DESCRIPTION  : Performs a Rete network modify for
                 all instances which contain a
                 specific shared slot
  INPUTS       : 1) The traversal id to use when
                    recursively entering subclasses
                    to prevent duplicate examinations
                    of a class
                 2) The class
                 3) The descriptor for the shared slot
  RETURNS      : Nothing useful
  SIDE EFFECTS : Instances which contain the shared
                 slot are filtered through the
                 Rete network via a retract/assert
  NOTES        : Assumes traversal id has been
                 established
 *****************************************************/
static void NetworkModifyForSharedSlot(
  Environment *theEnv,
  int sharedTraversalID,
  Defclass *cls,
  SlotDescriptor *sd)
  {
   Instance *ins;
   unsigned long i;

   /* ================================================
      Make sure we haven't already examined this class
      ================================================ */
   if (TestTraversalID(cls->traversalRecord,sharedTraversalID))
     return;
   SetTraversalID(cls->traversalRecord,sharedTraversalID);

   /* ===========================================
      If the instances of this class contain the
      shared slot, send update events to the Rete
      network for all of its instances
      =========================================== */
   if ((sd->slotName->id > cls->maxSlotNameID) ? false :
       ((cls->slotNameMap[sd->slotName->id] == 0) ? false :
        (cls->instanceTemplate[cls->slotNameMap[sd->slotName->id] - 1] == sd)))
     {
      for (ins = cls->instanceList ; ins != NULL ; ins = ins->nxtClass)
        ObjectNetworkAction(theEnv,OBJECT_MODIFY,ins,(int) sd->slotName->id);
     }

   /* ==================================
      Check the subclasses of this class
      ================================== */
   for (i = 0 ; i < cls->directSubclasses.classCount ; i++)
     NetworkModifyForSharedSlot(theEnv,sharedTraversalID,cls->directSubclasses.classArray[i],sd);
  }

#endif /* DEFRULE_CONSTRUCT */

#endif /* OBJECT_SYSTEM */