diff options
author | Somin Kim <somin926.kim@samsung.com> | 2015-06-02 16:04:49 +0900 |
---|---|---|
committer | Somin Kim <somin926.kim@samsung.com> | 2015-06-02 16:36:49 +0900 |
commit | ab87ef99aae26739df6a64a7234a5b42ee9af342 (patch) | |
tree | d5a301868959f7fe53e7c304af9fccc4e4818e6d | |
parent | 5f30dbb120b11fa36bdd599d36bb0d7efb255ea5 (diff) | |
download | clips-ab87ef99aae26739df6a64a7234a5b42ee9af342.tar.gz clips-ab87ef99aae26739df6a64a7234a5b42ee9af342.tar.bz2 clips-ab87ef99aae26739df6a64a7234a5b42ee9af342.zip |
Updated to version 6.30
Change-Id: Ie97f658f5742af01875b1289b2e63ad003e2a284
Signed-off-by: Somin Kim <somin926.kim@samsung.com>
339 files changed, 29891 insertions, 14078 deletions
diff --git a/packaging/clips.spec b/packaging/clips.spec index 070b93d..23e60ff 100644 --- a/packaging/clips.spec +++ b/packaging/clips.spec @@ -1,6 +1,6 @@ Name: clips Summary: C Language Integrated Production System (CLIPS) Library -Version: 6.24 +Version: 6.30 Release: 1 Group: System/Libraries License: Public diff --git a/src/agenda.c b/src/agenda.c index 30ce97a..0026a5d 100644 --- a/src/agenda.c +++ b/src/agenda.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* AGENDA MODULE */ /*******************************************************/ @@ -15,7 +15,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* 6.23: Corrected compilation errors for files */ @@ -28,6 +28,20 @@ /* */ /* Added EnvGetActivationBasisPPForm function. */ /* */ +/* 6.30: Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _AGENDA_SOURCE_ @@ -65,10 +79,13 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void PrintActivation(void *,char *,void *); + static void PrintActivation(void *,const char *,void *); static void AgendaClearFunction(void *); - static char *SalienceEvaluationName(int); + static const char *SalienceEvaluationName(int); static int EvaluateSalience(void *,void *); + static struct salienceGroup *ReuseOrCreateSalienceGroup(void *,struct defruleModule *,int); + static struct salienceGroup *FindSalienceGroup(struct defruleModule *,int); + static void RemoveActivationFromGroup(void *,struct activation *,struct defruleModule *); /*************************************************/ /* InitializeAgenda: Initializes the activations */ @@ -77,13 +94,13 @@ /*************************************************/ globle void InitializeAgenda( void *theEnv) - { + { AllocateEnvironmentData(theEnv,AGENDA_DATA,sizeof(struct agendaData),NULL); - + AgendaData(theEnv)->SalienceEvaluation = WHEN_DEFINED; AgendaData(theEnv)->Strategy = DEFAULT_STRATEGY; - + EnvAddClearFunction(theEnv,"agenda",AgendaClearFunction,0); #if DEBUGGING_FUNCTIONS AddWatchItem(theEnv,"activations",1,&AgendaData(theEnv)->WatchActivations,40,DefruleWatchAccess,DefruleWatchPrint); @@ -123,6 +140,7 @@ globle void AddActivation( struct defrule *theRule = (struct defrule *) vTheRule; struct partialMatch *binds = (struct partialMatch *) vBinds; struct defruleModule *theModuleItem; + struct salienceGroup *theGroup; /*=======================================*/ /* Focus on the module if the activation */ @@ -146,7 +164,6 @@ globle void AddActivation( newActivation->timetag = AgendaData(theEnv)->CurrentTimetag++; newActivation->salience = EvaluateSalience(theEnv,theRule); - newActivation->sortedBasis = NULL; newActivation->randomID = genrand(); newActivation->prev = NULL; newActivation->next = NULL; @@ -158,7 +175,7 @@ globle void AddActivation( /* the link between the join network and the agenda. */ /*=======================================================*/ - binds->binds[binds->bcount].gm.theValue = (void *) newActivation; + binds->marker = (void *) newActivation; /*====================================================*/ /* If activations are being watch, display a message. */ @@ -178,10 +195,76 @@ globle void AddActivation( /*=====================================*/ theModuleItem = (struct defruleModule *) theRule->header.whichModule; - PlaceActivation(theEnv,&(theModuleItem->agenda),newActivation); + + theGroup = ReuseOrCreateSalienceGroup(theEnv,theModuleItem,newActivation->salience); + + PlaceActivation(theEnv,&(theModuleItem->agenda),newActivation,theGroup); } /***************************************************************/ +/* ReuseOrCreateSalienceGroup: */ +/***************************************************************/ +static struct salienceGroup *ReuseOrCreateSalienceGroup( + void *theEnv, + struct defruleModule *theRuleModule, + int salience) + { + struct salienceGroup *theGroup, *lastGroup, *newGroup; + + for (lastGroup = NULL, theGroup = theRuleModule->groupings; + theGroup != NULL; + lastGroup = theGroup, theGroup = theGroup->next) + { + if (theGroup->salience == salience) + { return(theGroup); } + + if (theGroup->salience < salience) + { break; } + } + + newGroup = get_struct(theEnv,salienceGroup); + newGroup->salience = salience; + newGroup->first = NULL; + newGroup->last = NULL; + newGroup->next = theGroup; + newGroup->prev = lastGroup; + + if (newGroup->next != NULL) + { newGroup->next->prev = newGroup; } + + if (newGroup->prev != NULL) + { newGroup->prev->next = newGroup; } + + if (lastGroup == NULL) + { theRuleModule->groupings = newGroup; } + + return newGroup; + } + +/***************************************************************/ +/* FindSalienceGroup: */ +/***************************************************************/ +static struct salienceGroup *FindSalienceGroup( + struct defruleModule *theRuleModule, + int salience) + { + struct salienceGroup *theGroup; + + for (theGroup = theRuleModule->groupings; + theGroup != NULL; + theGroup = theGroup->next) + { + if (theGroup->salience == salience) + { return(theGroup); } + + if (theGroup->salience < salience) + { break; } + } + + return NULL; + } + +/***************************************************************/ /* ClearRuleFromAgenda: Clears the agenda of a specified rule. */ /***************************************************************/ globle void ClearRuleFromAgenda( @@ -239,7 +322,7 @@ globle void *EnvGetNextActivation( void *actPtr) { struct defruleModule *theModuleItem; - + if (actPtr == NULL) { theModuleItem = (struct defruleModule *) GetModuleItem(theEnv,NULL,DefruleData(theEnv)->DefruleModuleIndex); @@ -250,38 +333,74 @@ globle void *EnvGetNextActivation( { return((void *) (((struct activation *) actPtr)->next)); } } +/***********************************************/ +/* EnvGetActivationBasis: Returns the basis of */ +/* the rule associated with an activation. */ +/***********************************************/ +globle struct partialMatch *EnvGetActivationBasis( + void *theEnv, + void *actPtr) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + return ((struct activation *) actPtr)->basis; + } + /*********************************************/ /* EnvGetActivationName: Returns the name of */ /* the rule associated with an activation. */ /*********************************************/ -#if IBM_TBC -#pragma argsused +globle const char *EnvGetActivationName( + void *theEnv, + void *actPtr) + { +#if MAC_XCD +#pragma unused(theEnv) #endif -globle char *EnvGetActivationName( + + return(ValueToString(((struct activation *) actPtr)->theRule->header.name)); + } + +/******************************************/ +/* EnvGetActivationRule: Returns the rule */ +/* associated with an activation. */ +/******************************************/ +globle struct defrule *EnvGetActivationRule( void *theEnv, void *actPtr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif + return ((struct activation *) actPtr)->theRule; + } - return(ValueToString(((struct activation *) actPtr)->theRule->header.name)); +/**************************************************/ +/* EnvGetActivationSalience: Returns the salience */ +/* of the rule associated with an activation. */ +/**************************************************/ +globle int EnvGetActivationSalience( + void *theEnv, + void *actPtr) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + return ((struct activation *) actPtr)->salience; } /**************************************/ /* EnvSetActivationSalience: Sets the */ /* salience value of an activation. */ /**************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int EnvSetActivationSalience( void *theEnv, void *actPtr, int value) { int temp; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -297,7 +416,7 @@ globle int EnvSetActivationSalience( globle void EnvGetActivationPPForm( void *theEnv, char *buffer, - unsigned bufferLength, + size_t bufferLength, void *theActivation) { OpenStringDestination(theEnv,"ActPPForm",buffer,bufferLength); @@ -312,7 +431,7 @@ globle void EnvGetActivationPPForm( globle void EnvGetActivationBasisPPForm( void *theEnv, char *buffer, - unsigned bufferLength, + size_t bufferLength, void *vTheActivation) { struct activation *theActivation = (struct activation *) vTheActivation; @@ -415,6 +534,8 @@ globle intBool DetachActivation( theModuleItem = (struct defruleModule *) theActivation->theRule->header.whichModule; + RemoveActivationFromGroup(theEnv,theActivation,theModuleItem); + /*========================================================*/ /* If the activation is the top activation on the agenda, */ /* then update the module pointer to agenda. */ @@ -459,13 +580,13 @@ globle intBool DetachActivation( /****************************************************************************/ static void PrintActivation( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheActivation) { struct activation *theActivation = (struct activation *) vTheActivation; char printSpace[20]; - sprintf(printSpace,"%-6d ",theActivation->salience); + gensprintf(printSpace,"%-6d ",theActivation->salience); EnvPrintRouter(theEnv,logicalName,printSpace); EnvPrintRouter(theEnv,logicalName,ValueToString(theActivation->theRule->header.name)); EnvPrintRouter(theEnv,logicalName,": "); @@ -478,7 +599,7 @@ static void PrintActivation( /*******************************/ globle void EnvAgenda( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheModule) { struct defmodule *theModule = (struct defmodule *) vTheModule; @@ -514,6 +635,8 @@ globle void RemoveActivation( if (updateAgenda == TRUE) { + RemoveActivationFromGroup(theEnv,theActivation,theModuleItem); + /*===============================================*/ /* Update the pointer links between activations. */ /*===============================================*/ @@ -556,7 +679,7 @@ globle void RemoveActivation( /*============================================*/ if ((updateLinks == TRUE) && (theActivation->basis != NULL)) - { theActivation->basis->binds[theActivation->basis->bcount].gm.theValue = NULL; } + { theActivation->basis->marker = NULL; } /*================================================*/ /* Return the activation to the free memory pool. */ @@ -564,13 +687,71 @@ globle void RemoveActivation( AgendaData(theEnv)->NumberOfActivations--; - if (theActivation->sortedBasis != NULL) - { ReturnPartialMatch(theEnv,theActivation->sortedBasis); } - rtn_struct(theEnv,activation,theActivation); } /**************************************************************/ +/* RemoveActivationFromGroup: */ +/**************************************************************/ +static void RemoveActivationFromGroup( + void *theEnv, + struct activation *theActivation, + struct defruleModule *theRuleModule) + { + struct salienceGroup *theGroup; + + theGroup = FindSalienceGroup(theRuleModule,theActivation->salience); + if (theGroup == NULL) return; + + if (theActivation == theGroup->first) + { + /*====================================================*/ + /* If the activation is the only remaining activation */ + /* in the group, then the group needs to be removed. */ + /*====================================================*/ + + if (theActivation == theGroup->last) + { + if (theGroup->prev == NULL) + { theRuleModule->groupings = theGroup->next; } + else + { theGroup->prev->next = theGroup->next; } + + if (theGroup->next != NULL) + { theGroup->next->prev = theGroup->prev; } + + rtn_struct(theEnv,salienceGroup,theGroup); + } + + /*======================================================*/ + /* Otherwise this is the first activation in the group, */ + /* but there are other activations which follow. */ + /*======================================================*/ + + else + { theGroup->first = theActivation->next; } + } + else + { + /*====================================================*/ + /* Otherwise if the activation isn't the first in the */ + /* group, then check to see if it's the last. */ + /*====================================================*/ + + if (theActivation == theGroup->last) + { theGroup->last = theActivation->prev; } + + /*==================================================*/ + /* Otherwise the activation is in the middle of the */ + /* group and no first/last updates are needed. */ + /*==================================================*/ + + else + { return; } + } + } + +/**************************************************************/ /* AgendaClearFunction: Agenda clear routine for use with the */ /* clear command. Resets the current time tag to zero. */ /**************************************************************/ @@ -588,6 +769,7 @@ globle void RemoveAllActivations( void *theEnv) { struct activation *tempPtr, *theActivation; + struct salienceGroup *theGroup, *tempGroup; theActivation = GetDefruleModuleItem(theEnv,NULL)->agenda; while (theActivation != NULL) @@ -596,7 +778,15 @@ globle void RemoveAllActivations( RemoveActivation(theEnv,theActivation,TRUE,TRUE); theActivation = tempPtr; } - } + + theGroup = GetDefruleModuleItem(theEnv,NULL)->groupings; + while (theGroup != NULL) + { + tempGroup = theGroup->next; + rtn_struct(theEnv,salienceGroup,theGroup); + theGroup = tempGroup; + } + } /*********************************************************/ /* EnvGetAgendaChanged: Returns the value of the boolean */ @@ -632,6 +822,7 @@ globle void EnvReorderAgenda( struct defmodule *theModule = (struct defmodule *) vTheModule; int allModules = FALSE; struct defruleModule *theModuleItem; + struct salienceGroup *theGroup, *tempGroup; /*=============================================*/ /* If the module specified is a NULL pointer, */ @@ -661,6 +852,16 @@ globle void EnvReorderAgenda( theActivation = theModuleItem->agenda; theModuleItem->agenda = NULL; + theGroup = theModuleItem->groupings; + while (theGroup != NULL) + { + tempGroup = theGroup->next; + rtn_struct(theEnv,salienceGroup,theGroup); + theGroup = tempGroup; + } + + theModuleItem->groupings = NULL; + /*=========================================*/ /* Reorder the activations by placing them */ /* back on the agenda one by one. */ @@ -671,7 +872,8 @@ globle void EnvReorderAgenda( tempPtr = theActivation->next; theActivation->next = NULL; theActivation->prev = NULL; - PlaceActivation(theEnv,&(theModuleItem->agenda),theActivation); + theGroup = ReuseOrCreateSalienceGroup(theEnv,theModuleItem,theActivation->salience); + PlaceActivation(theEnv,&(theModuleItem->agenda),theActivation,theGroup); theActivation = tempPtr; } @@ -689,8 +891,8 @@ globle void EnvReorderAgenda( /****************************************************/ globle unsigned long GetNumberOfActivations( void *theEnv) - { - return(AgendaData(theEnv)->NumberOfActivations); + { + return(AgendaData(theEnv)->NumberOfActivations); } /******************************************************/ @@ -700,7 +902,7 @@ globle unsigned long GetNumberOfActivations( globle void RefreshCommand( void *theEnv) { - char *ruleName; + const char *ruleName; void *rulePtr; /*===========================*/ @@ -738,7 +940,8 @@ globle intBool EnvRefresh( { struct defrule *rulePtr; struct partialMatch *listOfMatches; - + unsigned long b; + /*====================================*/ /* Refresh each disjunct of the rule. */ /*====================================*/ @@ -752,22 +955,24 @@ globle intBool EnvRefresh( /* satisfies the LHS of the rule. */ /*================================*/ - for (listOfMatches = rulePtr->lastJoin->beta; - listOfMatches != NULL; - listOfMatches = listOfMatches->next) + for (b = 0; b < rulePtr->lastJoin->leftMemory->size; b++) { - /*=======================================================*/ - /* If the partial match is associated with an activation */ - /* (which it should always be) and it isn't associated */ - /* with a not CE that still has matches, then place a */ - /* new activation on the agenda if this partial match */ - /* doesn't have an activation associated with it. */ - /*=======================================================*/ - - if ((listOfMatches->activationf) && (! listOfMatches->counterf)) + for (listOfMatches = rulePtr->lastJoin->leftMemory->beta[b]; + listOfMatches != NULL; + listOfMatches = listOfMatches->nextInMemory) { - if (listOfMatches->binds[listOfMatches->bcount].gm.theValue == NULL) - { AddActivation(theEnv,rulePtr,listOfMatches); } + /*=======================================================*/ + /* If the partial match is associated with an activation */ + /* (which it should always be), then place a new */ + /* activation on the agenda if this partial matchdoesn't */ + /* have an activation associated with it. */ + /*=======================================================*/ + + if (((struct joinNode *) listOfMatches->owner)->ruleToActivate != NULL) + { + if (listOfMatches->marker == NULL) + { AddActivation(theEnv,rulePtr,listOfMatches); } + } } } } @@ -824,7 +1029,7 @@ globle void EnvRefreshAgenda( struct defmodule *theModule = (struct defmodule *) vTheModule; intBool oldValue; int allModules = FALSE; - + /*==========================*/ /* Save the current module. */ /*==========================*/ @@ -915,7 +1120,8 @@ globle void *SetSalienceEvaluationCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument, *oldValue; + const char *argument; + const char *oldValue; /*==================================================*/ /* Get the current setting for salience evaluation. */ @@ -979,10 +1185,10 @@ globle void *GetSalienceEvaluationCommand( /* to a specified salience evaluation behavior, returns a */ /* character string of the behavior's name. */ /*****************************************************************/ -static char *SalienceEvaluationName( +static const char *SalienceEvaluationName( int strategy) { - char *sname; + const char *sname; switch (strategy) { @@ -1010,8 +1216,8 @@ static char *SalienceEvaluationName( /****************************************************************/ globle intBool EnvGetSalienceEvaluation( void *theEnv) - { - return(AgendaData(theEnv)->SalienceEvaluation); + { + return(AgendaData(theEnv)->SalienceEvaluation); } /***********************************************/ @@ -1153,5 +1359,111 @@ globle void AgendaCommand( #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void Agenda( + const char *logicalName, + void *vTheModule) + { + EnvAgenda(GetCurrentEnvironment(),logicalName,vTheModule); + } + +globle intBool DeleteActivation( + void *theActivation) + { + return EnvDeleteActivation(GetCurrentEnvironment(),theActivation); + } + +globle struct partialMatch *GetActivationBasis( + void *actPtr) + { + return EnvGetActivationBasis(GetCurrentEnvironment(),actPtr); + } + +globle const char *GetActivationName( + void *actPtr) + { + return EnvGetActivationName(GetCurrentEnvironment(),actPtr); + } + +globle void GetActivationPPForm( + char *buffer, + unsigned bufferLength, + void *theActivation) + { + EnvGetActivationPPForm(GetCurrentEnvironment(),buffer,bufferLength,theActivation); + } + +globle struct defrule *GetActivationRule( + void *actPtr) + { + return EnvGetActivationRule(GetCurrentEnvironment(),actPtr); + } + +globle int GetActivationSalience( + void *actPtr) + { + return EnvGetActivationSalience(GetCurrentEnvironment(),actPtr); + } + +globle int GetAgendaChanged() + { + return EnvGetAgendaChanged(GetCurrentEnvironment()); + } + +globle void *GetNextActivation( + void *actPtr) + { + return EnvGetNextActivation(GetCurrentEnvironment(),actPtr); + } + +globle intBool Refresh( + void *theRule) + { + return EnvRefresh(GetCurrentEnvironment(),theRule); + } + +globle void RefreshAgenda( + void *vTheModule) + { + EnvRefreshAgenda(GetCurrentEnvironment(),vTheModule); + } + +globle void ReorderAgenda( + void *vTheModule) + { + EnvReorderAgenda(GetCurrentEnvironment(),vTheModule); + } + +globle void SetAgendaChanged( + int value) + { + EnvSetAgendaChanged(GetCurrentEnvironment(),value); + } + +globle int SetActivationSalience( + void *actPtr, + int value) + { + return EnvSetActivationSalience(GetCurrentEnvironment(),actPtr,value); + } + +globle intBool GetSalienceEvaluation() + { + return EnvGetSalienceEvaluation(GetCurrentEnvironment()); + } + +globle intBool SetSalienceEvaluation( + int value) + { + return EnvSetSalienceEvaluation(GetCurrentEnvironment(),value); + } + +#endif + #endif /* DEFRULE_CONSTRUCT */ diff --git a/src/agenda.h b/src/agenda.h index 3ce32f3..6f221c5 100644 --- a/src/agenda.h +++ b/src/agenda.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* AGENDA HEADER FILE */ /*******************************************************/ @@ -27,6 +27,20 @@ /* */ /* Added EnvGetActivationBasisPPForm function. */ /* */ +/* 6.30: Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_agenda @@ -59,33 +73,37 @@ struct activation struct defrule *theRule; struct partialMatch *basis; int salience; - unsigned long int timetag; - struct partialMatch *sortedBasis; + unsigned long long timetag; int randomID; struct activation *prev; struct activation *next; }; +struct salienceGroup + { + int salience; + struct activation *first; + struct activation *last; + struct salienceGroup *next; + struct salienceGroup *prev; + }; + typedef struct activation ACTIVATION; #define AGENDA_DATA 17 struct agendaData - { + { #if DEBUGGING_FUNCTIONS unsigned WatchActivations; #endif unsigned long NumberOfActivations; - unsigned long CurrentTimetag; + unsigned long long CurrentTimetag; int AgendaChanged; intBool SalienceEvaluation; int Strategy; }; -#define EnvGetActivationSalience(theEnv,actPtr) (((struct activation *) actPtr)->salience) -#define GetActivationRule(actPtr) (((struct activation *) actPtr)->theRule) -#define GetActivationBasis(actPtr) (((struct activation *) actPtr)->basis) -#define GetActivationSortedBasis(actPtr) (((struct activation *) actPtr)->sortedBasis) #define AgendaData(theEnv) ((struct agendaData *) GetEnvironmentData(theEnv,AGENDA_DATA)) #ifdef LOCALE @@ -102,49 +120,20 @@ struct agendaData /* GLOBAL EXTERNAL FUNCTION DEFINITIONS */ /****************************************/ -#if ENVIRONMENT_API_ONLY -#define Agenda(theEnv,a,b) EnvAgenda(theEnv,a,b) -#define DeleteActivation(theEnv,a) EnvDeleteActivation(theEnv,a) -#define GetActivationName(theEnv,a) EnvGetActivationName(theEnv,a) -#define GetActivationPPForm(theEnv,a,b,c) EnvGetActivationPPForm(theEnv,a,b,c) -#define GetActivationSalience(theEnv,actPtr) (((struct activation *) actPtr)->salience) -#define GetAgendaChanged(theEnv) EnvGetAgendaChanged(theEnv) -#define GetNextActivation(theEnv,a) EnvGetNextActivation(theEnv,a) -#define GetSalienceEvaluation(theEnv) EnvGetSalienceEvaluation(theEnv) -#define Refresh(theEnv,a) EnvRefresh(theEnv,a) -#define RefreshAgenda(theEnv,a) EnvRefreshAgenda(theEnv,a) -#define ReorderAgenda(theEnv,a) EnvReorderAgenda(theEnv,a) -#define SetActivationSalience(theEnv,a,b) EnvSetActivationSalience(theEnv,a,b) -#define SetAgendaChanged(theEnv,a) EnvSetAgendaChanged(theEnv,a) -#define SetSalienceEvaluation(theEnv,a) EnvSetSalienceEvaluation(theEnv,a) -#else -#define Agenda(a,b) EnvAgenda(GetCurrentEnvironment(),a,b) -#define DeleteActivation(a) EnvDeleteActivation(GetCurrentEnvironment(),a) -#define GetActivationName(a) EnvGetActivationName(GetCurrentEnvironment(),a) -#define GetActivationPPForm(a,b,c) EnvGetActivationPPForm(GetCurrentEnvironment(),a,b,c) -#define GetActivationSalience(actPtr) (((struct activation *) actPtr)->salience) -#define GetAgendaChanged() EnvGetAgendaChanged(GetCurrentEnvironment()) -#define GetNextActivation(a) EnvGetNextActivation(GetCurrentEnvironment(),a) -#define GetSalienceEvaluation() EnvGetSalienceEvaluation(GetCurrentEnvironment()) -#define Refresh(a) EnvRefresh(GetCurrentEnvironment(),a) -#define RefreshAgenda(a) EnvRefreshAgenda(GetCurrentEnvironment(),a) -#define ReorderAgenda(a) EnvReorderAgenda(GetCurrentEnvironment(),a) -#define SetActivationSalience(a,b) EnvSetActivationSalience(GetCurrentEnvironment(),a,b) -#define SetAgendaChanged(a) EnvSetAgendaChanged(GetCurrentEnvironment(),a) -#define SetSalienceEvaluation(a) EnvSetSalienceEvaluation(GetCurrentEnvironment(),a) -#endif - LOCALE void AddActivation(void *,void *,void *); LOCALE void ClearRuleFromAgenda(void *,void *); LOCALE void *EnvGetNextActivation(void *,void *); - LOCALE char *EnvGetActivationName(void *,void *); + LOCALE struct partialMatch *EnvGetActivationBasis(void *,void *); + LOCALE const char *EnvGetActivationName(void *,void *); + LOCALE struct defrule *EnvGetActivationRule(void *,void *); + LOCALE int EnvGetActivationSalience(void *,void *); LOCALE int EnvSetActivationSalience(void *,void *,int); - LOCALE void EnvGetActivationPPForm(void *,char *,unsigned,void *); - LOCALE void EnvGetActivationBasisPPForm(void *,char *,unsigned,void *); + LOCALE void EnvGetActivationPPForm(void *,char *,size_t,void *); + LOCALE void EnvGetActivationBasisPPForm(void *,char *,size_t,void *); LOCALE intBool MoveActivationToTop(void *,void *); LOCALE intBool EnvDeleteActivation(void *,void *); LOCALE intBool DetachActivation(void *,void *); - LOCALE void EnvAgenda(void *,char *,void *); + LOCALE void EnvAgenda(void *,const char *,void *); LOCALE void RemoveActivation(void *,void *,int,int); LOCALE void RemoveAllActivations(void *); LOCALE int EnvGetAgendaChanged(void *); @@ -164,6 +153,27 @@ struct agendaData LOCALE void AgendaCommand(void *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void Agenda(const char *,void *); + LOCALE intBool DeleteActivation(void *); + LOCALE struct partialMatch *GetActivationBasis(void *); + LOCALE const char *GetActivationName(void *); + LOCALE void GetActivationPPForm(char *,unsigned,void *); + LOCALE struct defrule *GetActivationRule(void *); + LOCALE int GetActivationSalience(void *); + LOCALE int GetAgendaChanged(void); + LOCALE void *GetNextActivation(void *); + LOCALE intBool GetSalienceEvaluation(void); + LOCALE intBool Refresh(void *); + LOCALE void RefreshAgenda(void *); + LOCALE void ReorderAgenda(void *); + LOCALE int SetActivationSalience(void *,int); + LOCALE void SetAgendaChanged(int); + LOCALE intBool SetSalienceEvaluation(int); + +#endif + #endif diff --git a/src/analysis.c b/src/analysis.c index 0794435..47ae207 100644 --- a/src/analysis.c +++ b/src/analysis.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* ANALYSIS MODULE */ /*******************************************************/ @@ -21,6 +21,8 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Join network rework and optimizations. */ +/* */ /*************************************************************/ #define _ANALYSIS_SOURCE_ @@ -48,6 +50,9 @@ #include "modulutl.h" #include "analysis.h" +#include "watch.h" +#include "rulepsr.h" + #if DEFGLOBAL_CONSTRUCT #include "globldef.h" #endif @@ -56,7 +61,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int GetVariables(void *,struct lhsParseNode *); + static int GetVariables(void *,struct lhsParseNode *,int,struct nandFrame *); static intBool UnboundVariablesInPattern(void *,struct lhsParseNode *,int); static int PropagateVariableToNodes(void *, struct lhsParseNode *, @@ -79,11 +84,15 @@ static int ProcessField(void *theEnv, struct lhsParseNode *, struct lhsParseNode *, - struct lhsParseNode *); + struct lhsParseNode *, + int, + struct nandFrame *); static int ProcessVariable(void *, struct lhsParseNode *, struct lhsParseNode *, - struct lhsParseNode *); + struct lhsParseNode *, + int, + struct nandFrame *); static void VariableMixingErrorMessage(void *,struct symbolHashNode *); static int PropagateVariableDriver(void *, struct lhsParseNode *, @@ -91,7 +100,9 @@ struct lhsParseNode *, int,struct symbolHashNode *, struct lhsParseNode *, - int); + int,int); + static int TestCEAnalysis(void *,struct lhsParseNode *,struct lhsParseNode *,int,int *,struct nandFrame *); + static void ReleaseNandFrames(void *,struct nandFrame *); /******************************************************************/ /* VariableAnalysis: Propagates variables references to other */ @@ -105,8 +116,9 @@ globle int VariableAnalysis( void *theEnv, struct lhsParseNode *patternPtr) { - struct lhsParseNode *rv, *theList, *tempList; int errorFlag = FALSE; + struct nandFrame *theNandFrames = NULL, *tempNandPtr; + int currentDepth = 1; /*======================================================*/ /* Loop through all of the CEs in the rule to determine */ @@ -118,6 +130,21 @@ globle int VariableAnalysis( while (patternPtr != NULL) { + /*==================================*/ + /* If the nand depth is increasing, */ + /* create a new nand frame. */ + /*==================================*/ + + while (patternPtr->beginNandDepth > currentDepth) + { + tempNandPtr = get_struct(theEnv,nandFrame); + tempNandPtr->nandCE = patternPtr; + tempNandPtr->depth = currentDepth; + tempNandPtr->next = theNandFrames; + theNandFrames = tempNandPtr; + currentDepth++; + } + /*=========================================================*/ /* If a pattern CE is encountered, propagate any variables */ /* found in the pattern and note any illegal references to */ @@ -161,7 +188,27 @@ globle int VariableAnalysis( /* in the same semantic scope as the bound variable. */ /*====================================================*/ - if (GetVariables(theEnv,patternPtr)) return(TRUE); + if (GetVariables(theEnv,patternPtr,PATTERN_CE,theNandFrames)) + { + ReleaseNandFrames(theEnv,theNandFrames); + return(TRUE); + } + + /*==========================================================*/ + /* Analyze any test CE that's been attached to the pattern. */ + /*==========================================================*/ + + if (TestCEAnalysis(theEnv,patternPtr,patternPtr->expression,FALSE,&errorFlag,theNandFrames) == TRUE) + { + ReleaseNandFrames(theEnv,theNandFrames); + return TRUE; + } + + if (TestCEAnalysis(theEnv,patternPtr,patternPtr->secondaryExpression,TRUE,&errorFlag,theNandFrames) == TRUE) + { + ReleaseNandFrames(theEnv,theNandFrames); + return TRUE; + } } /*==============================================================*/ @@ -173,41 +220,24 @@ globle int VariableAnalysis( else if (patternPtr->type == TEST_CE) { - /*=====================================================*/ - /* Verify that all variables were referenced properly. */ - /*=====================================================*/ - - rv = CheckExpression(theEnv,patternPtr->expression,NULL,(int) patternPtr->whichCE,NULL,0); - - /*=========================================================*/ - /* Determine the type and value constraints implied by the */ - /* expression and propagate these constraints to other */ - /* variables in the LHS. For example, the expression */ - /* (+ ?x 1) implies that ?x is a number. */ - /*=========================================================*/ - - theList = GetExpressionVarConstraints(theEnv,patternPtr->expression); - for (tempList = theList; tempList != NULL; tempList = tempList->right) - { - if (PropagateVariableDriver(theEnv,patternPtr,patternPtr,NULL,SF_VARIABLE, - (SYMBOL_HN *) tempList->value,tempList,FALSE)) - { - ReturnLHSParseNodes(theEnv,theList); - return(TRUE); - } - } - ReturnLHSParseNodes(theEnv,theList); + if (TestCEAnalysis(theEnv,patternPtr,patternPtr->expression,FALSE,&errorFlag,theNandFrames) == TRUE) + { + ReleaseNandFrames(theEnv,theNandFrames); + return TRUE; + } + } - /*========================================================*/ - /* If the variables in the expression were all referenced */ - /* properly, then create the expression to use in the */ - /* join network. */ - /*========================================================*/ + /*==================================*/ + /* If the nand depth is decreasing, */ + /* release the nand frames. */ + /*==================================*/ - if (rv != NULL) - { errorFlag = TRUE; } - else - { patternPtr->networkTest = GetvarReplace(theEnv,patternPtr->expression); } + while (patternPtr->endNandDepth < currentDepth) + { + tempNandPtr = theNandFrames->next; + rtn_struct(theEnv,nandFrame,theNandFrames); + theNandFrames = tempNandPtr; + currentDepth--; } /*=====================================================*/ @@ -224,6 +254,99 @@ globle int VariableAnalysis( return(errorFlag); } +/******************************************************/ +/* ReleaseNandFrames: Releases a list of nand frames. */ +/******************************************************/ +static void ReleaseNandFrames( + void *theEnv, + struct nandFrame *theFrames) + { + struct nandFrame *tmpFrame; + + while (theFrames != NULL) + { + tmpFrame = theFrames->next; + rtn_struct(theEnv,nandFrame,theFrames); + theFrames = tmpFrame; + } + } + +/*******************************************************************/ +/* TestCEAnalysis: If a test CE is encountered, make sure that all */ +/* references to variables have been previously bound. If they */ +/* are bound then replace the references to variables with */ +/* function calls to retrieve the variables. */ +/*******************************************************************/ +static int TestCEAnalysis( + void *theEnv, + struct lhsParseNode *patternPtr, + struct lhsParseNode *theExpression, + int secondary, + int *errorFlag, + struct nandFrame *theNandFrames) + { + struct lhsParseNode *rv, *theList, *tempList, *tempRight; + + if (theExpression == NULL) return FALSE; + + /*=====================================================*/ + /* Verify that all variables were referenced properly. */ + /*=====================================================*/ + + rv = CheckExpression(theEnv,theExpression,NULL,(int) patternPtr->whichCE,NULL,0); + + /*====================================================================*/ + /* Temporarily disconnect the right nodes. If this is a pattern node */ + /* with an attached test CE, we only want to propagate to following */ + /* patterns, not to nodes of this pattern which preceded the test CE. */ + /*====================================================================*/ + + tempRight = patternPtr->right; + patternPtr->right = NULL; + + /*=========================================================*/ + /* Determine the type and value constraints implied by the */ + /* expression and propagate these constraints to other */ + /* variables in the LHS. For example, the expression */ + /* (+ ?x 1) implies that ?x is a number. */ + /*=========================================================*/ + + theList = GetExpressionVarConstraints(theEnv,theExpression); + for (tempList = theList; tempList != NULL; tempList = tempList->right) + { + if (PropagateVariableDriver(theEnv,patternPtr,patternPtr,NULL,SF_VARIABLE, + (SYMBOL_HN *) tempList->value,tempList,FALSE,TEST_CE)) + { + ReturnLHSParseNodes(theEnv,theList); + patternPtr->right = tempRight; + return(TRUE); + } + } + + ReturnLHSParseNodes(theEnv,theList); + + /*============================*/ + /* Reconnect the right nodes. */ + /*============================*/ + + patternPtr->right = tempRight; + + /*========================================================*/ + /* If the variables in the expression were all referenced */ + /* properly, then create the expression to use in the */ + /* join network. */ + /*========================================================*/ + + if (rv != NULL) + { *errorFlag = TRUE; } + else if (secondary) + { patternPtr->secondaryNetworkTest = CombineExpressions(theEnv,patternPtr->secondaryNetworkTest,GetvarReplace(theEnv,theExpression,FALSE,theNandFrames)); } + else + { patternPtr->networkTest = CombineExpressions(theEnv,patternPtr->networkTest,GetvarReplace(theEnv,theExpression,FALSE,theNandFrames)); } + + return FALSE; + } + /****************************************************************/ /* GetVariables: Loops through each field/slot within a pattern */ /* and propagates the pattern and field location of bound */ @@ -232,7 +355,9 @@ globle int VariableAnalysis( /****************************************************************/ static int GetVariables( void *theEnv, - struct lhsParseNode *thePattern) + struct lhsParseNode *thePattern, + int patternHeadType, + struct nandFrame *theNandFrames) { struct lhsParseNode *patternHead = thePattern; struct lhsParseNode *multifieldHeader = NULL; @@ -268,12 +393,12 @@ static int GetVariables( (thePattern->type == MF_VARIABLE) || ((thePattern->type == PATTERN_CE) && (thePattern->value != NULL))) { - if (ProcessVariable(theEnv,thePattern,multifieldHeader,patternHead)) + if (ProcessVariable(theEnv,thePattern,multifieldHeader,patternHead,patternHeadType,theNandFrames)) { return(TRUE); } } else { - if (ProcessField(theEnv,thePattern,multifieldHeader,patternHead)) + if (ProcessField(theEnv,thePattern,multifieldHeader,patternHead,patternHeadType,theNandFrames)) { return(TRUE); } } } @@ -310,7 +435,9 @@ static int ProcessVariable( void *theEnv, struct lhsParseNode *thePattern, struct lhsParseNode *multifieldHeader, - struct lhsParseNode *patternHead) + struct lhsParseNode *patternHead, + int patternHeadType, + struct nandFrame *theNandFrames) { int theType; struct symbolHashNode *theVariable; @@ -358,7 +485,7 @@ static int ProcessVariable( thePattern,patternHead->beginNandDepth, TRUE,FALSE); - if (ProcessField(theEnv,thePattern,multifieldHeader,patternHead)) + if (ProcessField(theEnv,thePattern,multifieldHeader,patternHead,patternHeadType,theNandFrames)) { return(TRUE); } } @@ -367,7 +494,7 @@ static int ProcessVariable( /*=================================================================*/ return(PropagateVariableDriver(theEnv,patternHead,thePattern,multifieldHeader,theType, - theVariable,thePattern,TRUE)); + theVariable,thePattern,TRUE,patternHeadType)); } /*******************************************/ @@ -382,7 +509,8 @@ static int PropagateVariableDriver( int theType, struct symbolHashNode *variableName, struct lhsParseNode *theReference, - int assignReference) + int assignReference, + int patternHeadType) { /*===================================================*/ /* Propagate the variable location to any additional */ @@ -411,6 +539,19 @@ static int PropagateVariableDriver( return(TRUE); } + /*==============================================*/ + /* Propagate the variable location to any test */ + /* CEs which have been attached to the pattern. */ + /*==============================================*/ + + if (PropagateVariableToNodes(theEnv,patternHead->expression,theType,variableName,theReference, + patternHead->beginNandDepth,assignReference,TRUE)) + { return(TRUE); } + + if (PropagateVariableToNodes(theEnv,patternHead->secondaryExpression,theType,variableName,theReference, + patternHead->beginNandDepth,assignReference,TRUE)) + { return(TRUE); } + /*======================================================*/ /* Propagate values to other patterns if the pattern in */ /* which the variable is found is not a "not" CE or the */ @@ -419,6 +560,7 @@ static int PropagateVariableDriver( if (((patternHead->type == PATTERN_CE) || (patternHead->type == TEST_CE)) && (patternHead->negated == FALSE) && + (patternHead->exists == FALSE) && (patternHead->beginNandDepth <= patternHead->endNandDepth)) { int ignoreVariableMixing; @@ -431,7 +573,7 @@ static int PropagateVariableDriver( /* sequence expansion is desired). */ /*============================================================*/ - if (patternHead->type == TEST_CE) ignoreVariableMixing = TRUE; + if (patternHeadType == TEST_CE) ignoreVariableMixing = TRUE; else ignoreVariableMixing = FALSE; /*==========================*/ @@ -463,7 +605,9 @@ static int ProcessField( void *theEnv, struct lhsParseNode *thePattern, struct lhsParseNode *multifieldHeader, - struct lhsParseNode *patternHead) + struct lhsParseNode *patternHead, + int patternHeadType, + struct nandFrame *theNandFrames) { struct lhsParseNode *theList, *tempList; @@ -487,7 +631,7 @@ static int ProcessField( for (tempList = theList; tempList != NULL; tempList = tempList->right) { if (PropagateVariableDriver(theEnv,patternHead,thePattern,multifieldHeader,tempList->type, - (SYMBOL_HN *) tempList->value,tempList,FALSE)) + (SYMBOL_HN *) tempList->value,tempList,FALSE,patternHeadType)) { ReturnLHSParseNodes(theEnv,theList); return(TRUE); @@ -517,7 +661,7 @@ static int ProcessField( /* that will be used in the pattern and join networks. */ /*==============================================================*/ - FieldConversion(theEnv,thePattern,patternHead); + FieldConversion(theEnv,thePattern,patternHead,theNandFrames); /*=========================================================*/ /* Return FALSE to indicate that no errors were generated. */ @@ -564,6 +708,12 @@ static int PropagateVariableToNodes( theReference,startDepth,assignReference,TRUE); } + if (theNode->secondaryExpression != NULL) + { + PropagateVariableToNodes(theEnv,theNode->secondaryExpression,theType,variableName, + theReference,startDepth,assignReference,TRUE); + } + /*======================================================*/ /* If the field/slot is a single or multifield variable */ /* with the same name as the propagated variable, */ @@ -600,7 +750,6 @@ static int PropagateVariableToNodes( theNode->derivedConstraints = TRUE; } - /*=====================================================*/ /* Don't propagate the variable if it originates from */ /* a different type of pattern object and the variable */ @@ -933,6 +1082,7 @@ static void VariableReferenceErrorMessage( if (theExpression != NULL) { + whichCE = theExpression->whichCE; temprv = LHSParseNodesToExpression(theEnv,theExpression); ReturnExpression(theEnv,temprv->nextArg); temprv->nextArg = NULL; diff --git a/src/analysis.h b/src/analysis.h index 1763097..6c614af 100644 --- a/src/analysis.h +++ b/src/analysis.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* ANALYSIS HEADER FILE */ /*******************************************************/ @@ -21,6 +21,8 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Join network rework and optimizations. */ +/* */ /*************************************************************/ #ifndef _H_analysis @@ -43,6 +45,18 @@ #define LOCALE extern #endif +/*****************************************************/ +/* nandFrame structure: Stores information about the */ +/* current position in the nesting of not/and CEs */ +/* as the patterns of a rule are analyzed. */ +/*****************************************************/ +struct nandFrame + { + int depth; + struct lhsParseNode *nandCE; + struct nandFrame *next; + }; + LOCALE intBool VariableAnalysis(void *,struct lhsParseNode *); #endif diff --git a/src/argacces.c b/src/argacces.c index cacea6f..716e135 100644 --- a/src/argacces.c +++ b/src/argacces.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* ARGUMENT ACCESS MODULE */ /*******************************************************/ @@ -15,7 +15,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -23,6 +23,15 @@ /* */ /* Added IllegalLogicalNameMessage function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Support for fact-address arguments. */ +/* */ /*************************************************************/ #define _ARGACCES_SOURCE_ @@ -42,6 +51,7 @@ #include "insfun.h" #include "factmngr.h" #include "prntutil.h" +#include "sysdep.h" #include "argacces.h" @@ -49,8 +59,8 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void NonexistantError(void *,char *,char *,int); - static void ExpectedTypeError3(void *,char *,char *,int,char *); + static void NonexistantError(void *,const char *,const char *,int); + static void ExpectedTypeError3(void *,const char *,const char *,int,const char *); /*******************************************************************/ /* EnvRtnLexeme: Access function to retrieve the nth argument from */ @@ -60,7 +70,7 @@ /* value of the argument is returned (i.e. the string "a" would */ /* be returned for a, "a", and [a]). */ /*******************************************************************/ -globle char *EnvRtnLexeme( +globle const char *EnvRtnLexeme( void *theEnv, int argumentPosition) { @@ -182,7 +192,7 @@ globle double EnvRtnDouble( /* value of the argument is returned (i.e. the integer 4 */ /* would be returned for 4.3 and 4). */ /*****************************************************************/ -globle long EnvRtnLong( +globle long long EnvRtnLong( void *theEnv, int argumentPosition) { @@ -292,7 +302,7 @@ globle int EnvRtnArgCount( return(count); } - + /************************************************************************/ /* EnvArgCountCheck: Given the expected number of arguments, determines */ /* if the function currently being evaluated has the correct number */ @@ -305,7 +315,7 @@ globle int EnvRtnArgCount( /************************************************************************/ globle int EnvArgCountCheck( void *theEnv, - char *functionName, + const char *functionName, int countRelation, int expectedNumber) { @@ -351,7 +361,7 @@ globle int EnvArgCountCheck( /****************************************************************/ globle int EnvArgRangeCheck( void *theEnv, - char *functionName, + const char *functionName, int min, int max) { @@ -385,7 +395,7 @@ globle int EnvArgRangeCheck( /*************************************************************/ globle int EnvArgTypeCheck( void *theEnv, - char *functionName, + const char *functionName, int argumentPosition, int expectedType, DATA_OBJECT_PTR returnValue) @@ -450,7 +460,7 @@ globle int EnvArgTypeCheck( if ((returnValue->type == FLOAT) && (expectedType == INTEGER)) { returnValue->type = INTEGER; - returnValue->value = (void *) EnvAddLong(theEnv,(long) ValueToDouble(returnValue->value)); + returnValue->value = (void *) EnvAddLong(theEnv,(long long) ValueToDouble(returnValue->value)); return(TRUE); } @@ -466,6 +476,7 @@ globle int EnvArgTypeCheck( else if (expectedType == MULTIFIELD) ExpectedTypeError1(theEnv,functionName,argumentPosition,"multifield"); else if (expectedType == INTEGER_OR_FLOAT) ExpectedTypeError1(theEnv,functionName,argumentPosition,"integer or float"); else if (expectedType == SYMBOL_OR_STRING) ExpectedTypeError1(theEnv,functionName,argumentPosition,"symbol or string"); + else if (expectedType == FACT_ADDRESS) ExpectedTypeError1(theEnv,functionName,argumentPosition,"fact address"); #if OBJECT_SYSTEM else if (expectedType == INSTANCE_NAME) ExpectedTypeError1(theEnv,functionName,argumentPosition,"instance name"); else if (expectedType == INSTANCE_ADDRESS) ExpectedTypeError1(theEnv,functionName,argumentPosition,"instance address"); @@ -489,7 +500,7 @@ globle int EnvArgTypeCheck( globle intBool GetNumericArgument( void *theEnv, struct expr *theArgument, - char *functionName, + const char *functionName, DATA_OBJECT *result, intBool convertToFloat, int whichArgument) @@ -528,7 +539,7 @@ globle intBool GetNumericArgument( SetHaltExecution(theEnv,TRUE); SetEvaluationError(theEnv,TRUE); result->type = INTEGER; - result->value = (void *) EnvAddLong(theEnv,0L); + result->value = (void *) EnvAddLong(theEnv,0LL); return(FALSE); } @@ -560,12 +571,12 @@ globle intBool GetNumericArgument( /* logical name. If valid, the logical name is returned, otherwise */ /* NULL is returned. */ /*********************************************************************/ -globle char *GetLogicalName( +globle const char *GetLogicalName( void *theEnv, int whichArgument, - char *defaultLogicalName) + const char *defaultLogicalName) { - char *logicalName; + const char *logicalName; DATA_OBJECT result; EnvRtnUnknown(theEnv,whichArgument,&result); @@ -598,9 +609,9 @@ globle char *GetLogicalName( /* if it is a valid file name. If valid, the file name is */ /* returned, otherwise NULL is returned. */ /************************************************************/ -globle char *GetFileName( +globle const char *GetFileName( void *theEnv, - char *functionName, + const char *functionName, int whichArgument) { DATA_OBJECT result; @@ -620,8 +631,8 @@ globle char *GetFileName( /******************************************************************/ globle void OpenErrorMessage( void *theEnv, - char *functionName, - char *fileName) + const char *functionName, + const char *fileName) { PrintErrorID(theEnv,"ARGACCES",2,FALSE); EnvPrintRouter(theEnv,WERROR,"Function "); @@ -640,7 +651,7 @@ globle void OpenErrorMessage( /************************************************************/ globle struct defmodule *GetModuleName( void *theEnv, - char *functionName, + const char *functionName, int whichArgument, int *error) { @@ -696,10 +707,10 @@ globle struct defmodule *GetModuleName( /* is used by functions such as ppdeftemplate, undefrule, */ /* etc... to retrieve the construct name on which to operate. */ /****************************************************************/ -globle char *GetConstructName( +globle const char *GetConstructName( void *theEnv, - char *functionName, - char *constructType) + const char *functionName, + const char *constructType) { DATA_OBJECT result; @@ -725,8 +736,8 @@ globle char *GetConstructName( /**************************************************************************/ static void NonexistantError( void *theEnv, - char *accessFunction, - char *functionName, + const char *accessFunction, + const char *functionName, int argumentPosition) { PrintErrorID(theEnv,"ARGACCES",3,FALSE); @@ -745,7 +756,7 @@ static void NonexistantError( /*********************************************************/ globle void ExpectedCountError( void *theEnv, - char *functionName, + const char *functionName, int countRelation, int expectedNumber) { @@ -782,8 +793,8 @@ globle void ExpectedCountError( /*************************************************************/ globle intBool CheckFunctionArgCount( void *theEnv, - char *functionName, - char *restrictions, + const char *functionName, + const char *restrictions, int argumentCount) { register int minArguments, maxArguments; @@ -880,9 +891,9 @@ globle intBool CheckFunctionArgCount( /*******************************************************************/ globle void ExpectedTypeError1( void *theEnv, - char *functionName, + const char *functionName, int whichArg, - char *expectedType) + const char *expectedType) { PrintErrorID(theEnv,"ARGACCES",5,FALSE); EnvPrintRouter(theEnv,WERROR,"Function "); @@ -902,11 +913,11 @@ globle void ExpectedTypeError1( /**************************************************************/ globle void ExpectedTypeError2( void *theEnv, - char *functionName, + const char *functionName, int whichArg) { struct FunctionDefinition *theFunction; - char *theType; + const char *theType; theFunction = FindFunction(theEnv,functionName); @@ -925,10 +936,10 @@ globle void ExpectedTypeError2( /*******************************************************************/ static void ExpectedTypeError3( void *theEnv, - char *accessFunction, - char *functionName, + const char *accessFunction, + const char *functionName, int argumentPosition, - char *type) + const char *type) { PrintErrorID(theEnv,"ARGACCES",6,FALSE); EnvPrintRouter(theEnv,WERROR,"Function "); @@ -950,7 +961,7 @@ void *GetFactOrInstanceArgument( void *theEnv, int thePosition, DATA_OBJECT *item, - char *functionName) + const char *functionName) { #if DEFTEMPLATE_CONSTRUCT || OBJECT_SYSTEM void *ptr; @@ -981,7 +992,7 @@ void *GetFactOrInstanceArgument( if ((ptr = (void *) FindIndexedFact(theEnv,DOPToLong(item))) == NULL) { char tempBuffer[20]; - sprintf(tempBuffer,"f-%ld",DOPToLong(item)); + gensprintf(tempBuffer,"f-%lld",DOPToLong(item)); CantFindItemErrorMessage(theEnv,"fact",tempBuffer); } return(ptr); @@ -1018,10 +1029,74 @@ void *GetFactOrInstanceArgument( /****************************************************/ void IllegalLogicalNameMessage( void *theEnv, - char *theFunction) + const char *theFunction) { PrintErrorID(theEnv,"IOFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Illegal logical name used for "); EnvPrintRouter(theEnv,WERROR,theFunction); EnvPrintRouter(theEnv,WERROR," function.\n"); } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle int ArgCountCheck( + const char *functionName, + int countRelation, + int expectedNumber) + { + return EnvArgCountCheck(GetCurrentEnvironment(),functionName,countRelation,expectedNumber); + } + +globle int ArgRangeCheck( + const char *functionName, + int min, + int max) + { + return EnvArgRangeCheck(GetCurrentEnvironment(),functionName,min,max); + } + +globle int ArgTypeCheck( + const char *functionName, + int argumentPosition, + int expectedType, + DATA_OBJECT_PTR returnValue) + { + return EnvArgTypeCheck(GetCurrentEnvironment(),functionName,argumentPosition,expectedType,returnValue); + } + +globle int RtnArgCount() + { + return EnvRtnArgCount(GetCurrentEnvironment()); + } + +globle double RtnDouble( + int argumentPosition) + { + return EnvRtnDouble(GetCurrentEnvironment(),argumentPosition); + } + +globle const char *RtnLexeme( + int argumentPosition) + { + return EnvRtnLexeme(GetCurrentEnvironment(),argumentPosition); + } + +globle long long RtnLong( + int argumentPosition) + { + return EnvRtnLong(GetCurrentEnvironment(),argumentPosition); + } + +globle DATA_OBJECT_PTR RtnUnknown( + int argumentPosition, + DATA_OBJECT_PTR returnValue) + { + return EnvRtnUnknown(GetCurrentEnvironment(),argumentPosition,returnValue); + } + +#endif + diff --git a/src/argacces.h b/src/argacces.h index 1b12e46..632bd40 100644 --- a/src/argacces.h +++ b/src/argacces.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* ARGUMENT ACCESS HEADER FILE */ /*******************************************************/ @@ -15,7 +15,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -23,6 +23,13 @@ /* */ /* Added IllegalLogicalNameMessage function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_argacces @@ -49,47 +56,39 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define RtnArgCount(theEnv) EnvRtnArgCount(theEnv) -#define ArgCountCheck(theEnv,a,b,c) EnvArgCountCheck(theEnv,a,b,c) -#define ArgRangeCheck(theEnv,a,b,c) EnvArgRangeCheck(theEnv,a,b,c) -#define RtnLexeme(theEnv,a) EnvRtnLexeme(theEnv,a) -#define RtnDouble(theEnv,a) EnvRtnDouble(theEnv,a) -#define RtnLong(theEnv,a) EnvRtnLong(theEnv,a) -#define RtnUnknown(theEnv,a,b) EnvRtnUnknown(theEnv,a,b) -#define ArgTypeCheck(theEnv,a,b,c,d) EnvArgTypeCheck(theEnv,a,b,c,d) -#else -#define RtnArgCount() EnvRtnArgCount(GetCurrentEnvironment()) -#define ArgCountCheck(a,b,c) EnvArgCountCheck(GetCurrentEnvironment(),a,b,c) -#define ArgRangeCheck(a,b,c) EnvArgRangeCheck(GetCurrentEnvironment(),a,b,c) -#define RtnLexeme(a) EnvRtnLexeme(GetCurrentEnvironment(),a) -#define RtnDouble(a) EnvRtnDouble(GetCurrentEnvironment(),a) -#define RtnLong(a) EnvRtnLong(GetCurrentEnvironment(),a) -#define RtnUnknown(a,b) EnvRtnUnknown(GetCurrentEnvironment(),a,b) -#define ArgTypeCheck(a,b,c,d) EnvArgTypeCheck(GetCurrentEnvironment(),a,b,c,d) -#endif - LOCALE int EnvRtnArgCount(void *); - LOCALE int EnvArgCountCheck(void *,char *,int,int); - LOCALE int EnvArgRangeCheck(void *,char *,int,int); - LOCALE char *EnvRtnLexeme(void *,int); + LOCALE int EnvArgCountCheck(void *,const char *,int,int); + LOCALE int EnvArgRangeCheck(void *,const char *,int,int); + LOCALE const char *EnvRtnLexeme(void *,int); LOCALE double EnvRtnDouble(void *,int); - LOCALE long EnvRtnLong(void *,int); + LOCALE long long EnvRtnLong(void *,int); LOCALE struct dataObject *EnvRtnUnknown(void *,int,struct dataObject *); - LOCALE int EnvArgTypeCheck(void *,char *,int,int,struct dataObject *); - LOCALE intBool GetNumericArgument(void *,struct expr *,char *,struct dataObject *,int,int); - LOCALE char *GetLogicalName(void *,int,char *); - LOCALE char *GetFileName(void *,char *,int); - LOCALE char *GetConstructName(void *,char *,char *); - LOCALE void ExpectedCountError(void *,char *,int,int); - LOCALE void OpenErrorMessage(void *,char *,char *); - LOCALE intBool CheckFunctionArgCount(void *,char *,char *,int); - LOCALE void ExpectedReturnTypeError(char *,char *); - LOCALE void ExpectedTypeError1(void *,char *,int,char *); - LOCALE void ExpectedTypeError2(void *,char *,int); - LOCALE struct defmodule *GetModuleName(void *,char *,int,int *); - LOCALE void *GetFactOrInstanceArgument(void *,int,DATA_OBJECT *,char *); - LOCALE void IllegalLogicalNameMessage(void *,char *); + LOCALE int EnvArgTypeCheck(void *,const char *,int,int,struct dataObject *); + LOCALE intBool GetNumericArgument(void *,struct expr *,const char *,struct dataObject *,int,int); + LOCALE const char *GetLogicalName(void *,int,const char *); + LOCALE const char *GetFileName(void *,const char *,int); + LOCALE const char *GetConstructName(void *,const char *,const char *); + LOCALE void ExpectedCountError(void *,const char *,int,int); + LOCALE void OpenErrorMessage(void *,const char *,const char *); + LOCALE intBool CheckFunctionArgCount(void *,const char *,const char *,int); + LOCALE void ExpectedTypeError1(void *,const char *,int,const char *); + LOCALE void ExpectedTypeError2(void *,const char *,int); + LOCALE struct defmodule *GetModuleName(void *,const char *,int,int *); + LOCALE void *GetFactOrInstanceArgument(void *,int,DATA_OBJECT *,const char *); + LOCALE void IllegalLogicalNameMessage(void *,const char *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE int ArgCountCheck(const char *,int,int); + LOCALE int ArgRangeCheck(const char *,int,int); + LOCALE int ArgTypeCheck(const char *,int,int,DATA_OBJECT_PTR); + LOCALE int RtnArgCount(void); + LOCALE double RtnDouble(int); + LOCALE const char *RtnLexeme(int); + LOCALE long long RtnLong(int); + LOCALE DATA_OBJECT_PTR RtnUnknown(int,DATA_OBJECT_PTR); + +#endif #endif diff --git a/src/bload.c b/src/bload.c index 9d2875e..322d2a0 100644 --- a/src/bload.c +++ b/src/bload.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* BLOAD MODULE */ /*******************************************************/ @@ -12,7 +12,7 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -20,6 +20,16 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _BLOAD_SOURCE_ @@ -45,10 +55,10 @@ /***************************************/ static struct FunctionDefinition **ReadNeededFunctions(void *,long *,int *); - static struct FunctionDefinition *FastFindFunction(void *,char *,struct FunctionDefinition *); + static struct FunctionDefinition *FastFindFunction(void *,const char *,struct FunctionDefinition *); static int ClearBload(void *); static void AbortBload(void *); - static int BloadOutOfMemoryFunction(void *,unsigned long); + static int BloadOutOfMemoryFunction(void *,size_t); static void DeallocateBloadData(void *); /**********************************************/ @@ -60,18 +70,19 @@ globle void InitializeBloadData( { AllocateEnvironmentData(theEnv,BLOAD_DATA,sizeof(struct bloadData),NULL); AddEnvironmentCleanupFunction(theEnv,"bload",DeallocateBloadData,-1500); + EnvAddClearFunction(theEnv,"bload",(void (*)(void *)) ClearBload,10000); BloadData(theEnv)->BinaryPrefixID = "\1\2\3\4CLIPS"; - BloadData(theEnv)->BinaryVersionID = "V6.20"; + BloadData(theEnv)->BinaryVersionID = "V6.30"; } - + /************************************************/ /* DeallocateBloadData: Deallocates environment */ /* data for the bload command. */ /************************************************/ static void DeallocateBloadData( void *theEnv) - { + { DeallocateCallList(theEnv,BloadData(theEnv)->BeforeBloadFunctions); DeallocateCallList(theEnv,BloadData(theEnv)->AfterBloadFunctions); DeallocateCallList(theEnv,BloadData(theEnv)->ClearBloadReadyFunctions); @@ -84,12 +95,12 @@ static void DeallocateBloadData( /******************************/ globle int EnvBload( void *theEnv, - char *fileName) + const char *fileName) { long numberOfFunctions; unsigned long space; int error; - char IDbuffer[20]; + char IDbuffer[20]; char constructBuffer[CONSTRUCT_HEADER_SIZE]; struct BinaryItem *biPtr; struct callFunctionItem *bfPtr; @@ -130,7 +141,7 @@ globle int EnvBload( GenCloseBinary(theEnv); return(FALSE); } - + /*====================*/ /* Clear environment. */ /*====================*/ @@ -164,15 +175,17 @@ globle int EnvBload( /* executed before a bload occurs. */ /*==================================*/ + ConstructData(theEnv)->ClearInProgress = TRUE; for (bfPtr = BloadData(theEnv)->BeforeBloadFunctions; bfPtr != NULL; bfPtr = bfPtr->next) - { + { if (bfPtr->environmentAware) { (*bfPtr->func)(theEnv); } - else + else { (* (void (*)(void)) bfPtr->func)(); } } + ConstructData(theEnv)->ClearInProgress = FALSE; /*====================================================*/ /* Read in the functions needed by this binary image. */ @@ -246,7 +259,7 @@ globle int EnvBload( { EnvPrintRouter(theEnv,WDIALOG,"\nSkipping "); EnvPrintRouter(theEnv,WDIALOG,constructBuffer); - EnvPrintRouter(theEnv,WDIALOG," constructs because of unavailibility\n"); + EnvPrintRouter(theEnv,WDIALOG," constructs because of unavailability\n"); } } } @@ -320,8 +333,8 @@ globle int EnvBload( if (BloadData(theEnv)->FunctionArray != NULL) { - genlongfree(theEnv,(void *) BloadData(theEnv)->FunctionArray, - (unsigned long) sizeof(struct FunctionDefinition *) * numberOfFunctions); + genfree(theEnv,(void *) BloadData(theEnv)->FunctionArray, + sizeof(struct FunctionDefinition *) * numberOfFunctions); } FreeAtomicValueStorage(theEnv); @@ -333,10 +346,10 @@ globle int EnvBload( for (bfPtr = BloadData(theEnv)->AfterBloadFunctions; bfPtr != NULL; bfPtr = bfPtr->next) - { + { if (bfPtr->environmentAware) { (*bfPtr->func)(theEnv); } - else + else { (* (void (*)(void)) bfPtr->func)(); } } @@ -346,7 +359,6 @@ globle int EnvBload( /*=======================================*/ BloadData(theEnv)->BloadActive = TRUE; - EnvAddClearFunction(theEnv,"bload",(void (*)(void *)) ClearBload,10000); /*=============================*/ /* Return TRUE to indicate the */ @@ -375,14 +387,14 @@ globle int EnvBload( globle void BloadandRefresh( void *theEnv, long objcnt, - unsigned objsz, + size_t objsz, void (*objupdate)(void *,void *,long)) { register long i,bi; char *buf; long objsmaxread,objsread; - unsigned long space; - int (*oldOutOfMemoryFunction)(void *,unsigned long); + size_t space; + int (*oldOutOfMemoryFunction)(void *,size_t); if (objcnt == 0L) return; @@ -391,7 +403,7 @@ globle void BloadandRefresh( do { space = objsmaxread * objsz; - buf = (char *) genlongalloc(theEnv,space); + buf = (char *) genalloc(theEnv,space); if (buf == NULL) { if ((objsmaxread / 2) == 0) @@ -419,7 +431,7 @@ globle void BloadandRefresh( (*objupdate)(theEnv,buf + objsz * bi,i); } while (i < objcnt); - genlongfree(theEnv,(void *) buf,space); + genfree(theEnv,(void *) buf,space); } /**********************************************/ @@ -432,7 +444,8 @@ static struct FunctionDefinition **ReadNeededFunctions( int *error) { char *functionNames, *namePtr; - unsigned long int space,temp; + unsigned long int space; + size_t temp; long i; struct FunctionDefinition **newFunctionArray, *functionPtr; int functionsNotFound = 0; @@ -454,7 +467,7 @@ static struct FunctionDefinition **ReadNeededFunctions( /* Allocate area for strings to be read. */ /*=======================================*/ - functionNames = (char *) genlongalloc(theEnv,space); + functionNames = (char *) genalloc(theEnv,space); GenReadBinary(theEnv,(void *) functionNames,space); /*====================================================*/ @@ -462,7 +475,7 @@ static struct FunctionDefinition **ReadNeededFunctions( /*====================================================*/ temp = (unsigned long) sizeof(struct FunctionDefinition *) * *numberOfFunctions; - newFunctionArray = (struct FunctionDefinition **) genlongalloc(theEnv,temp); + newFunctionArray = (struct FunctionDefinition **) genalloc(theEnv,temp); namePtr = functionNames; functionPtr = NULL; for (i = 0; i < *numberOfFunctions; i++) @@ -490,7 +503,7 @@ static struct FunctionDefinition **ReadNeededFunctions( /* Free the memory used by the name buffer. */ /*==========================================*/ - genlongfree(theEnv,(void *) functionNames,space); + genfree(theEnv,(void *) functionNames,space); /*==================================================*/ /* If any of the required functions were not found, */ @@ -499,7 +512,7 @@ static struct FunctionDefinition **ReadNeededFunctions( if (functionsNotFound) { - genlongfree(theEnv,(void *) newFunctionArray,temp); + genfree(theEnv,(void *) newFunctionArray,temp); newFunctionArray = NULL; } @@ -518,7 +531,7 @@ static struct FunctionDefinition **ReadNeededFunctions( /*****************************************/ static struct FunctionDefinition *FastFindFunction( void *theEnv, - char *functionName, + const char *functionName, struct FunctionDefinition *lastFunction) { struct FunctionDefinition *theList, *theFunction; @@ -582,6 +595,14 @@ static int ClearBload( struct callFunctionItem *bfPtr; int ready,error; + /*======================================*/ + /* If bload is not active, then there's */ + /* no need to clear bload data. */ + /*======================================*/ + + if (! BloadData(theEnv)->BloadActive) + { return TRUE; } + /*=================================================*/ /* Make sure it's safe to clear the bloaded image. */ /*=================================================*/ @@ -593,7 +614,7 @@ static int ClearBload( { if (bfPtr->environmentAware) { ready = (* ((int (*)(void *)) bfPtr->func))(theEnv); } - else + else { ready = (* ((int (*)(void)) bfPtr->func))(); } if (ready == FALSE) @@ -649,7 +670,6 @@ static int ClearBload( /*==================================*/ BloadData(theEnv)->BloadActive = FALSE; - EnvRemoveClearFunction(theEnv,"bload"); /*====================================*/ /* Return TRUE to indicate the binary */ @@ -671,10 +691,10 @@ static void AbortBload( for (bfPtr = BloadData(theEnv)->AbortBloadFunctions; bfPtr != NULL; bfPtr = bfPtr->next) - { + { if (bfPtr->environmentAware) { (*bfPtr->func)(theEnv); } - else + else { (* (void (*)(void)) bfPtr->func)(); } } } @@ -686,7 +706,7 @@ static void AbortBload( /********************************************/ globle void AddBeforeBloadFunction( void *theEnv, - char *name, + const char *name, void (*func)(void *), int priority) { @@ -701,7 +721,7 @@ globle void AddBeforeBloadFunction( /*******************************************/ globle void AddAfterBloadFunction( void *theEnv, - char *name, + const char *name, void (*func)(void *), int priority) { @@ -716,7 +736,7 @@ globle void AddAfterBloadFunction( /**************************************************/ globle void AddClearBloadReadyFunction( void *theEnv, - char *name, + const char *name, int (*func)(void *), int priority) { @@ -733,7 +753,7 @@ globle void AddClearBloadReadyFunction( /*********************************************/ globle void AddAbortBloadFunction( void *theEnv, - char *name, + const char *name, void (*func)(void *), int priority) { @@ -752,14 +772,11 @@ globle void AddAbortBloadFunction( SIDE EFFECTS : None NOTES : None *******************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int BloadOutOfMemoryFunction( void *theEnv, - unsigned long size) + size_t size) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(size,theEnv) #endif return(TRUE); @@ -772,7 +789,7 @@ static int BloadOutOfMemoryFunction( /*****************************************************/ globle void CannotLoadWithBloadMessage( void *theEnv, - char *constructName) + const char *constructName) { PrintErrorID(theEnv,"BLOAD",1,TRUE); EnvPrintRouter(theEnv,WERROR,"Cannot load "); @@ -780,6 +797,20 @@ globle void CannotLoadWithBloadMessage( EnvPrintRouter(theEnv,WERROR," construct with binary load in effect.\n"); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle int Bload( + const char *fileName) + { + return EnvBload(GetCurrentEnvironment(),fileName); + } + +#endif + #endif /* (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) */ /**************************************/ @@ -790,13 +821,13 @@ globle int BloadCommand( void *theEnv) { #if (! RUN_TIME) && (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) - char *fileName; + const char *fileName; if (EnvArgCountCheck(theEnv,"bload",EXACTLY,1) == -1) return(FALSE); fileName = GetFileName(theEnv,"bload",1); if (fileName != NULL) return(EnvBload(theEnv,fileName)); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif diff --git a/src/bload.h b/src/bload.h index 1b73c30..1fcef4f 100644 --- a/src/bload.h +++ b/src/bload.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* BLOAD HEADER FILE */ /*******************************************************/ @@ -11,7 +11,7 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,16 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_bload @@ -46,9 +56,9 @@ #define BLOAD_DATA 38 struct bloadData - { - char *BinaryPrefixID; - char *BinaryVersionID; + { + const char *BinaryPrefixID; + const char *BinaryVersionID; struct FunctionDefinition **FunctionArray; int BloadActive; struct callFunctionItem *BeforeBloadFunctions; @@ -70,23 +80,20 @@ struct bloadData #define FunctionPointer(i) ((struct FunctionDefinition *) (((i) == -1L) ? NULL : BloadData(theEnv)->FunctionArray[i])) -#if ENVIRONMENT_API_ONLY -#define Bload(theEnv,a) EnvBload(theEnv,a) -#else -#define Bload(a) EnvBload(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeBloadData(void *); LOCALE int BloadCommand(void *); - LOCALE intBool EnvBload(void *,char *); - LOCALE void BloadandRefresh(void *,long,unsigned,void (*)(void *,void *,long)); + LOCALE intBool EnvBload(void *,const char *); + LOCALE void BloadandRefresh(void *,long,size_t,void (*)(void *,void *,long)); LOCALE intBool Bloaded(void *); - LOCALE void AddBeforeBloadFunction(void *,char *,void (*)(void *),int); - LOCALE void AddAfterBloadFunction(void *,char *,void (*)(void *),int); - LOCALE void AddBloadReadyFunction(void *,char *,int (*)(void),int); - LOCALE void AddClearBloadReadyFunction(void *,char *,int (*)(void *),int); - LOCALE void AddAbortBloadFunction(void *,char *,void (*)(void *),int); - LOCALE void CannotLoadWithBloadMessage(void *,char *); + LOCALE void AddBeforeBloadFunction(void *,const char *,void (*)(void *),int); + LOCALE void AddAfterBloadFunction(void *,const char *,void (*)(void *),int); + LOCALE void AddClearBloadReadyFunction(void *,const char *,int (*)(void *),int); + LOCALE void AddAbortBloadFunction(void *,const char *,void (*)(void *),int); + LOCALE void CannotLoadWithBloadMessage(void *,const char *); + +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE int Bload(const char *); +#endif #endif diff --git a/src/bmathfun.c b/src/bmathfun.c index a5da6d0..bc96069 100644 --- a/src/bmathfun.c +++ b/src/bmathfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* BASIC MATH FUNCTIONS MODULE */ /*******************************************************/ @@ -22,6 +22,10 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _BMATHFUN_SOURCE_ @@ -41,7 +45,7 @@ #define BMATHFUN_DATA 6 struct basicMathFunctionData - { + { intBool AutoFloatDividend; }; @@ -52,24 +56,24 @@ struct basicMathFunctionData /***************************************************************/ globle void BasicMathFunctionDefinitions( void *theEnv) - { + { AllocateEnvironmentData(theEnv,BMATHFUN_DATA,sizeof(struct basicMathFunctionData),NULL); - + BasicMathFunctionData(theEnv)->AutoFloatDividend = TRUE; #if ! RUN_TIME EnvDefineFunction2(theEnv,"+", 'n',PTIEF AdditionFunction, "AdditionFunction", "2*n"); EnvDefineFunction2(theEnv,"*", 'n', PTIEF MultiplicationFunction, "MultiplicationFunction", "2*n"); EnvDefineFunction2(theEnv,"-", 'n', PTIEF SubtractionFunction, "SubtractionFunction", "2*n"); - + EnvDefineFunction2(theEnv,"/", 'n', PTIEF DivisionFunction, "DivisionFunction", "2*n"); - EnvDefineFunction2(theEnv,"div", 'l', PTIEF DivFunction, "DivFunction", "2*n"); + EnvDefineFunction2(theEnv,"div", 'g', PTIEF DivFunction, "DivFunction", "2*n"); EnvDefineFunction2(theEnv,"set-auto-float-dividend", 'b', SetAutoFloatDividendCommand, "SetAutoFloatDividendCommand", "11"); EnvDefineFunction2(theEnv,"get-auto-float-dividend", 'b', GetAutoFloatDividendCommand, "GetAutoFloatDividendCommand", "00"); - EnvDefineFunction2(theEnv,"integer", 'l', PTIEF IntegerFunction, "IntegerFunction", "11n"); + EnvDefineFunction2(theEnv,"integer", 'g', PTIEF IntegerFunction, "IntegerFunction", "11n"); EnvDefineFunction2(theEnv,"float", 'd', PTIEF FloatFunction, "FloatFunction", "11n"); EnvDefineFunction2(theEnv,"abs", 'n', PTIEF AbsFunction, "AbsFunction", "11n"); EnvDefineFunction2(theEnv,"min", 'n', PTIEF MinFunction, "MinFunction", "2*n"); @@ -86,7 +90,7 @@ globle void AdditionFunction( DATA_OBJECT_PTR returnValue) { double ftotal = 0.0; - long ltotal = 0L; + long long ltotal = 0LL; intBool useFloatTotal = FALSE; EXPRESSION *theExpression; DATA_OBJECT theArgument; @@ -148,7 +152,7 @@ globle void MultiplicationFunction( DATA_OBJECT_PTR returnValue) { double ftotal = 1.0; - long ltotal = 1L; + long long ltotal = 1LL; intBool useFloatTotal = FALSE; EXPRESSION *theExpression; DATA_OBJECT theArgument; @@ -209,7 +213,7 @@ globle void SubtractionFunction( DATA_OBJECT_PTR returnValue) { double ftotal = 0.0; - long ltotal = 0L; + long long ltotal = 0LL; intBool useFloatTotal = FALSE; EXPRESSION *theExpression; DATA_OBJECT theArgument; @@ -290,14 +294,14 @@ globle void DivisionFunction( DATA_OBJECT_PTR returnValue) { double ftotal = 1.0; - long ltotal = 1L; + long long ltotal = 1LL; intBool useFloatTotal; EXPRESSION *theExpression; DATA_OBJECT theArgument; int pos = 1; useFloatTotal = BasicMathFunctionData(theEnv)->AutoFloatDividend; - + /*===================================================*/ /* Get the first argument. This number which will be */ /* the starting product from which all subsequent */ @@ -382,14 +386,14 @@ globle void DivisionFunction( /* DivFunction: H/L access routine */ /* for the div function. */ /*************************************/ -globle long DivFunction( +globle long long DivFunction( void *theEnv) { - long total = 1L; + long long total = 1LL; EXPRESSION *theExpression; DATA_OBJECT theArgument; int pos = 1; - long theNumber; + long long theNumber; /*===================================================*/ /* Get the first argument. This number which will be */ @@ -406,7 +410,7 @@ globle long DivFunction( if (theArgument.type == INTEGER) { total = ValueToLong(theArgument.value); } else - { total = (long) ValueToDouble(theArgument.value); } + { total = (long long) ValueToDouble(theArgument.value); } pos++; } @@ -423,10 +427,10 @@ globle long DivFunction( else theExpression = GetNextArgument(theExpression); if (theArgument.type == INTEGER) theNumber = ValueToLong(theArgument.value); - else if (theArgument.type == FLOAT) theNumber = (long) ValueToDouble(theArgument.value); + else if (theArgument.type == FLOAT) theNumber = (long long) ValueToDouble(theArgument.value); else theNumber = 1; - if (theNumber == 0L) + if (theNumber == 0LL) { DivideByZeroErrorMessage(theEnv,"div"); SetHaltExecution(theEnv,TRUE); @@ -437,7 +441,7 @@ globle long DivFunction( if (theArgument.type == INTEGER) { total /= ValueToLong(theArgument.value); } else - { total = total / (long) ValueToDouble(theArgument.value); } + { total = total / (long long) ValueToDouble(theArgument.value); } pos++; } @@ -539,7 +543,7 @@ globle intBool EnvSetAutoFloatDividend( /* IntegerFunction: H/L access routine */ /* for the integer function. */ /*****************************************/ -globle long int IntegerFunction( +globle long long IntegerFunction( void *theEnv) { DATA_OBJECT valstruct; @@ -548,7 +552,7 @@ globle long int IntegerFunction( /* Check for the correct number of arguments. */ /*============================================*/ - if (EnvArgCountCheck(theEnv,"integer",EXACTLY,1) == -1) return(0L); + if (EnvArgCountCheck(theEnv,"integer",EXACTLY,1) == -1) return(0LL); /*================================================================*/ /* Check for the correct type of argument. Note that ArgTypeCheck */ @@ -556,7 +560,7 @@ globle long int IntegerFunction( /* (which is the purpose of the integer function). */ /*================================================================*/ - if (EnvArgTypeCheck(theEnv,"integer",1,INTEGER,&valstruct) == FALSE) return(0L); + if (EnvArgTypeCheck(theEnv,"integer",1,INTEGER,&valstruct) == FALSE) return(0LL); /*===================================================*/ /* Return the numeric value converted to an integer. */ @@ -816,3 +820,17 @@ globle void MaxFunction( return; } +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool GetAutoFloatDividend() + { + return EnvGetAutoFloatDividend(GetCurrentEnvironment()); + } + +globle intBool SetAutoFloatDividend( + int value) + { + return EnvSetAutoFloatDividend(GetCurrentEnvironment(),value); + } + +#endif diff --git a/src/bmathfun.h b/src/bmathfun.h index 1323566..6fdbfe9 100644 --- a/src/bmathfun.h +++ b/src/bmathfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* BASIC MATH FUNCTIONS MODULE */ /*******************************************************/ @@ -18,6 +18,10 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_bmathfun @@ -38,30 +42,29 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetAutoFloatDividend(theEnv) EnvGetAutoFloatDividend(theEnv) -#define SetAutoFloatDividend(theEnv,a) EnvSetAutoFloatDividend(theEnv,a) -#else -#define GetAutoFloatDividend() EnvGetAutoFloatDividend(GetCurrentEnvironment()) -#define SetAutoFloatDividend(a) EnvSetAutoFloatDividend(GetCurrentEnvironment(),a) -#endif - LOCALE void BasicMathFunctionDefinitions(void *); LOCALE void AdditionFunction(void *,DATA_OBJECT_PTR); LOCALE void MultiplicationFunction(void *,DATA_OBJECT_PTR); LOCALE void SubtractionFunction(void *,DATA_OBJECT_PTR); LOCALE void DivisionFunction(void *,DATA_OBJECT_PTR); - LOCALE long DivFunction(void *); + LOCALE long long DivFunction(void *); LOCALE intBool SetAutoFloatDividendCommand(void *); LOCALE intBool GetAutoFloatDividendCommand(void *); LOCALE intBool EnvGetAutoFloatDividend(void *); LOCALE intBool EnvSetAutoFloatDividend(void *,int); - LOCALE long int IntegerFunction(void *); + LOCALE long long IntegerFunction(void *); LOCALE double FloatFunction(void *); LOCALE void AbsFunction(void *,DATA_OBJECT_PTR); LOCALE void MinFunction(void *,DATA_OBJECT_PTR); LOCALE void MaxFunction(void *,DATA_OBJECT_PTR); +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool GetAutoFloatDividend(void); + LOCALE intBool SetAutoFloatDividend(int); + +#endif + #endif diff --git a/src/bsave.c b/src/bsave.c index 8bd1dad..801199c 100644 --- a/src/bsave.c +++ b/src/bsave.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* BSAVE MODULE */ /*******************************************************/ @@ -12,7 +12,7 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -23,6 +23,18 @@ /* Added environment parameter to GenClose. */ /* Added environment parameter to GenOpen. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used genstrncpy instead of strncpy. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _BSAVE_SOURCE_ @@ -49,7 +61,7 @@ static void FindNeededItems(void *); static void InitializeFunctionNeededFlags(void *); static void WriteNeededFunctions(void *,FILE *); - static unsigned long int FunctionBinarySize(void *); + static size_t FunctionBinarySize(void *); static void WriteBinaryHeader(void *,FILE *); static void WriteBinaryFooter(void *,FILE *); #endif @@ -64,7 +76,7 @@ globle void InitializeBsaveData( { AllocateEnvironmentData(theEnv,BSAVE_DATA,sizeof(struct bsaveData),DeallocateBsaveData); } - + /************************************************/ /* DeallocateBsaveData: Deallocates environment */ /* data for the bsave command. */ @@ -73,7 +85,7 @@ static void DeallocateBsaveData( void *theEnv) { struct BinaryItem *tmpPtr, *nextPtr; - + tmpPtr = BsaveData(theEnv)->ListOfBinaryItems; while (tmpPtr != NULL) { @@ -91,14 +103,14 @@ globle int BsaveCommand( void *theEnv) { #if (! RUN_TIME) && BLOAD_AND_BSAVE - char *fileName; + const char *fileName; if (EnvArgCountCheck(theEnv,"bsave",EXACTLY,1) == -1) return(FALSE); fileName = GetFileName(theEnv,"bsave",1); if (fileName != NULL) { if (EnvBsave(theEnv,fileName)) return(TRUE); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -113,7 +125,7 @@ globle int BsaveCommand( /******************************/ globle intBool EnvBsave( void *theEnv, - char *fileName) + const char *fileName) { FILE *fp; struct BinaryItem *biPtr; @@ -193,7 +205,7 @@ globle intBool EnvBsave( { if (biPtr->bsaveStorageFunction != NULL) { - strncpy(constructBuffer,biPtr->name,CONSTRUCT_HEADER_SIZE); + genstrncpy(constructBuffer,biPtr->name,CONSTRUCT_HEADER_SIZE); GenWrite(constructBuffer,(unsigned long) CONSTRUCT_HEADER_SIZE,fp); (*biPtr->bsaveStorageFunction)(theEnv,fp); } @@ -231,7 +243,7 @@ globle intBool EnvBsave( { if (biPtr->bsaveFunction != NULL) { - strncpy(constructBuffer,biPtr->name,CONSTRUCT_HEADER_SIZE); + genstrncpy(constructBuffer,biPtr->name,CONSTRUCT_HEADER_SIZE); GenWrite(constructBuffer,(unsigned long) CONSTRUCT_HEADER_SIZE,fp); (*biPtr->bsaveFunction)(theEnv,fp); } @@ -309,7 +321,8 @@ static void WriteNeededFunctions( void *theEnv, FILE *fp) { - unsigned long int space, count = 0, length; + unsigned long int count = 0; + size_t space, length; struct FunctionDefinition *functionList; /*================================================*/ @@ -356,7 +369,7 @@ static void WriteNeededFunctions( if (functionList->bsaveIndex >= 0) { length = strlen(ValueToString(functionList->callFunctionName)) + 1; - GenWrite(ValueToString(functionList->callFunctionName),(unsigned long) length,fp); + GenWrite((void *) ValueToString(functionList->callFunctionName),(unsigned long) length,fp); } } } @@ -366,10 +379,10 @@ static void WriteNeededFunctions( /* of bytes needed to save all of the */ /* function names in the binary save file. */ /*********************************************/ -static unsigned long int FunctionBinarySize( +static size_t FunctionBinarySize( void *theEnv) { - unsigned long int size = 0; + size_t size = 0; struct FunctionDefinition *functionList; for (functionList = GetFunctionList(theEnv); @@ -484,8 +497,8 @@ static void WriteBinaryHeader( void *theEnv, FILE *fp) { - GenWrite(BloadData(theEnv)->BinaryPrefixID,(unsigned long) strlen(BloadData(theEnv)->BinaryPrefixID) + 1,fp); - GenWrite(BloadData(theEnv)->BinaryVersionID,(unsigned long) strlen(BloadData(theEnv)->BinaryVersionID) + 1,fp); + GenWrite((void *) BloadData(theEnv)->BinaryPrefixID,(unsigned long) strlen(BloadData(theEnv)->BinaryPrefixID) + 1,fp); + GenWrite((void *) BloadData(theEnv)->BinaryVersionID,(unsigned long) strlen(BloadData(theEnv)->BinaryVersionID) + 1,fp); } /******************************************************/ @@ -498,7 +511,7 @@ static void WriteBinaryFooter( { char footerBuffer[CONSTRUCT_HEADER_SIZE]; - strncpy(footerBuffer,BloadData(theEnv)->BinaryPrefixID,CONSTRUCT_HEADER_SIZE); + genstrncpy(footerBuffer,BloadData(theEnv)->BinaryPrefixID,CONSTRUCT_HEADER_SIZE); GenWrite(footerBuffer,(unsigned long) CONSTRUCT_HEADER_SIZE,fp); } @@ -514,7 +527,7 @@ static void WriteBinaryFooter( /**********************************************************/ globle intBool AddBinaryItem( void *theEnv, - char *name, + const char *name, int priority, void (*findFunction)(void *), void (*expressionFunction)(void *,FILE *), @@ -588,6 +601,24 @@ globle intBool AddBinaryItem( #endif /* BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if BLOAD_AND_BSAVE + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool Bsave( + const char *fileName) + { + return EnvBsave(GetCurrentEnvironment(),fileName); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* BLOAD_AND_BSAVE */ + diff --git a/src/bsave.h b/src/bsave.h index 54d8df4..dd00eb0 100644 --- a/src/bsave.h +++ b/src/bsave.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* BSAVE HEADER FILE */ /*******************************************************/ @@ -11,7 +11,7 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,18 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used genstrncpy instead of strncpy. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_bsave @@ -47,7 +59,7 @@ struct BinaryItem; struct BinaryItem { - char *name; + const char *name; void (*findFunction)(void *); void (*bloadStorageFunction)(void *); void (*bloadFunction)(void *); @@ -78,7 +90,7 @@ typedef struct bsave_expr #define BSAVE_DATA 39 struct bsaveData - { + { struct BinaryItem *ListOfBinaryItems; #if BLOAD_AND_BSAVE BLOADCNTSV *BloadCountSaveTop; @@ -87,21 +99,15 @@ struct bsaveData #define BsaveData(theEnv) ((struct bsaveData *) GetEnvironmentData(theEnv,BSAVE_DATA)) -#if ENVIRONMENT_API_ONLY -#define Bsave(theEnv,a) EnvBsave(theEnv,a) -#else -#define Bsave(a) EnvBsave(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeBsaveData(void *); LOCALE int BsaveCommand(void *); #if BLOAD_AND_BSAVE - LOCALE intBool EnvBsave(void *,char *); + LOCALE intBool EnvBsave(void *,const char *); LOCALE void MarkNeededItems(void *,struct expr *); LOCALE void SaveBloadCount(void *,long); LOCALE void RestoreBloadCount(void *,long *); #endif - LOCALE intBool AddBinaryItem(void *,char *,int, + LOCALE intBool AddBinaryItem(void *,const char *,int, void (*)(void *), void (*)(void *,FILE *), void (*)(void *,FILE *), @@ -110,12 +116,14 @@ struct bsaveData void (*)(void *), void (*)(void *)); -#ifndef _BSAVE_SOURCE_ - extern struct BinaryItem *ListOfBinaryItems; -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool Bsave(const char *); #endif +#endif /* _H_bsave */ + diff --git a/src/classcom.c b/src/classcom.c index 29a9639..406441d 100644 --- a/src/classcom.c +++ b/src/classcom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* CLASS COMMANDS MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Kernel Interface Commands for Object System */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ @@ -26,6 +27,18 @@ /* */ /* Added pragmas to remove compilation warnings. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /**************************************************************/ /* ========================================= @@ -64,7 +77,7 @@ #if (! BLOAD_ONLY) && (! RUN_TIME) && DEBUGGING_FUNCTIONS static void SaveDefclass(void *,struct constructHeader *,void *); #endif -static char *GetClassDefaultsModeName(unsigned short); +static const char *GetClassDefaultsModeName(unsigned short); /* ========================================= ***************************************** @@ -81,14 +94,56 @@ static char *GetClassDefaultsModeName(unsigned short); SIDE EFFECTS : None NOTES : None ******************************************************************/ -globle void *EnvFindDefclass( +globle void *EnvFindDefclass( // TBD Needs to look in imported void *theEnv, - char *classAndModuleName) + const char *classAndModuleName) { SYMBOL_HN *classSymbol = NULL; DEFCLASS *cls; struct defmodule *theModule = NULL; - char *className; + const char *className; + + SaveCurrentModule(theEnv); + className = ExtractModuleAndConstructName(theEnv,classAndModuleName); + if (className != NULL) + { + classSymbol = FindSymbolHN(theEnv,ExtractModuleAndConstructName(theEnv,classAndModuleName)); + theModule = ((struct defmodule *) EnvGetCurrentModule(theEnv)); + } + RestoreCurrentModule(theEnv); + + if (classSymbol == NULL) + return(NULL); + cls = DefclassData(theEnv)->ClassTable[HashClass(classSymbol)]; + while (cls != NULL) + { + if (cls->header.name == classSymbol) + { + if (cls->system || (cls->header.whichModule->theModule == theModule)) + return(cls->installed ? (void *) cls : NULL); + } + cls = cls->nxtHash; + } + return(NULL); + } + +/******************************************************************* + NAME : EnvFindDefclass + DESCRIPTION : Looks up a specified class in the class hash table + (Only looks in current or specified module) + INPUTS : The name-string of the class (including module) + RETURNS : The address of the found class, NULL otherwise + SIDE EFFECTS : None + NOTES : None + ******************************************************************/ +globle void *EnvFindDefclassInModule( + void *theEnv, + const char *classAndModuleName) + { + SYMBOL_HN *classSymbol = NULL; + DEFCLASS *cls; + struct defmodule *theModule = NULL; + const char *className; SaveCurrentModule(theEnv); className = ExtractModuleAndConstructName(theEnv,classAndModuleName); @@ -128,10 +183,10 @@ globle void *EnvFindDefclass( ***************************************************/ globle DEFCLASS *LookupDefclassByMdlOrScope( void *theEnv, - char *classAndModuleName) + const char *classAndModuleName) { DEFCLASS *cls; - char *className; + const char *className; SYMBOL_HN *classSymbol; struct defmodule *theModule; @@ -171,7 +226,7 @@ globle DEFCLASS *LookupDefclassByMdlOrScope( ****************************************************/ globle DEFCLASS *LookupDefclassInScope( void *theEnv, - char *className) + const char *className) { DEFCLASS *cls; SYMBOL_HN *classSymbol; @@ -204,7 +259,7 @@ globle DEFCLASS *LookupDefclassInScope( globle DEFCLASS *LookupDefclassAnywhere( void *theEnv, struct defmodule *theModule, - char *className) + const char *className) { DEFCLASS *cls; SYMBOL_HN *classSymbol; @@ -235,9 +290,6 @@ globle DEFCLASS *LookupDefclassAnywhere( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC && (! DEFMODULE_CONSTRUCT) -#pragma argsused -#endif globle intBool DefclassInScope( void *theEnv, DEFCLASS *theDefclass, @@ -253,7 +305,7 @@ globle intBool DefclassInScope( moduleID = (int) theModule->bsaveID; return(TestBitMap(scopeMap,moduleID) ? TRUE : FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,theDefclass,theModule) #endif return(TRUE); @@ -299,7 +351,7 @@ globle intBool EnvIsDefclassDeletable( cls = (DEFCLASS *) ptr; if (cls->system == 1) return(FALSE); - + #if (! BLOAD_ONLY) && (! RUN_TIME) return((IsClassBeingUsed(cls) == FALSE) ? TRUE : FALSE); #else @@ -334,10 +386,6 @@ globle intBool EnvUndefclass( void *theEnv, void *theDefclass) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,theDefclass) -#endif - #if RUN_TIME || BLOAD_ONLY return(FALSE); #else @@ -368,7 +416,7 @@ globle intBool EnvUndefclass( *********************************************************/ globle void PPDefclassCommand( void *theEnv) - { + { PPConstructCommand(theEnv,"ppdefclass",DefclassData(theEnv)->DefclassConstruct); } @@ -397,7 +445,7 @@ globle void ListDefclassesCommand( ***************************************************/ globle void EnvListDefclasses( void *theEnv, - char *logicalName, + const char *logicalName, struct defmodule *theModule) { ListConstruct(theEnv,DefclassData(theEnv)->DefclassConstruct,logicalName,theModule); @@ -414,14 +462,11 @@ globle void EnvListDefclasses( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefclassWatchInstances( void *theEnv, void *theClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -440,15 +485,12 @@ globle unsigned EnvGetDefclassWatchInstances( SIDE EFFECTS : Watch flag for the class set NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefclassWatchInstances( void *theEnv, unsigned newState, void *theClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -468,14 +510,11 @@ globle void EnvSetDefclassWatchInstances( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefclassWatchSlots( void *theEnv, void *theClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -493,15 +532,12 @@ globle unsigned EnvGetDefclassWatchSlots( SIDE EFFECTS : Watch flag for the class set NOTES : None **********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefclassWatchSlots( void *theEnv, unsigned newState, void *theClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -552,7 +588,7 @@ globle unsigned DefclassWatchAccess( ***********************************************************************/ globle unsigned DefclassWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { @@ -564,7 +600,7 @@ globle unsigned DefclassWatchPrint( EnvGetDefclassWatchInstances,EnvSetDefclassWatchInstances)); } -#endif +#endif /* DEBUGGING_FUNCTIONS */ /********************************************************* NAME : GetDefclassListFunction @@ -616,7 +652,7 @@ globle int HasSuperclass( DEFCLASS *c1, DEFCLASS *c2) { - register unsigned i; + long i; for (i = 1 ; i < c1->allSuperclasses.classCount ; i++) if (c1->allSuperclasses.classArray[i] == c2) @@ -635,7 +671,7 @@ globle int HasSuperclass( ********************************************************************/ globle SYMBOL_HN *CheckClassAndSlot( void *theEnv, - char *func, + const char *func, DEFCLASS **cls) { DATA_OBJECT temp; @@ -664,18 +700,15 @@ globle SYMBOL_HN *CheckClassAndSlot( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC && (! DEBUGGING_FUNCTIONS) -#pragma argsused -#endif globle void SaveDefclasses( void *theEnv, void *theModule, - char *logName) + const char *logName) { #if DEBUGGING_FUNCTIONS DoForAllConstructsInModule(theEnv,theModule,SaveDefclass,DefclassData(theEnv)->DefclassModuleIndex,FALSE,(void *) logName); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,theModule,logName) #endif #endif @@ -706,9 +739,9 @@ static void SaveDefclass( struct constructHeader *theDefclass, void *userBuffer) { - char *logName = (char *) userBuffer; + const char *logName = (const char *) userBuffer; unsigned hnd; - char *ppForm; + const char *ppForm; ppForm = EnvGetDefclassPPForm(theEnv,(void *) theDefclass); if (ppForm != NULL) @@ -755,7 +788,7 @@ globle unsigned short EnvGetClassDefaultsMode( { return(DefclassData(theEnv)->ClassDefaultsMode); } - + /***************************************************/ /* GetClassDefaultsModeCommand: H/L access routine */ /* for the get-class-defaults-mode command. */ @@ -776,9 +809,9 @@ globle void *SetClassDefaultsModeCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; unsigned short oldMode; - + oldMode = DefclassData(theEnv)->ClassDefaultsMode; /*=====================================================*/ @@ -820,10 +853,10 @@ globle void *SetClassDefaultsModeCommand( /* to a specified class defaults mode, return a character string */ /* of the class defaults mode's name. */ /*******************************************************************/ -static char *GetClassDefaultsModeName( +static const char *GetClassDefaultsModeName( unsigned short mode) { - char *sname; + const char *sname; switch (mode) { @@ -841,4 +874,173 @@ static char *GetClassDefaultsModeName( return(sname); } -#endif +/*#############################*/ +/* Additional Access Functions */ +/*#############################*/ + +globle SYMBOL_HN *GetDefclassNamePointer( + void *theClass) + { + return GetConstructNamePointer((struct constructHeader *) theClass); + } + +globle void SetNextDefclass( + void *theClass, + void *targetClass) + { + SetNextConstruct((struct constructHeader *) theClass, + (struct constructHeader *) targetClass); + } + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvGetDefclassName( + void *theEnv, + void *theClass) + { + return EnvGetConstructNameString(theEnv,(struct constructHeader *) theClass); + } + +globle const char *EnvGetDefclassPPForm( + void *theEnv, + void *theClass) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theClass); + } + +globle struct defmoduleItemHeader *EnvGetDefclassModule( + void *theEnv, + void *theClass) + { + return GetConstructModuleItem((struct constructHeader *) theClass); + } + +globle const char *EnvDefclassModule( + void *theEnv, + void *theClass) + { + return GetConstructModuleName((struct constructHeader *) theClass); + } + +globle void EnvSetDefclassPPForm( + void *theEnv, + void *theClass, + char *thePPForm) + { + SetConstructPPForm(theEnv,(struct constructHeader *) theClass,thePPForm); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *FindDefclass( + const char *classAndModuleName) + { + return EnvFindDefclass(GetCurrentEnvironment(),classAndModuleName); + } + +globle void GetDefclassList( + DATA_OBJECT *returnValue, + struct defmodule *theModule) + { + EnvGetDefclassList(GetCurrentEnvironment(),returnValue,theModule); + } + +globle void *GetNextDefclass( + void *ptr) + { + return EnvGetNextDefclass(GetCurrentEnvironment(),ptr); + } + +globle intBool IsDefclassDeletable( + void *ptr) + { + return EnvIsDefclassDeletable(GetCurrentEnvironment(),ptr); + } + +globle intBool Undefclass( + void *theDefclass) + { + return EnvUndefclass(GetCurrentEnvironment(),theDefclass); + } + +globle unsigned short SetClassDefaultsMode( + unsigned short value) + { + return EnvSetClassDefaultsMode(GetCurrentEnvironment(),value); + } + +globle unsigned short GetClassDefaultsMode() + { + return EnvGetClassDefaultsMode(GetCurrentEnvironment()); + } + +globle const char *GetDefclassName( + void *theClass) + { + return EnvGetDefclassName(GetCurrentEnvironment(),theClass); + } + +globle const char *GetDefclassPPForm( + void *theClass) + { + return EnvGetDefclassPPForm(GetCurrentEnvironment(),theClass); + } + +globle struct defmoduleItemHeader *GetDefclassModule( + void *theClass) + { + return EnvGetDefclassModule(GetCurrentEnvironment(),theClass); + } + +globle const char *DefclassModule( + void *theClass) + { + return EnvDefclassModule(GetCurrentEnvironment(),theClass); + } + +#if DEBUGGING_FUNCTIONS + +globle unsigned GetDefclassWatchInstances( + void *theClass) + { + return EnvGetDefclassWatchInstances(GetCurrentEnvironment(),theClass); + } + +globle unsigned GetDefclassWatchSlots( + void *theClass) + { + return EnvGetDefclassWatchSlots(GetCurrentEnvironment(),theClass); + } + +globle void ListDefclasses( + const char *logicalName, + struct defmodule *theModule) + { + EnvListDefclasses(GetCurrentEnvironment(),logicalName,theModule); + } + +globle void SetDefclassWatchInstances( + unsigned newState, + void *theClass) + { + EnvSetDefclassWatchInstances(GetCurrentEnvironment(),newState,theClass); + } + +globle void SetDefclassWatchSlots( + unsigned newState, + void *theClass) + { + EnvSetDefclassWatchSlots(GetCurrentEnvironment(),newState,theClass); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* OBJECT_SYSTEM */ diff --git a/src/classcom.h b/src/classcom.h index 8aea2c7..da83710 100644 --- a/src/classcom.h +++ b/src/classcom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/04/15 */ /* */ /* */ /*******************************************************/ @@ -10,16 +10,29 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_classcom @@ -28,19 +41,6 @@ #define CONVENIENCE_MODE 0 #define CONSERVATION_MODE 1 -#define EnvGetDefclassName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDefclassPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) - -#define GetDefclassNamePointer(x) GetConstructNamePointer((struct constructHeader *) x) -#define GetDefclassModule(x) GetConstructModuleItem((struct constructHeader *) x) - -#define SetNextDefclass(c,t) SetNextConstruct((struct constructHeader *) c, \ - (struct constructHeader *) t) - -#define SetDefclassPPForm(c,ppf) SetConstructPPForm(theEnv,(struct constructHeader *) c,ppf) - -#define EnvDefclassModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - #ifndef _H_cstrccom #include "cstrccom.h" #endif @@ -64,79 +64,73 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DefclassModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefclass(theEnv,a) EnvFindDefclass(theEnv,a) -#define GetDefclassList(theEnv,a,b) EnvGetDefclassList(theEnv,a,b) -#define GetDefclassName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDefclassPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetDefclassWatchInstances(theEnv,a) EnvGetDefclassWatchInstances(theEnv,a) -#define GetDefclassWatchSlots(theEnv,a) EnvGetDefclassWatchSlots(theEnv,a) -#define GetNextDefclass(theEnv,a) EnvGetNextDefclass(theEnv,a) -#define IsDefclassDeletable(theEnv,a) EnvIsDefclassDeletable(theEnv,a) -#define ListDefclasses(theEnv,a,b) EnvListDefclasses(theEnv,a,b) -#define SetDefclassWatchInstances(theEnv,a,b) EnvSetDefclassWatchInstances(theEnv,a,b) -#define SetDefclassWatchSlots(theEnv,a,b) EnvSetDefclassWatchSlots(theEnv,a,b) -#define Undefclass(theEnv,a) EnvUndefclass(theEnv,a) -#define SetClassDefaultsMode(theEnv,a) EnvSetClassDefaultsMode(theEnv,a) -#define GetClassDefaultsMode(theEnv) EnvGetClassDefaultsMode(theEnv) -#else -#define DefclassModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefclass(a) EnvFindDefclass(GetCurrentEnvironment(),a) -#define GetDefclassList(a,b) EnvGetDefclassList(GetCurrentEnvironment(),a,b) -#define GetDefclassName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDefclassPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetDefclassWatchInstances(a) EnvGetDefclassWatchInstances(GetCurrentEnvironment(),a) -#define GetDefclassWatchSlots(a) EnvGetDefclassWatchSlots(GetCurrentEnvironment(),a) -#define GetNextDefclass(a) EnvGetNextDefclass(GetCurrentEnvironment(),a) -#define IsDefclassDeletable(a) EnvIsDefclassDeletable(GetCurrentEnvironment(),a) -#define ListDefclasses(a,b) EnvListDefclasses(GetCurrentEnvironment(),a,b) -#define SetDefclassWatchInstances(a,b) EnvSetDefclassWatchInstances(GetCurrentEnvironment(),a,b) -#define SetDefclassWatchSlots(a,b) EnvSetDefclassWatchSlots(GetCurrentEnvironment(),a,b) -#define Undefclass(a) EnvUndefclass(GetCurrentEnvironment(),a) -#define SetClassDefaultsMode(a) EnvSetClassDefaultsMode(GetCurrentEnvironment(),a) -#define GetClassDefaultsMode() EnvGetClassDefaultsMode(GetCurrentEnvironment()) -#endif - -LOCALE void *EnvFindDefclass(void *,char *); -LOCALE DEFCLASS *LookupDefclassByMdlOrScope(void *,char *); -LOCALE DEFCLASS *LookupDefclassInScope(void *,char *); -LOCALE DEFCLASS *LookupDefclassAnywhere(void *,struct defmodule *,char *); -LOCALE intBool DefclassInScope(void *,DEFCLASS *,struct defmodule *); -LOCALE void *EnvGetNextDefclass(void *,void *); -LOCALE intBool EnvIsDefclassDeletable(void *,void *); - -LOCALE void UndefclassCommand(void *); -LOCALE unsigned short EnvSetClassDefaultsMode(void *,unsigned short); -LOCALE unsigned short EnvGetClassDefaultsMode(void *); -LOCALE void *GetClassDefaultsModeCommand(void *); -LOCALE void *SetClassDefaultsModeCommand(void *); + LOCALE const char *EnvGetDefclassName(void *,void *); + LOCALE const char *EnvGetDefclassPPForm(void *,void *); + LOCALE struct defmoduleItemHeader + *EnvGetDefclassModule(void *,void *); + LOCALE const char *EnvDefclassModule(void *,void *); + LOCALE SYMBOL_HN *GetDefclassNamePointer(void *); + LOCALE void SetNextDefclass(void *,void *); + LOCALE void EnvSetDefclassPPForm(void *,void *,char *); + + LOCALE void *EnvFindDefclass(void *,const char *); + LOCALE void *EnvFindDefclassInModule(void *,const char *); + LOCALE DEFCLASS *LookupDefclassByMdlOrScope(void *,const char *); + LOCALE DEFCLASS *LookupDefclassInScope(void *,const char *); + LOCALE DEFCLASS *LookupDefclassAnywhere(void *,struct defmodule *,const char *); + LOCALE intBool DefclassInScope(void *,DEFCLASS *,struct defmodule *); + LOCALE void *EnvGetNextDefclass(void *,void *); + LOCALE intBool EnvIsDefclassDeletable(void *,void *); + + LOCALE void UndefclassCommand(void *); + LOCALE unsigned short EnvSetClassDefaultsMode(void *,unsigned short); + LOCALE unsigned short EnvGetClassDefaultsMode(void *); + LOCALE void *GetClassDefaultsModeCommand(void *); + LOCALE void *SetClassDefaultsModeCommand(void *); #if DEBUGGING_FUNCTIONS -LOCALE void PPDefclassCommand(void *); -LOCALE void ListDefclassesCommand(void *); -LOCALE void EnvListDefclasses(void *,char *,struct defmodule *); -LOCALE unsigned EnvGetDefclassWatchInstances(void *,void *); -LOCALE void EnvSetDefclassWatchInstances(void *,unsigned,void *); -LOCALE unsigned EnvGetDefclassWatchSlots(void *,void *); -LOCALE void EnvSetDefclassWatchSlots(void *,unsigned,void *); -LOCALE unsigned DefclassWatchAccess(void *,int,unsigned,EXPRESSION *); -LOCALE unsigned DefclassWatchPrint(void *,char *,int,EXPRESSION *); + LOCALE void PPDefclassCommand(void *); + LOCALE void ListDefclassesCommand(void *); + LOCALE void EnvListDefclasses(void *,const char *,struct defmodule *); + LOCALE unsigned EnvGetDefclassWatchInstances(void *,void *); + LOCALE void EnvSetDefclassWatchInstances(void *,unsigned,void *); + LOCALE unsigned EnvGetDefclassWatchSlots(void *,void *); + LOCALE void EnvSetDefclassWatchSlots(void *,unsigned,void *); + LOCALE unsigned DefclassWatchAccess(void *,int,unsigned,EXPRESSION *); + LOCALE unsigned DefclassWatchPrint(void *,const char *,int,EXPRESSION *); #endif -LOCALE void GetDefclassListFunction(void *,DATA_OBJECT *); -LOCALE void EnvGetDefclassList(void *,DATA_OBJECT *,struct defmodule *); -LOCALE intBool EnvUndefclass(void *,void *); -LOCALE intBool HasSuperclass(DEFCLASS *,DEFCLASS *); + LOCALE void GetDefclassListFunction(void *,DATA_OBJECT *); + LOCALE void EnvGetDefclassList(void *,DATA_OBJECT *,struct defmodule *); + LOCALE intBool EnvUndefclass(void *,void *); + LOCALE intBool HasSuperclass(DEFCLASS *,DEFCLASS *); -LOCALE SYMBOL_HN *CheckClassAndSlot(void *,char *,DEFCLASS **); + LOCALE SYMBOL_HN *CheckClassAndSlot(void *,const char *,DEFCLASS **); #if (! BLOAD_ONLY) && (! RUN_TIME) -LOCALE void SaveDefclasses(void *,void *,char *); + LOCALE void SaveDefclasses(void *,void *,const char *); #endif -#endif - - - - +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE const char *DefclassModule(void *); + LOCALE void *FindDefclass(const char *); + LOCALE void GetDefclassList(DATA_OBJECT *,struct defmodule *); + LOCALE unsigned short GetClassDefaultsMode(void); + LOCALE struct defmoduleItemHeader + *GetDefclassModule(void *); + LOCALE const char *GetDefclassName(void *); + LOCALE const char *GetDefclassPPForm(void *); + LOCALE unsigned GetDefclassWatchInstances(void *); + LOCALE unsigned GetDefclassWatchSlots(void *); + LOCALE void *GetNextDefclass(void *); + LOCALE intBool IsDefclassDeletable(void *); + LOCALE void ListDefclasses(const char *,struct defmodule *); + LOCALE unsigned short SetClassDefaultsMode(unsigned short); + LOCALE void SetDefclassWatchInstances(unsigned,void *); + LOCALE void SetDefclassWatchSlots(unsigned,void *); + LOCALE intBool Undefclass(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_classcom */ diff --git a/src/classexm.c b/src/classexm.c index c782e69..ce1227f 100644 --- a/src/classexm.c +++ b/src/classexm.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CLASS EXAMINATION MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Class browsing and examination commands */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Modified the slot-writablep function to return */ @@ -32,6 +33,21 @@ /* default exists for a slot (the ?NONE value was */ /* specified). DR0870 */ /* */ +/* 6.30: Used %zd for printing size_t arguments. */ +/* */ +/* Added EnvSlotDefaultP function. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Used gensprintf and genstrcat instead of */ +/* sprintf and strcat. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /**************************************************************/ /* ========================================= @@ -56,6 +72,7 @@ #include "msgfun.h" #include "router.h" #include "strngrtr.h" +#include "sysdep.h" #define _CLASSEXM_SOURCE_ #include "classexm.h" @@ -66,19 +83,19 @@ ========================================= ***************************************** */ -static int CheckTwoClasses(void *,char *,DEFCLASS **,DEFCLASS **); -static SLOT_DESC *CheckSlotExists(void *,char *,DEFCLASS **,intBool,intBool); -static SLOT_DESC *LookupSlot(void *,DEFCLASS *,char *,intBool); +static int CheckTwoClasses(void *,const char *,DEFCLASS **,DEFCLASS **); +static SLOT_DESC *CheckSlotExists(void *,const char *,DEFCLASS **,intBool,intBool); +static SLOT_DESC *LookupSlot(void *,DEFCLASS *,const char *,intBool); #if DEBUGGING_FUNCTIONS -static DEFCLASS *CheckClass(void *,char *,char *); -static char *GetClassNameArgument(void *,char *); -static void PrintClassBrowse(void *,char *,DEFCLASS *,unsigned); -static void DisplaySeparator(void *,char *,char *,int,int); -static void DisplaySlotBasicInfo(void *,char *,char *,char *,char *,DEFCLASS *); -static intBool PrintSlotSources(void *,char *,SYMBOL_HN *,PACKED_CLASS_LINKS *,unsigned,int); -static void DisplaySlotConstraintInfo(void *,char *,char *,char *,unsigned,DEFCLASS *); -static char *ConstraintCode(CONSTRAINT_RECORD *,unsigned,unsigned); +static DEFCLASS *CheckClass(void *,const char *,const char *); +static const char *GetClassNameArgument(void *,const char *); +static void PrintClassBrowse(void *,const char *,DEFCLASS *,long); +static void DisplaySeparator(void *,const char *,char *,int,int); +static void DisplaySlotBasicInfo(void *,const char *,const char *,const char *,char *,DEFCLASS *); +static intBool PrintSlotSources(void *,const char *,SYMBOL_HN *,PACKED_CLASS_LINKS *,long,int); +static void DisplaySlotConstraintInfo(void *,const char *,const char *,char *,unsigned,DEFCLASS *); +static const char *ConstraintCode(CONSTRAINT_RECORD *,unsigned,unsigned); #endif /* ========================================= @@ -101,7 +118,7 @@ globle void BrowseClassesCommand( void *theEnv) { register DEFCLASS *cls; - + if (EnvRtnArgCount(theEnv) == 0) /* ================================================ Find the OBJECT root class (has no superclasses) @@ -134,7 +151,7 @@ globle void BrowseClassesCommand( ****************************************************************/ globle void EnvBrowseClasses( void *theEnv, - char *logicalName, + const char *logicalName, void *clsptr) { PrintClassBrowse(theEnv,logicalName,(DEFCLASS *) clsptr,0); @@ -153,9 +170,9 @@ globle void EnvBrowseClasses( globle void DescribeClassCommand( void *theEnv) { - char *cname; + const char *cname; DEFCLASS *cls; - + cname = GetClassNameArgument(theEnv,"describe-class"); if (cname == NULL) return; @@ -178,7 +195,7 @@ globle void DescribeClassCommand( ******************************************************/ globle void EnvDescribeClass( void *theEnv, - char *logicalName, + const char *logicalName, void *clsptr) { DEFCLASS *cls; @@ -186,7 +203,7 @@ globle void EnvDescribeClass( slotNamePrintFormat[12], overrideMessagePrintFormat[12]; int messageBanner; - unsigned i; + long i; size_t slotNameLength, maxSlotNameLength; size_t overrideMessageLength, maxOverrideMessageLength; @@ -232,9 +249,20 @@ globle void EnvDescribeClass( maxSlotNameLength = 16; if (maxOverrideMessageLength > 12) maxOverrideMessageLength = 12; - sprintf(slotNamePrintFormat,"%%-%ld.%lds : ",(long) maxSlotNameLength,(long) maxSlotNameLength); - sprintf(overrideMessagePrintFormat,"%%-%ld.%lds ", (long) maxOverrideMessageLength, - (long) maxOverrideMessageLength); +#if WIN_MVC + gensprintf(slotNamePrintFormat,"%%-%Id.%Ids : ",maxSlotNameLength,maxSlotNameLength); + gensprintf(overrideMessagePrintFormat,"%%-%Id.%Ids ",maxOverrideMessageLength, + maxOverrideMessageLength); +#elif WIN_GCC + gensprintf(slotNamePrintFormat,"%%-%ld.%lds : ",(long) maxSlotNameLength,(long) maxSlotNameLength); + gensprintf(overrideMessagePrintFormat,"%%-%ld.%lds ",(long) maxOverrideMessageLength, + (long) maxOverrideMessageLength); +#else + gensprintf(slotNamePrintFormat,"%%-%zd.%zds : ",maxSlotNameLength,maxSlotNameLength); + gensprintf(overrideMessagePrintFormat,"%%-%zd.%zds ",maxOverrideMessageLength, + maxOverrideMessageLength); +#endif + DisplaySlotBasicInfo(theEnv,logicalName,slotNamePrintFormat,overrideMessagePrintFormat,buf,cls); EnvPrintRouter(theEnv,logicalName,"\nConstraint information for slots:\n\n"); DisplaySlotConstraintInfo(theEnv,logicalName,slotNamePrintFormat,buf,82,cls); @@ -261,7 +289,7 @@ globle void EnvDescribeClass( DisplaySeparator(theEnv,logicalName,buf,82,'='); } -#endif +#endif /* DEBUGGING_FUNCTIONS */ /********************************************************** NAME : GetCreateAccessorString @@ -273,7 +301,7 @@ globle void EnvDescribeClass( SIDE EFFECTS : None NOTES : Used by (describe-class) and (slot-facets) **********************************************************/ -globle char *GetCreateAccessorString( +globle const char *GetCreateAccessorString( void *vsd) { SLOT_DESC *sd = (SLOT_DESC *) vsd; @@ -283,7 +311,10 @@ globle char *GetCreateAccessorString( if ((sd->createReadAccessor == 0) && (sd->createWriteAccessor == 0)) return("NIL"); else - return((char *) (sd->createReadAccessor ? "R" : "W")); + { + if (sd->createReadAccessor) return "R"; + else return "W"; + } } /************************************************************ @@ -312,7 +343,7 @@ globle intBool SuperclassPCommand( void *theEnv) { DEFCLASS *c1,*c2; - + if (CheckTwoClasses(theEnv,"superclassp",&c1,&c2) == FALSE) return(FALSE); return(EnvSuperclassP(theEnv,(void *) c1,(void *) c2)); @@ -330,15 +361,12 @@ globle intBool SuperclassPCommand( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvSuperclassP( void *theEnv, void *firstClass, void *secondClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -357,7 +385,7 @@ globle intBool SubclassPCommand( void *theEnv) { DEFCLASS *c1,*c2; - + if (CheckTwoClasses(theEnv,"subclassp",&c1,&c2) == FALSE) return(FALSE); return(EnvSubclassP(theEnv,(void *) c1,(void *) c2)); @@ -375,15 +403,12 @@ globle intBool SubclassPCommand( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvSubclassP( void *theEnv, void *firstClass, void *secondClass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -405,7 +430,7 @@ globle int SlotExistPCommand( SLOT_DESC *sd; int inheritFlag = FALSE; DATA_OBJECT dobj; - + sd = CheckSlotExists(theEnv,"slot-existp",&cls,FALSE,TRUE); if (sd == NULL) return(FALSE); @@ -439,7 +464,7 @@ globle int SlotExistPCommand( globle intBool EnvSlotExistP( void *theEnv, void *theDefclass, - char *slotName, + const char *slotName, intBool inheritFlag) { return((LookupSlot(theEnv,(DEFCLASS *) theDefclass,slotName,inheritFlag) != NULL) @@ -461,7 +486,7 @@ globle int MessageHandlerExistPCommand( SYMBOL_HN *mname; DATA_OBJECT temp; unsigned mtype = MPRIMARY; - + if (EnvArgTypeCheck(theEnv,"message-handler-existp",1,SYMBOL,&temp) == FALSE) return(FALSE); cls = LookupDefclassByMdlOrScope(theEnv,DOToString(temp)); @@ -502,7 +527,7 @@ globle intBool SlotWritablePCommand( { DEFCLASS *theDefclass; SLOT_DESC *sd; - + sd = CheckSlotExists(theEnv,"slot-writablep",&theDefclass,TRUE,TRUE); if (sd == NULL) return(FALSE); @@ -522,7 +547,7 @@ globle intBool SlotWritablePCommand( globle intBool EnvSlotWritableP( void *theEnv, void *theDefclass, - char *slotName) + const char *slotName) { SLOT_DESC *sd; @@ -545,7 +570,7 @@ globle intBool SlotInitablePCommand( { DEFCLASS *theDefclass; SLOT_DESC *sd; - + sd = CheckSlotExists(theEnv,"slot-initablep",&theDefclass,TRUE,TRUE); if (sd == NULL) return(FALSE); @@ -565,7 +590,7 @@ globle intBool SlotInitablePCommand( globle intBool EnvSlotInitableP( void *theEnv, void *theDefclass, - char *slotName) + const char *slotName) { SLOT_DESC *sd; @@ -588,7 +613,7 @@ globle intBool SlotPublicPCommand( { DEFCLASS *theDefclass; SLOT_DESC *sd; - + sd = CheckSlotExists(theEnv,"slot-publicp",&theDefclass,TRUE,FALSE); if (sd == NULL) return(FALSE); @@ -608,7 +633,7 @@ globle intBool SlotPublicPCommand( globle intBool EnvSlotPublicP( void *theEnv, void *theDefclass, - char *slotName) + const char *slotName) { SLOT_DESC *sd; @@ -617,6 +642,35 @@ globle intBool EnvSlotPublicP( return(sd->publicVisibility ? TRUE : FALSE); } +/*************************************************** + NAME : EnvSlotDefaultP + DESCRIPTION : Determines if a slot has a default value + INPUTS : 1) The class + 2) The slot name + RETURNS : TRUE if slot is public, + FALSE otherwise + SIDE EFFECTS : None + NOTES : None + ***************************************************/ +globle int EnvSlotDefaultP( + void *theEnv, + void *theDefclass, + const char *slotName) + { + SLOT_DESC *sd; + + if ((sd = LookupSlot(theEnv,(DEFCLASS *) theDefclass,slotName,FALSE)) == NULL) + return(NO_DEFAULT); + + if (sd->noDefault) + { return(NO_DEFAULT); } + else if (sd->dynamicDefault) + { return(DYNAMIC_DEFAULT); } + + return(STATIC_DEFAULT); + } + + /********************************************************************** NAME : SlotDirectAccessPCommand DESCRIPTION : Determines if an existing slot can be directly @@ -633,7 +687,7 @@ globle intBool SlotDirectAccessPCommand( { DEFCLASS *theDefclass; SLOT_DESC *sd; - + sd = CheckSlotExists(theEnv,"slot-direct-accessp",&theDefclass,TRUE,TRUE); if (sd == NULL) return(FALSE); @@ -655,7 +709,7 @@ globle intBool SlotDirectAccessPCommand( globle intBool EnvSlotDirectAccessP( void *theEnv, void *theDefclass, - char *slotName) + const char *slotName) { SLOT_DESC *sd; @@ -686,14 +740,14 @@ globle void SlotDefaultValueCommand( sd = CheckSlotExists(theEnv,"slot-default-value",&theDefclass,TRUE,TRUE); if (sd == NULL) return; - + if (sd->noDefault) { SetpType(theValue,SYMBOL); SetpValue(theValue,EnvAddSymbol(theEnv,"?NONE")); - return; + return; } - + if (sd->dynamicDefault) EvaluateAndStoreInDataObject(theEnv,(int) sd->multiple, (EXPRESSION *) sd->defaultValue, @@ -717,7 +771,7 @@ globle void SlotDefaultValueCommand( globle intBool EnvSlotDefaultValue( void *theEnv, void *theDefclass, - char *slotName, + const char *slotName, DATA_OBJECT_PTR theValue) { SLOT_DESC *sd; @@ -726,14 +780,14 @@ globle intBool EnvSlotDefaultValue( SetpValue(theValue,EnvFalseSymbol(theEnv)); if ((sd = LookupSlot(theEnv,(DEFCLASS *) theDefclass,slotName,TRUE)) == NULL) return(FALSE); - + if (sd->noDefault) { SetpType(theValue,SYMBOL); SetpValue(theValue,EnvAddSymbol(theEnv,"?NONE")); - return(TRUE); + return(TRUE); } - + if (sd->dynamicDefault) return(EvaluateAndStoreInDataObject(theEnv,(int) sd->multiple, (EXPRESSION *) sd->defaultValue, @@ -754,7 +808,7 @@ globle intBool ClassExistPCommand( void *theEnv) { DATA_OBJECT temp; - + if (EnvArgTypeCheck(theEnv,"class-existp",1,SYMBOL,&temp) == FALSE) return(FALSE); return((LookupDefclassByMdlOrScope(theEnv,DOToString(temp)) != NULL) ? TRUE : FALSE); @@ -779,7 +833,7 @@ globle intBool ClassExistPCommand( ******************************************************/ static int CheckTwoClasses( void *theEnv, - char *func, + const char *func, DEFCLASS **c1, DEFCLASS **c2) { @@ -824,7 +878,7 @@ static int CheckTwoClasses( ***************************************************/ static SLOT_DESC *CheckSlotExists( void *theEnv, - char *func, + const char *func, DEFCLASS **classBuffer, intBool existsErrorFlag, intBool inheritFlag) @@ -876,7 +930,7 @@ static SLOT_DESC *CheckSlotExists( static SLOT_DESC *LookupSlot( void *theEnv, DEFCLASS *theDefclass, - char *slotName, + const char *slotName, intBool inheritFlag) { SYMBOL_HN *slotSymbol; @@ -911,8 +965,8 @@ static SLOT_DESC *LookupSlot( ******************************************************/ static DEFCLASS *CheckClass( void *theEnv, - char *func, - char *cname) + const char *func, + const char *cname) { DEFCLASS *cls; @@ -930,9 +984,9 @@ static DEFCLASS *CheckClass( SIDE EFFECTS : None NOTES : Assumes only 1 argument *********************************************************/ -static char *GetClassNameArgument( +static const char *GetClassNameArgument( void *theEnv, - char *fname) + const char *fname) { DATA_OBJECT temp; @@ -953,11 +1007,11 @@ static char *GetClassNameArgument( ****************************************************************/ static void PrintClassBrowse( void *theEnv, - char *logicalName, + const char *logicalName, DEFCLASS *cls, - unsigned depth) + long depth) { - register unsigned i; + long i; for (i = 0 ; i < depth ; i++) EnvPrintRouter(theEnv,logicalName," "); @@ -982,7 +1036,7 @@ static void PrintClassBrowse( *********************************************************/ static void DisplaySeparator( void *theEnv, - char *logicalName, + const char *logicalName, char *buf, int maxlen, int sepchar) @@ -1027,57 +1081,57 @@ static void DisplaySeparator( *************************************************************/ static void DisplaySlotBasicInfo( void *theEnv, - char *logicalName, - char *slotNamePrintFormat, - char *overrideMessagePrintFormat, + const char *logicalName, + const char *slotNamePrintFormat, + const char *overrideMessagePrintFormat, char *buf, DEFCLASS *cls) { - register unsigned i; + long i; SLOT_DESC *sp; - char *createString; + const char *createString; - sprintf(buf,slotNamePrintFormat,"SLOTS"); + gensprintf(buf,slotNamePrintFormat,"SLOTS"); #if DEFRULE_CONSTRUCT - strcat(buf,"FLD DEF PRP ACC STO MCH SRC VIS CRT "); + genstrcat(buf,"FLD DEF PRP ACC STO MCH SRC VIS CRT "); #else - strcat(buf,"FLD DEF PRP ACC STO SRC VIS CRT "); + genstrcat(buf,"FLD DEF PRP ACC STO SRC VIS CRT "); #endif EnvPrintRouter(theEnv,logicalName,buf); - sprintf(buf,overrideMessagePrintFormat,"OVRD-MSG"); + gensprintf(buf,overrideMessagePrintFormat,"OVRD-MSG"); EnvPrintRouter(theEnv,logicalName,buf); EnvPrintRouter(theEnv,logicalName,"SOURCE(S)\n"); for (i = 0 ; i < cls->instanceSlotCount ; i++) { sp = cls->instanceTemplate[i]; - sprintf(buf,slotNamePrintFormat,ValueToString(sp->slotName->name)); - strcat(buf,sp->multiple ? "MLT " : "SGL "); + gensprintf(buf,slotNamePrintFormat,ValueToString(sp->slotName->name)); + genstrcat(buf,sp->multiple ? "MLT " : "SGL "); if (sp->noDefault) - strcat(buf,"NIL "); + genstrcat(buf,"NIL "); else - strcat(buf,sp->dynamicDefault ? "DYN " : "STC "); - strcat(buf,sp->noInherit ? "NIL " : "INH "); + genstrcat(buf,sp->dynamicDefault ? "DYN " : "STC "); + genstrcat(buf,sp->noInherit ? "NIL " : "INH "); if (sp->initializeOnly) - strcat(buf,"INT "); + genstrcat(buf,"INT "); else if (sp->noWrite) - strcat(buf," R "); + genstrcat(buf," R "); else - strcat(buf,"RW "); - strcat(buf,sp->shared ? "SHR " : "LCL "); + genstrcat(buf,"RW "); + genstrcat(buf,sp->shared ? "SHR " : "LCL "); #if DEFRULE_CONSTRUCT - strcat(buf,sp->reactive ? "RCT " : "NIL "); + genstrcat(buf,sp->reactive ? "RCT " : "NIL "); #endif - strcat(buf,sp->composite ? "CMP " : "EXC "); - strcat(buf,sp->publicVisibility ? "PUB " : "PRV "); + genstrcat(buf,sp->composite ? "CMP " : "EXC "); + genstrcat(buf,sp->publicVisibility ? "PUB " : "PRV "); createString = GetCreateAccessorString(sp); if (createString[1] == '\0') - strcat(buf," "); - strcat(buf,createString); + genstrcat(buf," "); + genstrcat(buf,createString); if ((createString[1] == '\0') ? TRUE : (createString[2] == '\0')) - strcat(buf," "); - strcat(buf," "); + genstrcat(buf," "); + genstrcat(buf," "); EnvPrintRouter(theEnv,logicalName,buf); - sprintf(buf,overrideMessagePrintFormat, + gensprintf(buf,overrideMessagePrintFormat, sp->noWrite ? "NIL" : ValueToString(sp->overrideMessage)); EnvPrintRouter(theEnv,logicalName,buf); PrintSlotSources(theEnv,logicalName,sp->slotName->name,&sp->cls->allSuperclasses,0,TRUE); @@ -1107,10 +1161,10 @@ static void DisplaySlotBasicInfo( ***************************************************/ static intBool PrintSlotSources( void *theEnv, - char *logicalName, + const char *logicalName, SYMBOL_HN *sname, PACKED_CLASS_LINKS *sprec, - unsigned theIndex, + long theIndex, int inhp) { SLOT_DESC *csp; @@ -1159,38 +1213,38 @@ static intBool PrintSlotSources( *********************************************************/ static void DisplaySlotConstraintInfo( void *theEnv, - char *logicalName, - char *slotNamePrintFormat, + const char *logicalName, + const char *slotNamePrintFormat, char *buf, unsigned maxlen, DEFCLASS *cls) { - register unsigned i; + long i; CONSTRAINT_RECORD *cr; - char *strdest = "***describe-class***"; + const char *strdest = "***describe-class***"; - sprintf(buf,slotNamePrintFormat,"SLOTS"); - strcat(buf,"SYM STR INN INA EXA FTA INT FLT\n"); + gensprintf(buf,slotNamePrintFormat,"SLOTS"); + genstrcat(buf,"SYM STR INN INA EXA FTA INT FLT\n"); EnvPrintRouter(theEnv,logicalName,buf); for (i = 0 ; i < cls->instanceSlotCount ; i++) { cr = cls->instanceTemplate[i]->constraint; - sprintf(buf,slotNamePrintFormat,ValueToString(cls->instanceTemplate[i]->slotName->name)); + gensprintf(buf,slotNamePrintFormat,ValueToString(cls->instanceTemplate[i]->slotName->name)); if (cr != NULL) { - strcat(buf,ConstraintCode(cr,(unsigned) cr->symbolsAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->symbolsAllowed, (unsigned) cr->symbolRestriction)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->stringsAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->stringsAllowed, (unsigned) cr->stringRestriction)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->instanceNamesAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->instanceNamesAllowed, (unsigned) (cr->instanceNameRestriction || cr->classRestriction))); - strcat(buf,ConstraintCode(cr,(unsigned) cr->instanceAddressesAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->instanceAddressesAllowed, (unsigned) cr->classRestriction)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->externalAddressesAllowed,0)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->factAddressesAllowed,0)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->integersAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->externalAddressesAllowed,0)); + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->factAddressesAllowed,0)); + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->integersAllowed, (unsigned) cr->integerRestriction)); - strcat(buf,ConstraintCode(cr,(unsigned) cr->floatsAllowed, + genstrcat(buf,ConstraintCode(cr,(unsigned) cr->floatsAllowed, (unsigned) cr->floatRestriction)); OpenStringDestination(theEnv,strdest,buf + strlen(buf),(maxlen - strlen(buf) - 1)); if (cr->integersAllowed || cr->floatsAllowed || cr->anyAllowed) @@ -1236,17 +1290,111 @@ static void DisplaySlotConstraintInfo( SIDE EFFECTS : None NOTES : Used by DisplaySlotConstraintInfo ******************************************************/ -static char *ConstraintCode( +static const char *ConstraintCode( CONSTRAINT_RECORD *cr, unsigned allow, unsigned restrictValues) { if (allow || cr->anyAllowed) - return((char *) ((restrictValues || cr->anyRestriction) ? " # " : " + ")); + { + if (restrictValues || cr->anyRestriction) return " # "; + else return " + "; + } return(" "); } #endif +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + +globle void BrowseClasses( + const char *logicalName, + void *clsptr) + { + EnvBrowseClasses(GetCurrentEnvironment(),logicalName,clsptr); + } + +globle void DescribeClass( + const char *logicalName, + void *clsptr) + { + EnvDescribeClass(GetCurrentEnvironment(),logicalName,clsptr); + } + +#endif + +globle intBool SlotDirectAccessP( + void *theDefclass, + const char *slotName) + { + return EnvSlotDirectAccessP(GetCurrentEnvironment(),theDefclass,slotName); + } + +globle intBool SlotExistP( + void *theDefclass, + const char *slotName, + intBool inheritFlag) + { + return EnvSlotExistP(GetCurrentEnvironment(),theDefclass,slotName,inheritFlag); + } + +globle intBool SlotInitableP( + void *theDefclass, + const char *slotName) + { + return EnvSlotInitableP(GetCurrentEnvironment(),theDefclass,slotName); + } + +globle intBool SlotPublicP( + void *theDefclass, + const char *slotName) + { + return EnvSlotPublicP(GetCurrentEnvironment(),theDefclass,slotName); + } + +globle int SlotDefaultP( + void *theDefclass, + const char *slotName) + { + return EnvSlotDefaultP(GetCurrentEnvironment(),theDefclass,slotName); + } + +globle intBool SlotWritableP( + void *theDefclass, + const char *slotName) + { + return EnvSlotWritableP(GetCurrentEnvironment(),theDefclass,slotName); + } + +globle intBool SubclassP( + void *firstClass, + void *secondClass) + { + return EnvSubclassP(GetCurrentEnvironment(),firstClass,secondClass); + } + +globle intBool SuperclassP( + void *firstClass, + void *secondClass) + { + return EnvSuperclassP(GetCurrentEnvironment(),firstClass,secondClass); + } + +globle intBool SlotDefaultValue( + void *theDefclass, + const char *slotName, + DATA_OBJECT_PTR theValue) + { + return EnvSlotDefaultValue(GetCurrentEnvironment(),theDefclass,slotName,theValue); + } + +#endif + #endif diff --git a/src/classexm.h b/src/classexm.h index 4c1b8a4..2e5bd3f 100644 --- a/src/classexm.h +++ b/src/classexm.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,14 +10,15 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ -/* */ +/* */ /* 6.24: The DescribeClass macros were incorrectly */ /* defined. DR0862 */ /* */ @@ -25,6 +26,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added EnvSlotDefaultP function. */ +/* */ +/* Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Used gensprintf and genstrcat instead of */ +/* sprintf and strcat. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_classexm @@ -40,60 +54,53 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define BrowseClasses(theEnv,a,b) EnvBrowseClasses(theEnv,a,b) -#define DescribeClass(theEnv,a,b) EnvDescribeClass(theEnv,a,b) -#define SlotDirectAccessP(theEnv,a,b) EnvSlotDirectAccessP(theEnv,a,b) -#define SlotExistP(theEnv,a,b,c) EnvSlotExistP(theEnv,a,b,c) -#define SlotInitableP(theEnv,a,b) EnvSlotInitableP(theEnv,a,b) -#define SlotPublicP(theEnv,a,b) EnvSlotPublicP(theEnv,a,b) -#define SlotWritableP(theEnv,a,b) EnvSlotWritableP(theEnv,a,b) -#define SubclassP(theEnv,a,b) EnvSubclassP(theEnv,a,b) -#define SuperclassP(theEnv,a,b) EnvSuperclassP(theEnv,a,b) -#define SlotDefaultValue(theEnv,a,b,c) EnvSlotDefaultValue(theEnv,a,b,c) -#else -#define BrowseClasses(a,b) EnvBrowseClasses(GetCurrentEnvironment(),a,b) -#define DescribeClass(a,b) EnvDescribeClass(GetCurrentEnvironment(),a,b) -#define SlotDirectAccessP(a,b) EnvSlotDirectAccessP(GetCurrentEnvironment(),a,b) -#define SlotExistP(a,b,c) EnvSlotExistP(GetCurrentEnvironment(),a,b,c) -#define SlotInitableP(a,b) EnvSlotInitableP(GetCurrentEnvironment(),a,b) -#define SlotPublicP(a,b) EnvSlotPublicP(GetCurrentEnvironment(),a,b) -#define SlotWritableP(a,b) EnvSlotWritableP(GetCurrentEnvironment(),a,b) -#define SubclassP(a,b) EnvSubclassP(GetCurrentEnvironment(),a,b) -#define SuperclassP(a,b) EnvSuperclassP(GetCurrentEnvironment(),a,b) -#define SlotDefaultValue(a,b,c) EnvSlotDefaultValue(GetCurrentEnvironment(),a,b,c) -#endif - #if DEBUGGING_FUNCTIONS -LOCALE void BrowseClassesCommand(void *); -LOCALE void EnvBrowseClasses(void *,char *,void *); -LOCALE void DescribeClassCommand(void *); -LOCALE void EnvDescribeClass(void *,char *,void *); -#endif -LOCALE char *GetCreateAccessorString(void *); + LOCALE void BrowseClassesCommand(void *); + LOCALE void EnvBrowseClasses(void *,const char *,void *); + LOCALE void DescribeClassCommand(void *); + LOCALE void EnvDescribeClass(void *,const char *,void *); -LOCALE void *GetDefclassModuleCommand(void *); -LOCALE intBool SuperclassPCommand(void *); -LOCALE intBool EnvSuperclassP(void *,void *,void *); -LOCALE intBool SubclassPCommand(void *); -LOCALE intBool EnvSubclassP(void *,void *,void *); -LOCALE int SlotExistPCommand(void *); -LOCALE intBool EnvSlotExistP(void *,void *,char *,intBool); -LOCALE int MessageHandlerExistPCommand(void *); -LOCALE intBool SlotWritablePCommand(void *); -LOCALE intBool EnvSlotWritableP(void *,void *,char *); -LOCALE intBool SlotInitablePCommand(void *); -LOCALE intBool EnvSlotInitableP(void *,void *,char *); -LOCALE intBool SlotPublicPCommand(void *); -LOCALE intBool EnvSlotPublicP(void *,void *,char *); -LOCALE intBool SlotDirectAccessPCommand(void *); -LOCALE intBool EnvSlotDirectAccessP(void *,void *,char *); -LOCALE void SlotDefaultValueCommand(void *,DATA_OBJECT_PTR); -LOCALE intBool EnvSlotDefaultValue(void *,void *,char *,DATA_OBJECT_PTR); -LOCALE int ClassExistPCommand(void *); +#endif /* DEBUGGING_FUNCTIONS */ -#ifndef _CLASSEXM_SOURCE_ -#endif + LOCALE const char *GetCreateAccessorString(void *); + LOCALE void *GetDefclassModuleCommand(void *); + LOCALE intBool SuperclassPCommand(void *); + LOCALE intBool EnvSuperclassP(void *,void *,void *); + LOCALE intBool SubclassPCommand(void *); + LOCALE intBool EnvSubclassP(void *,void *,void *); + LOCALE int SlotExistPCommand(void *); + LOCALE intBool EnvSlotExistP(void *,void *,const char *,intBool); + LOCALE int MessageHandlerExistPCommand(void *); + LOCALE intBool SlotWritablePCommand(void *); + LOCALE intBool EnvSlotWritableP(void *,void *,const char *); + LOCALE intBool SlotInitablePCommand(void *); + LOCALE intBool EnvSlotInitableP(void *,void *,const char *); + LOCALE intBool SlotPublicPCommand(void *); + LOCALE intBool EnvSlotPublicP(void *,void *,const char *); + LOCALE intBool SlotDirectAccessPCommand(void *); + LOCALE intBool EnvSlotDirectAccessP(void *,void *,const char *); + LOCALE void SlotDefaultValueCommand(void *,DATA_OBJECT_PTR); + LOCALE intBool EnvSlotDefaultValue(void *,void *,const char *,DATA_OBJECT_PTR); + LOCALE int ClassExistPCommand(void *); + LOCALE int EnvSlotDefaultP(void *,void *,const char *); +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + LOCALE void BrowseClasses(const char *,void *); + LOCALE void DescribeClass(const char *,void *); #endif + LOCALE intBool SlotDirectAccessP(void *,const char *); + LOCALE intBool SlotExistP(void *,const char *,intBool); + LOCALE intBool SlotInitableP(void *,const char *); + LOCALE intBool SlotPublicP(void *,const char *); + LOCALE int SlotDefaultP(void *,const char *); + LOCALE intBool SlotWritableP(void *,const char *); + LOCALE intBool SubclassP(void *,void *); + LOCALE intBool SuperclassP(void *,void *); + LOCALE intBool SlotDefaultValue(void *,const char *,DATA_OBJECT_PTR); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_classexm */ diff --git a/src/classfun.c b/src/classfun.c index 49e9085..f451610 100644 --- a/src/classfun.c +++ b/src/classfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CLASS FUNCTIONS MODULE */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Internal class manipulation routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -21,6 +21,24 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used genstrcpy and genstrcat instead of strcpy */ +/* and strcat. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_AND_SAVE */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ /* ========================================= @@ -55,6 +73,7 @@ #include "msgfun.h" #include "router.h" #include "scanner.h" +#include "sysdep.h" #include "utility.h" #define _CLASSFUN_SOURCE_ @@ -81,7 +100,7 @@ static unsigned HashSlotName(SYMBOL_HN *); #if (! RUN_TIME) -static unsigned NewSlotNameID(void *); +static int NewSlotNameID(void *); static void DeassignClassID(void *,unsigned); #endif @@ -99,14 +118,11 @@ static void DeassignClassID(void *,unsigned); SIDE EFFECTS : Busy count incremented NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void IncrementDefclassBusyCount( void *theEnv, void *theDefclass) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -127,7 +143,7 @@ globle void IncrementDefclassBusyCount( globle void DecrementDefclassBusyCount( void *theEnv, void *theDefclass) - { + { if (! ConstructData(theEnv)->ClearInProgress) ((DEFCLASS *) theDefclass)->busy--; } @@ -144,14 +160,8 @@ globle void DecrementDefclassBusyCount( globle intBool InstancesPurge( void *theEnv) { - int svdepth; - DestroyAllInstances(theEnv); - svdepth = EvaluationData(theEnv)->CurrentEvaluationDepth; - if (EvaluationData(theEnv)->CurrentEvaluationDepth == 0) - EvaluationData(theEnv)->CurrentEvaluationDepth = -1; CleanupInstances(theEnv); - EvaluationData(theEnv)->CurrentEvaluationDepth = svdepth; return((InstanceData(theEnv)->InstanceList != NULL) ? FALSE : TRUE); } @@ -199,7 +209,7 @@ globle SLOT_DESC *FindClassSlot( DEFCLASS *cls, SYMBOL_HN *sname) { - register unsigned i; + long i; for (i = 0 ; i < cls->slotCount ; i++) { @@ -220,8 +230,8 @@ globle SLOT_DESC *FindClassSlot( ***************************************************************/ globle void ClassExistError( void *theEnv, - char *func, - char *cname) + const char *func, + const char *cname) { PrintErrorID(theEnv,"CLASSFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to find class "); @@ -267,7 +277,7 @@ globle void DeleteClassLinks( ******************************************************/ globle void PrintClassName( void *theEnv, - char *logicalName, + const char *logicalName, DEFCLASS *theDefclass, intBool linefeedFlag) { @@ -298,11 +308,11 @@ globle void PrintClassName( ***************************************************/ globle void PrintPackedClassLinks( void *theEnv, - char *logicalName, - char *title, + const char *logicalName, + const char *title, PACKED_CLASS_LINKS *plinks) { - register unsigned i; + long i; EnvPrintRouter(theEnv,logicalName,title); for (i = 0 ; i < plinks->classCount ; i++) @@ -421,10 +431,54 @@ globle void DeleteSubclassLink( DEFCLASS *sclass, DEFCLASS *cls) { - register unsigned deletedIndex; + long deletedIndex; PACKED_CLASS_LINKS *src,dst; src = &sclass->directSubclasses; + + for (deletedIndex = 0 ; deletedIndex < src->classCount ; deletedIndex++) + if (src->classArray[deletedIndex] == cls) + break; + if (deletedIndex == src->classCount) + return; + if (src->classCount > 1) + { + dst.classArray = (DEFCLASS **) gm2(theEnv,(sizeof(DEFCLASS *) * (src->classCount - 1))); + if (deletedIndex != 0) + GenCopyMemory(DEFCLASS *,deletedIndex,dst.classArray,src->classArray); + GenCopyMemory(DEFCLASS *,src->classCount - deletedIndex - 1, + dst.classArray + deletedIndex,src->classArray + deletedIndex + 1); + } + else + dst.classArray = NULL; + dst.classCount = (unsigned short) (src->classCount - 1); + DeletePackedClassLinks(theEnv,src,FALSE); + src->classCount = dst.classCount; + src->classArray = dst.classArray; + } + + +/*************************************************** + NAME : DeleteSuperclassLink + DESCRIPTION : Removes a class from another + class's superclass list + INPUTS : 1) The subclass whose superclass + list is to be modified + 2) The superclass to be removed + RETURNS : Nothing useful + SIDE EFFECTS : The subclass list is changed + NOTES : None + ***************************************************/ +globle void DeleteSuperclassLink( + void *theEnv, + DEFCLASS *sclass, + DEFCLASS *cls) + { + long deletedIndex; + PACKED_CLASS_LINKS *src,dst; + + src = &sclass->directSuperclasses; + for (deletedIndex = 0 ; deletedIndex < src->classCount ; deletedIndex++) if (src->classArray[deletedIndex] == cls) break; @@ -497,7 +551,7 @@ globle DEFCLASS *NewClass( ClearBitString(cls->traversalRecord,TRAVERSAL_BYTES); return(cls); } - + /*************************************************** NAME : DeletePackedClassLinks DESCRIPTION : Dealloacates a contiguous array @@ -570,13 +624,13 @@ globle void AssignClassID( globle SLOT_NAME *AddSlotName( void *theEnv, SYMBOL_HN *slotName, - unsigned newid, + int newid, int usenewid) { SLOT_NAME *snp; unsigned hashTableIndex; char *buf; - unsigned bufsz; + size_t bufsz; hashTableIndex = HashSlotName(slotName); snp = DefclassData(theEnv)->SlotNameTable[hashTableIndex]; @@ -597,15 +651,15 @@ globle SLOT_NAME *AddSlotName( snp->name = slotName; snp->hashTableIndex = hashTableIndex; snp->use = 1; - snp->id = usenewid ? newid : NewSlotNameID(theEnv); + snp->id = (short) (usenewid ? newid : NewSlotNameID(theEnv)); snp->nxt = DefclassData(theEnv)->SlotNameTable[hashTableIndex]; DefclassData(theEnv)->SlotNameTable[hashTableIndex] = snp; IncrementSymbolCount(slotName); bufsz = (sizeof(char) * (PUT_PREFIX_LENGTH + strlen(ValueToString(slotName)) + 1)); buf = (char *) gm2(theEnv,bufsz); - strcpy(buf,PUT_PREFIX); - strcat(buf,ValueToString(slotName)); + genstrcpy(buf,PUT_PREFIX); + genstrcat(buf,ValueToString(slotName)); snp->putHandlerName = (SYMBOL_HN *) EnvAddSymbol(theEnv,buf); IncrementSymbolCount(snp->putHandlerName); rm(theEnv,(void *) buf,bufsz); @@ -672,7 +726,7 @@ LOCALE void RemoveDefclass( { DEFCLASS *cls = (DEFCLASS *) vcls; HANDLER *hnd; - register unsigned i; + long i; /* ==================================================== Remove all of this class's superclasses' links to it @@ -680,6 +734,12 @@ LOCALE void RemoveDefclass( for (i = 0 ; i < cls->directSuperclasses.classCount ; i++) DeleteSubclassLink(theEnv,cls->directSuperclasses.classArray[i],cls); + /* ==================================================== + Remove all of this class's subclasses' links to it + ==================================================== */ + for (i = 0 ; i < cls->directSubclasses.classCount ; i++) + DeleteSuperclassLink(theEnv,cls->directSubclasses.classArray[i],cls); + RemoveClassFromTable(theEnv,cls); InstallClass(theEnv,cls,FALSE); @@ -726,14 +786,14 @@ LOCALE void RemoveDefclass( rm(theEnv,(void *) cls->handlers,(sizeof(HANDLER) * cls->handlerCount)); rm(theEnv,(void *) cls->handlerOrderMap,(sizeof(unsigned) * cls->handlerCount)); } - - SetDefclassPPForm((void *) cls,NULL); + + EnvSetDefclassPPForm(theEnv,(void *) cls,NULL); DeassignClassID(theEnv,(unsigned) cls->id); rtn_struct(theEnv,defclass,cls); } - + #endif - + /******************************************************************* NAME : DestroyDefclass DESCRIPTION : Deallocates a class structure and @@ -741,14 +801,14 @@ LOCALE void RemoveDefclass( INPUTS : The address of the class RETURNS : Nothing useful SIDE EFFECTS : None - NOTES : + NOTES : *******************************************************************/ LOCALE void DestroyDefclass( void *theEnv, void *vcls) { DEFCLASS *cls = (DEFCLASS *) vcls; - register unsigned i; + long i; #if ! RUN_TIME HANDLER *hnd; DeletePackedClassLinks(theEnv,&cls->directSuperclasses,FALSE); @@ -770,7 +830,7 @@ LOCALE void DestroyDefclass( #endif } } - + #if ! RUN_TIME if (cls->instanceSlotCount != 0) { @@ -791,7 +851,7 @@ LOCALE void DestroyDefclass( if (hnd->ppForm != NULL) rm(theEnv,(void *) hnd->ppForm,(sizeof(char) * (strlen(hnd->ppForm)+1))); - + if (hnd->usrData != NULL) { ClearUserDataList(theEnv,hnd->usrData); } } @@ -801,17 +861,17 @@ LOCALE void DestroyDefclass( rm(theEnv,(void *) cls->handlers,(sizeof(HANDLER) * cls->handlerCount)); rm(theEnv,(void *) cls->handlerOrderMap,(sizeof(unsigned) * cls->handlerCount)); } - + DestroyConstructHeader(theEnv,&cls->header); rtn_struct(theEnv,defclass,cls); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(hnd) #endif #endif } - + #if ! RUN_TIME /*************************************************** @@ -833,7 +893,7 @@ globle void InstallClass( { SLOT_DESC *slot; HANDLER *hnd; - register unsigned i; + long i; if ((set && cls->installed) || ((set == FALSE) && (cls->installed == 0))) @@ -856,7 +916,7 @@ globle void InstallClass( DecrementBitMapCount(theEnv,cls->scopeMap); #endif ClearUserDataList(theEnv,cls->header.usrData); - + for (i = 0 ; i < cls->slotCount ; i++) { slot = &cls->slots[i]; @@ -902,7 +962,7 @@ globle void InstallClass( globle int IsClassBeingUsed( DEFCLASS *cls) { - register unsigned i; + long i; if (cls->busy > 0) return(TRUE); @@ -972,7 +1032,7 @@ globle int DeleteClassUAG( void *theEnv, DEFCLASS *cls) { - unsigned subCount; + long subCount; while (cls->directSubclasses.classCount != 0) { @@ -1009,7 +1069,7 @@ globle void MarkBitMapSubclasses( DEFCLASS *cls, int set) { - register unsigned i; + long i; if (set) SetBitMap(map,cls->id); @@ -1060,7 +1120,7 @@ globle short FindSlotNameID( ***************************************************/ globle SYMBOL_HN *FindIDSlotName( void *theEnv, - unsigned id) + int id) { SLOT_NAME *snp; @@ -1078,7 +1138,7 @@ globle SYMBOL_HN *FindIDSlotName( ***************************************************/ globle SLOT_NAME *FindIDSlotNameHash( void *theEnv, - unsigned id) + int id) { register int i; SLOT_NAME *snp; @@ -1205,10 +1265,10 @@ static unsigned HashSlotName( SIDE EFFECTS : None NOTES : None ***********************************************/ -static unsigned NewSlotNameID( +static int NewSlotNameID( void *theEnv) { - unsigned newid = 0; + int newid = 0; register unsigned i; SLOT_NAME *snp; @@ -1245,7 +1305,7 @@ static void DeassignClassID( void *theEnv, unsigned id) { - register unsigned i; + int i; int reallocReqd; unsigned short oldChunk = 0,newChunk = 0; @@ -1275,7 +1335,7 @@ static void DeassignClassID( DefclassData(theEnv)->ClassIDMap = (DEFCLASS **) genrealloc(theEnv,(void *) DefclassData(theEnv)->ClassIDMap, (unsigned) (oldChunk * sizeof(DEFCLASS *)), (unsigned) (newChunk * sizeof(DEFCLASS *))); - + DefclassData(theEnv)->AvailClassID = newChunk; } } diff --git a/src/classfun.h b/src/classfun.h index 04fe9c4..1e74810 100644 --- a/src/classfun.h +++ b/src/classfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -21,6 +21,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used genstrcpy and genstrcat instead of strcpy */ +/* and strcat. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_classfun @@ -60,12 +73,12 @@ LOCALE intBool InstancesPurge(void *theEnv); LOCALE void InitializeClasses(void *); #endif LOCALE SLOT_DESC *FindClassSlot(DEFCLASS *,SYMBOL_HN *); -LOCALE void ClassExistError(void *,char *,char *); +LOCALE void ClassExistError(void *,const char *,const char *); LOCALE void DeleteClassLinks(void *,CLASS_LINK *); -LOCALE void PrintClassName(void *,char *,DEFCLASS *,intBool); +LOCALE void PrintClassName(void *,const char *,DEFCLASS *,intBool); #if DEBUGGING_FUNCTIONS || ((! BLOAD_ONLY) && (! RUN_TIME)) -LOCALE void PrintPackedClassLinks(void *,char *,char *,PACKED_CLASS_LINKS *); +LOCALE void PrintPackedClassLinks(void *,const char *,const char *,PACKED_CLASS_LINKS *); #endif #if ! RUN_TIME @@ -73,10 +86,11 @@ LOCALE void PutClassInTable(void *,DEFCLASS *); LOCALE void RemoveClassFromTable(void *,DEFCLASS *); LOCALE void AddClassLink(void *,PACKED_CLASS_LINKS *,DEFCLASS *,int); LOCALE void DeleteSubclassLink(void *,DEFCLASS *,DEFCLASS *); +LOCALE void DeleteSuperclassLink(void *,DEFCLASS *,DEFCLASS *); LOCALE DEFCLASS *NewClass(void *,SYMBOL_HN *); LOCALE void DeletePackedClassLinks(void *,PACKED_CLASS_LINKS *,int); LOCALE void AssignClassID(void *,DEFCLASS *); -LOCALE SLOT_NAME *AddSlotName(void *,SYMBOL_HN *,unsigned,int); +LOCALE SLOT_NAME *AddSlotName(void *,SYMBOL_HN *,int,int); LOCALE void DeleteSlotName(void *,SLOT_NAME *); LOCALE void RemoveDefclass(void *,void *); LOCALE void InstallClass(void *,DEFCLASS *,int); @@ -91,8 +105,8 @@ LOCALE void MarkBitMapSubclasses(char *,DEFCLASS *,int); #endif LOCALE short FindSlotNameID(void *,SYMBOL_HN *); -LOCALE SYMBOL_HN *FindIDSlotName(void *,unsigned); -LOCALE SLOT_NAME *FindIDSlotNameHash(void *,unsigned); +LOCALE SYMBOL_HN *FindIDSlotName(void *,int); +LOCALE SLOT_NAME *FindIDSlotNameHash(void *,int); LOCALE int GetTraversalID(void *); LOCALE void ReleaseTraversalID(void *); LOCALE unsigned HashClass(SYMBOL_HN *); @@ -112,7 +126,7 @@ extern unsigned WatchInstances,WatchSlots; #define PRIMITIVE_CLASSES 9 struct defclassData - { + { struct construct *DefclassConstruct; int DefclassModuleIndex; ENTITY_RECORD DefclassEntityRecord; diff --git a/src/classinf.c b/src/classinf.c index 036452a..076609d 100644 --- a/src/classinf.c +++ b/src/classinf.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CLASS INFO PROGRAMMATIC ACCESS MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Class Information Interface Support Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable exp to theExp */ @@ -28,6 +29,16 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /**************************************************************/ /* ========================================= @@ -68,10 +79,10 @@ ========================================= ***************************************** */ -static void SlotInfoSupportFunction(void *,DATA_OBJECT *,char *,void (*)(void *,void *,char *,DATA_OBJECT *)); +static void SlotInfoSupportFunction(void *,DATA_OBJECT *,const char *,void (*)(void *,void *,const char *,DATA_OBJECT *)); static unsigned CountSubclasses(DEFCLASS *,int,int); static unsigned StoreSubclasses(void *,unsigned,DEFCLASS *,int,int,short); -static SLOT_DESC *SlotInfoSlot(void *,DATA_OBJECT *,DEFCLASS *,char *,char *); +static SLOT_DESC *SlotInfoSlot(void *,DATA_OBJECT *,DEFCLASS *,const char *,const char *); /********************************************************************* NAME : ClassAbstractPCommand @@ -86,7 +97,7 @@ globle int ClassAbstractPCommand( { DATA_OBJECT tmp; DEFCLASS *cls; - + if (EnvArgTypeCheck(theEnv,"class-abstractp",1,SYMBOL,&tmp) == FALSE) return(FALSE); cls = LookupDefclassByMdlOrScope(theEnv,DOToString(tmp)); @@ -115,7 +126,7 @@ globle int ClassReactivePCommand( { DATA_OBJECT tmp; DEFCLASS *cls; - + if (EnvArgTypeCheck(theEnv,"class-reactivep",1,SYMBOL,&tmp) == FALSE) return(FALSE); cls = LookupDefclassByMdlOrScope(theEnv,DOToString(tmp)); @@ -145,7 +156,7 @@ globle int ClassReactivePCommand( ***********************************************************/ globle void *ClassInfoFnxArgs( void *theEnv, - char *fnx, + const char *fnx, int *inhp) { void *clsptr; @@ -198,7 +209,7 @@ globle void ClassSlotsCommand( { int inhp; void *clsptr; - + clsptr = ClassInfoFnxArgs(theEnv,"class-slots",&inhp); if (clsptr == NULL) { @@ -224,7 +235,7 @@ globle void ClassSuperclassesCommand( { int inhp; void *clsptr; - + clsptr = ClassInfoFnxArgs(theEnv,"class-superclasses",&inhp); if (clsptr == NULL) { @@ -250,7 +261,7 @@ globle void ClassSubclassesCommand( { int inhp; void *clsptr; - + clsptr = ClassInfoFnxArgs(theEnv,"class-subclasses",&inhp); if (clsptr == NULL) { @@ -276,7 +287,7 @@ globle void GetDefmessageHandlersListCmd( { int inhp; void *clsptr; - + if (EnvRtnArgCount(theEnv) == 0) EnvGetDefmessageHandlerList(theEnv,NULL,result,0); else @@ -304,7 +315,7 @@ globle void SlotFacetsCommand( globle void SlotSourcesCommand( void *theEnv, DATA_OBJECT *result) - { + { SlotInfoSupportFunction(theEnv,result,"slot-sources",EnvSlotSources); } @@ -351,14 +362,11 @@ globle void SlotCardinalityCommand( SIDE EFFECTS : None NOTES : None ********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvClassAbstractP( void *theEnv, void *clsptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -375,14 +383,11 @@ globle intBool EnvClassAbstractP( SIDE EFFECTS : None NOTES : None ********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvClassReactiveP( void *theEnv, void *clsptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -409,9 +414,9 @@ globle void EnvClassSlots( DATA_OBJECT *result, int inhp) { - unsigned long size; + long size; register DEFCLASS *cls; - register unsigned long i; + long i; cls = (DEFCLASS *) clsptr; size = inhp ? cls->instanceSlotCount : cls->slotCount; @@ -459,7 +464,7 @@ globle void EnvGetDefmessageHandlerList( int inhp) { DEFCLASS *cls,*svcls,*svnxt,*supcls; - unsigned j; + long j; register int classi,classiLimit; unsigned long i, sublen, len; @@ -536,7 +541,7 @@ globle void EnvClassSuperclasses( { PACKED_CLASS_LINKS *plinks; unsigned offset; - register unsigned i,j; + long i,j; if (inhp) { @@ -579,7 +584,7 @@ globle void EnvClassSubclasses( DATA_OBJECT *result, int inhp) { - register unsigned i; + register int i; // Bug fix 2014-07-18: Previously unsigned and SetpDOEnd decremented to -1. register int id; if ((id = GetTraversalID(theEnv)) == -1) @@ -616,7 +621,7 @@ globle void ClassSubclassAddresses( DATA_OBJECT *result, int inhp) { - register unsigned i; + register int i; // Bug fix 2014-07-18: Previously unsigned and SetpDOEnd decremented to -1. register int id; if ((id = GetTraversalID(theEnv)) == -1) @@ -651,7 +656,7 @@ globle void ClassSubclassAddresses( globle void EnvSlotFacets( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register int i; @@ -670,28 +675,67 @@ globle void EnvSlotFacets( for (i = 1 ; i <= 9 ; i++) SetMFType(result->value,i,SYMBOL); #endif - SetMFValue(result->value,1,EnvAddSymbol(theEnv,(char *) (sp->multiple ? "MLT" : "SGL"))); + if (sp->multiple) + SetMFValue(result->value,1,EnvAddSymbol(theEnv,"MLT")); + else + SetMFValue(result->value,1,EnvAddSymbol(theEnv,"SGL")); + if (sp->noDefault) SetMFValue(result->value,2,EnvAddSymbol(theEnv,"NIL")); else - SetMFValue(result->value,2,EnvAddSymbol(theEnv,(char *) (sp->dynamicDefault ? "DYN" : "STC"))); - SetMFValue(result->value,3,EnvAddSymbol(theEnv,(char *) (sp->noInherit ? "NIL" : "INH"))); + { + if (sp->dynamicDefault) + SetMFValue(result->value,2,EnvAddSymbol(theEnv,"DYN")); + else + SetMFValue(result->value,2,EnvAddSymbol(theEnv,"STC")); + } + + if (sp->noInherit) + SetMFValue(result->value,3,EnvAddSymbol(theEnv,"NIL")); + else + SetMFValue(result->value,3,EnvAddSymbol(theEnv,"INH")); + if (sp->initializeOnly) SetMFValue(result->value,4,EnvAddSymbol(theEnv,"INT")); else if (sp->noWrite) SetMFValue(result->value,4,EnvAddSymbol(theEnv,"R")); else SetMFValue(result->value,4,EnvAddSymbol(theEnv,"RW")); - SetMFValue(result->value,5,EnvAddSymbol(theEnv,(char *) (sp->shared ? "SHR" : "LCL"))); + + if (sp->shared) + SetMFValue(result->value,5,EnvAddSymbol(theEnv,"SHR")); + else + SetMFValue(result->value,5,EnvAddSymbol(theEnv,"LCL")); + #if DEFRULE_CONSTRUCT - SetMFValue(result->value,6,EnvAddSymbol(theEnv,(char *) (sp->reactive ? "RCT" : "NIL"))); - SetMFValue(result->value,7,EnvAddSymbol(theEnv,(char *) (sp->composite ? "CMP" : "EXC"))); - SetMFValue(result->value,8,EnvAddSymbol(theEnv,(char *) (sp->publicVisibility ? "PUB" : "PRV"))); + if (sp->reactive) + SetMFValue(result->value,6,EnvAddSymbol(theEnv,"RCT")); + else + SetMFValue(result->value,6,EnvAddSymbol(theEnv,"NIL")); + + if (sp->composite) + SetMFValue(result->value,7,EnvAddSymbol(theEnv,"CMP")); + else + SetMFValue(result->value,7,EnvAddSymbol(theEnv,"EXC")); + + if (sp->publicVisibility) + SetMFValue(result->value,8,EnvAddSymbol(theEnv,"PUB")); + else + SetMFValue(result->value,8,EnvAddSymbol(theEnv,"PRV")); + SetMFValue(result->value,9,EnvAddSymbol(theEnv,GetCreateAccessorString((void *) sp))); SetMFValue(result->value,10,sp->noWrite ? EnvAddSymbol(theEnv,"NIL") : (void *) sp->overrideMessage); #else - SetMFValue(result->value,6,EnvAddSymbol(theEnv,(char *) (sp->composite ? "CMP" : "EXC"))); - SetMFValue(result->value,7,EnvAddSymbol(theEnv,(char *) (sp->publicVisibility ? "PUB" : "PRV"))); + if (sp->composite) + SetMFValue(result->value,6,EnvAddSymbol(theEnv,"CMP")); + else + SetMFValue(result->value,6,EnvAddSymbol(theEnv,"EXC")); + + if (sp->publicVisibility) + SetMFValue(result->value,7,EnvAddSymbol(theEnv,"PUB")); + else + SetMFValue(result->value,7,EnvAddSymbol(theEnv,"PRV")); + SetMFValue(result->value,8,EnvAddSymbol(theEnv,GetCreateAccessorString((void *) sp))); SetMFValue(result->value,9,sp->noWrite ? EnvAddSymbol(theEnv,"NIL") : (void *) sp->overrideMessage); #endif @@ -700,7 +744,7 @@ globle void EnvSlotFacets( globle void EnvSlotSources( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register unsigned i; @@ -746,7 +790,7 @@ globle void EnvSlotSources( globle void EnvSlotTypes( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register unsigned i,j; @@ -828,7 +872,7 @@ DefclassData(theEnv)->PrimitiveClassMap[j])); globle void EnvSlotAllowedValues( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register int i; @@ -859,7 +903,7 @@ globle void EnvSlotAllowedValues( globle void EnvSlotAllowedClasses( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register int i; @@ -890,7 +934,7 @@ globle void EnvSlotAllowedClasses( globle void EnvSlotRange( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register SLOT_DESC *sp; @@ -919,7 +963,7 @@ globle void EnvSlotRange( globle void EnvSlotCardinality( void *theEnv, void *clsptr, - char *sname, + const char *sname, DATA_OBJECT *result) { register SLOT_DESC *sp; @@ -970,8 +1014,8 @@ globle void EnvSlotCardinality( static void SlotInfoSupportFunction( void *theEnv, DATA_OBJECT *result, - char *fnxname, - void (*fnx)(void *,void *,char *,DATA_OBJECT *)) + const char *fnxname, + void (*fnx)(void *,void *,const char *,DATA_OBJECT *)) { SYMBOL_HN *ssym; DEFCLASS *cls; @@ -1001,7 +1045,7 @@ static unsigned CountSubclasses( int inhp, int tvid) { - register unsigned i,cnt; + long i,cnt; register DEFCLASS *subcls; for (cnt = 0 , i = 0 ; i < cls->directSubclasses.classCount ; i++) @@ -1039,7 +1083,7 @@ static unsigned StoreSubclasses( int tvid, short storeName) { - register unsigned i,classi; + long i,classi; register DEFCLASS *subcls; for (i = si , classi = 0 ; classi < cls->directSubclasses.classCount ; classi++) @@ -1058,7 +1102,7 @@ static unsigned StoreSubclasses( SetMFType(mfval,i,DEFCLASS_PTR); SetMFValue(mfval,i++,(void *) subcls); } - + if (inhp && (subcls->directSubclasses.classCount != 0)) i += StoreSubclasses(mfval,i,subcls,inhp,tvid,storeName); } @@ -1084,8 +1128,8 @@ static SLOT_DESC *SlotInfoSlot( void *theEnv, DATA_OBJECT *result, DEFCLASS *cls, - char *sname, - char *fnxname) + const char *sname, + const char *fnxname) { SYMBOL_HN *ssym; int i; @@ -1109,4 +1153,115 @@ static SLOT_DESC *SlotInfoSlot( return(cls->instanceTemplate[i]); } +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool ClassAbstractP( + void *clsptr) + { + return EnvClassAbstractP(GetCurrentEnvironment(),clsptr); + } + +#if DEFRULE_CONSTRUCT +globle intBool ClassReactiveP( + void *clsptr) + { + return EnvClassReactiveP(GetCurrentEnvironment(),clsptr); + } +#endif + +globle void ClassSlots( + void *clsptr, + DATA_OBJECT *result, + int inhp) + { + EnvClassSlots(GetCurrentEnvironment(),clsptr,result,inhp); + } + +globle void ClassSubclasses( + void *clsptr, + DATA_OBJECT *result, + int inhp) + { + EnvClassSubclasses(GetCurrentEnvironment(),clsptr,result,inhp); + } + +globle void ClassSuperclasses( + void *clsptr, + DATA_OBJECT *result, + int inhp) + { + EnvClassSuperclasses(GetCurrentEnvironment(),clsptr,result,inhp); + } + +globle void SlotAllowedValues( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotAllowedValues(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotAllowedClasses( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotAllowedClasses(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotCardinality( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotCardinality(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotFacets( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotFacets(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotRange( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotRange(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotSources( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotSources(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void SlotTypes( + void *clsptr, + const char *sname, + DATA_OBJECT *result) + { + EnvSlotTypes(GetCurrentEnvironment(),clsptr,sname,result); + } + +globle void GetDefmessageHandlerList( + void *clsptr, + DATA_OBJECT *result, + int inhp) + { + EnvGetDefmessageHandlerList(GetCurrentEnvironment(),clsptr,result,inhp); + } + +#endif + + #endif diff --git a/src/classinf.h b/src/classinf.h index 839d26d..71a9d27 100644 --- a/src/classinf.h +++ b/src/classinf.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,15 +10,26 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_classinf @@ -38,70 +49,60 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define ClassAbstractP(theEnv,a) EnvClassAbstractP(theEnv,a) -#define ClassReactiveP(theEnv,a) EnvClassReactiveP(theEnv,a) -#define ClassSlots(theEnv,a,b,c) EnvClassSlots(theEnv,a,b,c) -#define ClassSubclasses(theEnv,a,b,c) EnvClassSubclasses(theEnv,a,b,c) -#define ClassSuperclasses(theEnv,a,b,c) EnvClassSuperclasses(theEnv,a,b,c) -#define SlotAllowedValues(theEnv,a,b,c) EnvSlotAllowedValues(theEnv,a,b,c) -#define SlotAllowedClasses(theEnv,a,b,c) EnvSlotAllowedClasses(theEnv,a,b,c) -#define SlotCardinality(theEnv,a,b,c) EnvSlotCardinality(theEnv,a,b,c) -#define SlotFacets(theEnv,a,b,c) EnvSlotFacets(theEnv,a,b,c) -#define SlotRange(theEnv,a,b,c) EnvSlotRange(theEnv,a,b,c) -#define SlotSources(theEnv,a,b,c) EnvSlotSources(theEnv,a,b,c) -#define SlotTypes(theEnv,a,b,c) EnvSlotTypes(theEnv,a,b,c) -#define GetDefmessageHandlerList(theEnv,a,b,c) EnvGetDefmessageHandlerList(theEnv,a,b,c) -#else -#define ClassAbstractP(a) EnvClassAbstractP(GetCurrentEnvironment(),a) -#define ClassReactiveP(a) EnvClassReactiveP(GetCurrentEnvironment(),a) -#define ClassSlots(a,b,c) EnvClassSlots(GetCurrentEnvironment(),a,b,c) -#define ClassSubclasses(a,b,c) EnvClassSubclasses(GetCurrentEnvironment(),a,b,c) -#define ClassSuperclasses(a,b,c) EnvClassSuperclasses(GetCurrentEnvironment(),a,b,c) -#define SlotAllowedValues(a,b,c) EnvSlotAllowedValues(GetCurrentEnvironment(),a,b,c) -#define SlotAllowedClasses(a,b,c) EnvSlotAllowedClasses(GetCurrentEnvironment(),a,b,c) -#define SlotCardinality(a,b,c) EnvSlotCardinality(GetCurrentEnvironment(),a,b,c) -#define SlotFacets(a,b,c) EnvSlotFacets(GetCurrentEnvironment(),a,b,c) -#define SlotRange(a,b,c) EnvSlotRange(GetCurrentEnvironment(),a,b,c) -#define SlotSources(a,b,c) EnvSlotSources(GetCurrentEnvironment(),a,b,c) -#define SlotTypes(a,b,c) EnvSlotTypes(GetCurrentEnvironment(),a,b,c) -#define GetDefmessageHandlerList(a,b,c) EnvGetDefmessageHandlerList(GetCurrentEnvironment(),a,b,c) -#endif - -LOCALE intBool ClassAbstractPCommand(void *); + LOCALE intBool ClassAbstractPCommand(void *); #if DEFRULE_CONSTRUCT -LOCALE intBool ClassReactivePCommand(void *); + LOCALE intBool ClassReactivePCommand(void *); #endif -LOCALE void *ClassInfoFnxArgs(void *,char *,int *); -LOCALE void ClassSlotsCommand(void *,DATA_OBJECT *); -LOCALE void ClassSuperclassesCommand(void *,DATA_OBJECT *); -LOCALE void ClassSubclassesCommand(void *,DATA_OBJECT *); -LOCALE void GetDefmessageHandlersListCmd(void *,DATA_OBJECT *); -LOCALE void SlotFacetsCommand(void *,DATA_OBJECT *); -LOCALE void SlotSourcesCommand(void *,DATA_OBJECT *); -LOCALE void SlotTypesCommand(void *,DATA_OBJECT *); -LOCALE void SlotAllowedValuesCommand(void *,DATA_OBJECT *); -LOCALE void SlotAllowedClassesCommand(void *,DATA_OBJECT *); -LOCALE void SlotRangeCommand(void *,DATA_OBJECT *); -LOCALE void SlotCardinalityCommand(void *,DATA_OBJECT *); -LOCALE intBool EnvClassAbstractP(void *,void *); + LOCALE void *ClassInfoFnxArgs(void *,const char *,int *); + LOCALE void ClassSlotsCommand(void *,DATA_OBJECT *); + LOCALE void ClassSuperclassesCommand(void *,DATA_OBJECT *); + LOCALE void ClassSubclassesCommand(void *,DATA_OBJECT *); + LOCALE void GetDefmessageHandlersListCmd(void *,DATA_OBJECT *); + LOCALE void SlotFacetsCommand(void *,DATA_OBJECT *); + LOCALE void SlotSourcesCommand(void *,DATA_OBJECT *); + LOCALE void SlotTypesCommand(void *,DATA_OBJECT *); + LOCALE void SlotAllowedValuesCommand(void *,DATA_OBJECT *); + LOCALE void SlotAllowedClassesCommand(void *,DATA_OBJECT *); + LOCALE void SlotRangeCommand(void *,DATA_OBJECT *); + LOCALE void SlotCardinalityCommand(void *,DATA_OBJECT *); + LOCALE intBool EnvClassAbstractP(void *,void *); #if DEFRULE_CONSTRUCT -LOCALE intBool EnvClassReactiveP(void *,void *); + LOCALE intBool EnvClassReactiveP(void *,void *); #endif -LOCALE void EnvClassSlots(void *,void *,DATA_OBJECT *,int); -LOCALE void EnvGetDefmessageHandlerList(void *,void *,DATA_OBJECT *,int); -LOCALE void EnvClassSuperclasses(void *,void *,DATA_OBJECT *,int); -LOCALE void EnvClassSubclasses(void *,void *,DATA_OBJECT *,int); -LOCALE void ClassSubclassAddresses(void *,void *,DATA_OBJECT *,int); -LOCALE void EnvSlotFacets(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotSources(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotTypes(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotAllowedValues(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotAllowedClasses(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotRange(void *,void *,char *,DATA_OBJECT *); -LOCALE void EnvSlotCardinality(void *,void *,char *,DATA_OBJECT *); + LOCALE void EnvClassSlots(void *,void *,DATA_OBJECT *,int); + LOCALE void EnvGetDefmessageHandlerList(void *,void *,DATA_OBJECT *,int); + LOCALE void EnvClassSuperclasses(void *,void *,DATA_OBJECT *,int); + LOCALE void EnvClassSubclasses(void *,void *,DATA_OBJECT *,int); + LOCALE void ClassSubclassAddresses(void *,void *,DATA_OBJECT *,int); + LOCALE void EnvSlotFacets(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotSources(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotTypes(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotAllowedValues(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotAllowedClasses(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotRange(void *,void *,const char *,DATA_OBJECT *); + LOCALE void EnvSlotCardinality(void *,void *,const char *,DATA_OBJECT *); + +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE intBool ClassAbstractP(void *); +#if DEFRULE_CONSTRUCT + LOCALE intBool ClassReactiveP(void *); #endif + LOCALE void ClassSlots(void *,DATA_OBJECT *,int); + LOCALE void ClassSubclasses(void *,DATA_OBJECT *,int); + LOCALE void ClassSuperclasses(void *,DATA_OBJECT *,int); + LOCALE void SlotAllowedValues(void *,const char *,DATA_OBJECT *); + LOCALE void SlotAllowedClasses(void *,const char *,DATA_OBJECT *); + LOCALE void SlotCardinality(void *,const char *,DATA_OBJECT *); + LOCALE void SlotFacets(void *,const char *,DATA_OBJECT *); + LOCALE void SlotRange(void *,const char *,DATA_OBJECT *); + LOCALE void SlotSources(void *,const char *,DATA_OBJECT *); + LOCALE void SlotTypes(void *,const char *,DATA_OBJECT *); + LOCALE void GetDefmessageHandlerList(void *,DATA_OBJECT *,int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_classinf */ diff --git a/src/classini.c b/src/classini.c index 4dbc405..b215c77 100644 --- a/src/classini.c +++ b/src/classini.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CLASS INITIALIZATION MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Defclass Initialization Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ @@ -26,6 +27,20 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /**************************************************************/ /* ========================================= @@ -77,6 +92,8 @@ #if DEFRULE_CONSTRUCT #include "objrtbld.h" +#include "objrtfnx.h" +#include "objrtmch.h" #endif #if RUN_TIME @@ -106,9 +123,11 @@ static void DeallocateDefclassData(void *); #if (! RUN_TIME) static void DestroyDefclassAction(void *,struct constructHeader *,void *); -static DEFCLASS *AddSystemClass(void *,char *,DEFCLASS *); +static DEFCLASS *AddSystemClass(void *,const char *,DEFCLASS *); static void *AllocateModule(void *); static void ReturnModule(void *,void *); +#else +static void SearchForHashedPatternNodes(void *,OBJECT_PATTERN_NODE *); #endif #if (! BLOAD_ONLY) && (! RUN_TIME) && DEFMODULE_CONSTRUCT @@ -132,17 +151,17 @@ static void UpdateDefclassesScope(void *); **********************************************************/ globle void SetupObjectSystem( void *theEnv) - { + { ENTITY_RECORD defclassEntityRecord = { "DEFCLASS_PTR", DEFCLASS_PTR,1,0,0, NULL,NULL,NULL,NULL,NULL, DecrementDefclassBusyCount, IncrementDefclassBusyCount, - NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL }; AllocateEnvironmentData(theEnv,DEFCLASS_DATA,sizeof(struct defclassData),NULL); AddEnvironmentCleanupFunction(theEnv,"defclasses",DeallocateDefclassData,-500); - memcpy(&DefclassData(theEnv)->DefclassEntityRecord,&defclassEntityRecord,sizeof(struct entityRecord)); + memcpy(&DefclassData(theEnv)->DefclassEntityRecord,&defclassEntityRecord,sizeof(struct entityRecord)); #if ! RUN_TIME DefclassData(theEnv)->ClassDefaultsMode = CONVENIENCE_MODE; @@ -180,7 +199,7 @@ globle void SetupObjectSystem( SetupObjectPatternStuff(theEnv); #endif } - + /***************************************************/ /* DeallocateDefclassData: Deallocates environment */ /* data for the defclass construct. */ @@ -188,13 +207,13 @@ globle void SetupObjectSystem( static void DeallocateDefclassData( void *theEnv) { -#if ! RUN_TIME +#if ! RUN_TIME SLOT_NAME *tmpSNPPtr, *nextSNPPtr; int i; struct defclassModule *theModuleItem; void *theModule; int bloaded = FALSE; - + #if BLOAD || BLOAD_AND_BSAVE if (Bloaded(theEnv)) bloaded = TRUE; #endif @@ -202,10 +221,10 @@ static void DeallocateDefclassData( /*=============================*/ /* Destroy all the defclasses. */ /*=============================*/ - + if (! bloaded) { - DoForAllConstructs(theEnv,DestroyDefclassAction,DefclassData(theEnv)->DefclassModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDefclassAction,DefclassData(theEnv)->DefclassModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; @@ -221,7 +240,7 @@ static void DeallocateDefclassData( /*==========================*/ /* Remove the class tables. */ /*==========================*/ - + if (! bloaded) { if (DefclassData(theEnv)->ClassIDMap != NULL) @@ -229,7 +248,7 @@ static void DeallocateDefclassData( genfree(theEnv,DefclassData(theEnv)->ClassIDMap,DefclassData(theEnv)->AvailClassID * sizeof(DEFCLASS *)); } } - + if (DefclassData(theEnv)->ClassTable != NULL) { genfree(theEnv,DefclassData(theEnv)->ClassTable,sizeof(DEFCLASS *) * CLASS_TABLE_HASH_SIZE); @@ -244,7 +263,7 @@ static void DeallocateDefclassData( for (i = 0; i < SLOT_NAME_TABLE_HASH_SIZE; i++) { tmpSNPPtr = DefclassData(theEnv)->SlotNameTable[i]; - + while (tmpSNPPtr != NULL) { nextSNPPtr = tmpSNPPtr->nxt; @@ -253,7 +272,7 @@ static void DeallocateDefclassData( } } } - + if (DefclassData(theEnv)->SlotNameTable != NULL) { genfree(theEnv,DefclassData(theEnv)->SlotNameTable,sizeof(SLOT_NAME *) * SLOT_NAME_TABLE_HASH_SIZE); @@ -263,7 +282,7 @@ static void DeallocateDefclassData( void *tmpexp; register unsigned int i; register int j; - + if (DefclassData(theEnv)->ClassTable != NULL) { for (j = 0 ; j < CLASS_TABLE_HASH_SIZE ; j++) @@ -282,31 +301,28 @@ static void DeallocateDefclassData( } #endif } - + #if ! RUN_TIME /*********************************************************/ /* DestroyDefclassAction: Action used to remove defclass */ /* as a result of DestroyEnvironment. */ /*********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDefclassAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif struct defclass *theDefclass = (struct defclass *) theConstruct; if (theDefclass == NULL) return; -#if (! BLOAD_ONLY) +#if (! BLOAD_ONLY) DestroyDefclass(theEnv,theDefclass); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -409,8 +425,27 @@ globle void ObjectsRunTimeInitialize( } } + SearchForHashedPatternNodes(theEnv,ObjectReteData(theEnv)->ObjectPatternNetworkPointer); } +/*******************************************************************/ +/* SearchForHashedPatternNodes: */ +/*******************************************************************/ +static void SearchForHashedPatternNodes( + void *theEnv, + OBJECT_PATTERN_NODE *theNode) + { + while (theNode != NULL) + { + if ((theNode->lastLevel != NULL) && (theNode->lastLevel->selector)) + { AddHashedPatternNode(theEnv,theNode->lastLevel,theNode,theNode->networkTest->type,theNode->networkTest->value); } + + SearchForHashedPatternNodes(theEnv,theNode->nextLevel); + + theNode = theNode->rightNode; + } + } + #else /*************************************************************** @@ -437,7 +472,7 @@ globle void CreateSystemClasses( #if DEFRULE_CONSTRUCT DEFCLASS *initialObject; #endif - + /* =================================== Add canonical slot name entries for the is-a and name fields - used for @@ -554,7 +589,7 @@ static void SetupDefclasses( #else NULL, #endif - EnvFindDefclass); + EnvFindDefclassInModule); DefclassData(theEnv)->DefclassConstruct = AddConstruct(theEnv,"defclass","defclasses", #if (! BLOAD_ONLY) && (! RUN_TIME) @@ -663,11 +698,11 @@ static void SetupDefclasses( *********************************************************/ static DEFCLASS *AddSystemClass( void *theEnv, - char *name, + const char *name, DEFCLASS *parent) { DEFCLASS *sys; - register unsigned i; + long i; char defaultScopeMap[1]; sys = NewClass(theEnv,(SYMBOL_HN *) EnvAddSymbol(theEnv,name)); @@ -700,7 +735,7 @@ static DEFCLASS *AddSystemClass( ClearBitString((void *) defaultScopeMap,(int) sizeof(char)); SetBitMap(defaultScopeMap,0); #if DEFMODULE_CONSTRUCT - sys->scopeMap = (BITMAP_HN *) AddBitMap(theEnv,(void *) defaultScopeMap,(int) sizeof(char)); + sys->scopeMap = (BITMAP_HN *) EnvAddBitMap(theEnv,(void *) defaultScopeMap,(int) sizeof(char)); IncrementBitMapCount(sys->scopeMap); #endif return(sys); @@ -709,10 +744,10 @@ static DEFCLASS *AddSystemClass( /***************************************************** NAME : AllocateModule DESCRIPTION : Creates and initializes a - list of deffunctions for a new module + list of defclasses for a new module INPUTS : None - RETURNS : The new deffunction module - SIDE EFFECTS : Deffunction module created + RETURNS : The new defclass module + SIDE EFFECTS : Defclass module created NOTES : None *****************************************************/ static void *AllocateModule( @@ -723,11 +758,11 @@ static void *AllocateModule( /*************************************************** NAME : ReturnModule - DESCRIPTION : Removes a deffunction module and - all associated deffunctions - INPUTS : The deffunction module + DESCRIPTION : Removes a defclass module and + all associated defclasses + INPUTS : The defclass module RETURNS : Nothing useful - SIDE EFFECTS : Module and deffunctions deleted + SIDE EFFECTS : Module and defclasses deleted NOTES : None ***************************************************/ static void ReturnModule( @@ -762,7 +797,7 @@ static void UpdateDefclassesScope( int newModuleID,count; char *newScopeMap; unsigned newScopeMapSize; - char *className; + const char *className; struct defmodule *matchModule; newModuleID = (int) ((struct defmodule *) EnvGetCurrentModule(theEnv))->bsaveID; @@ -784,7 +819,7 @@ static void UpdateDefclassesScope( else if (FindImportedConstruct(theEnv,"defclass",matchModule, className,&count,TRUE,NULL) != NULL) SetBitMap(newScopeMap,newModuleID); - theDefclass->scopeMap = (BITMAP_HN *) AddBitMap(theEnv,(void *) newScopeMap,newScopeMapSize); + theDefclass->scopeMap = (BITMAP_HN *) EnvAddBitMap(theEnv,(void *) newScopeMap,newScopeMapSize); IncrementBitMapCount(theDefclass->scopeMap); } rm(theEnv,(void *) newScopeMap,newScopeMapSize); diff --git a/src/classini.h b/src/classini.h index 3eccc0e..1f74bac 100644 --- a/src/classini.h +++ b/src/classini.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,33 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Corrected compilation errors for files */ +/* generated by constructs-to-c. DR0861 */ +/* */ +/* 6.24: Added allowed-classes slot facet. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Corrected code to remove run-time program */ +/* compiler warning. */ +/* */ +/* 6.30: Borland C (IBM_TBC) and Metrowerks CodeWarrior */ +/* (MAC_MCW, IBM_MCW) are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_classini diff --git a/src/classpsr.c b/src/classpsr.c index cf30850..d837152 100644 --- a/src/classpsr.c +++ b/src/classpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CLASS PARSER MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Parsing Routines for Defclass Construct */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ /* Converted INSTANCE_PATTERN_MATCHING to */ @@ -22,6 +23,22 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support to allow CreateClassScopeMap to */ +/* be used by other functions. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /**************************************************************/ /* ========================================= @@ -77,18 +94,15 @@ ========================================= ***************************************** */ -static intBool ValidClassName(void *,char *,DEFCLASS **); -static intBool ParseSimpleQualifier(void *,char *,char *,char *,char *,intBool *,intBool *); -static intBool ReadUntilClosingParen(void *,char *,struct token *); +static intBool ValidClassName(void *,const char *,DEFCLASS **); +static intBool ParseSimpleQualifier(void *,const char *,const char *,const char *,const char *,intBool *,intBool *); +static intBool ReadUntilClosingParen(void *,const char *,struct token *); static void AddClass(void *,DEFCLASS *); static void BuildSubclassLinks(void *,DEFCLASS *); static void FormInstanceTemplate(void *,DEFCLASS *); static void FormSlotNameMap(void *,DEFCLASS *); -static TEMP_SLOT_LINK *MergeSlots(void *,TEMP_SLOT_LINK *,DEFCLASS *,unsigned *,int); +static TEMP_SLOT_LINK *MergeSlots(void *,TEMP_SLOT_LINK *,DEFCLASS *,short *,int); static void PackSlots(void *,DEFCLASS *,TEMP_SLOT_LINK *); -#if DEFMODULE_CONSTRUCT -static void CreateClassScopeMap(void *,DEFCLASS *); -#endif static void CreatePublicSlotMessageHandlers(void *,DEFCLASS *); /* ========================================= @@ -145,7 +159,7 @@ static void CreatePublicSlotMessageHandlers(void *,DEFCLASS *); ***************************************************************************************/ globle int ParseDefclass( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *cname; DEFCLASS *cls; @@ -173,8 +187,8 @@ globle int ParseDefclass( #endif cname = GetConstructNameAndComment(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken,"defclass", - EnvFindDefclass,NULL,"#",TRUE, - TRUE,TRUE); + EnvFindDefclassInModule,NULL,"#",TRUE, + TRUE,TRUE,FALSE); if (cname == NULL) return(TRUE); @@ -288,7 +302,7 @@ globle int ParseDefclass( ========================================================================= */ if (roleSpecified == FALSE) { - if (preclist->classArray[1]->system && /* Change to cause */ + if (preclist->classArray[1]->system && /* Change to cause */ (DefclassData(theEnv)->ClassDefaultsMode == CONVENIENCE_MODE)) /* default role of */ { abstract = FALSE; } /* classes to be concrete. */ else @@ -298,7 +312,7 @@ globle int ParseDefclass( if (patternMatchSpecified == FALSE) { if ((preclist->classArray[1]->system) && /* Change to cause */ - (! abstract) && /* default pattern-match */ + (! abstract) && /* default pattern-match */ (DefclassData(theEnv)->ClassDefaultsMode == CONVENIENCE_MODE)) /* of classes to be */ { reactive = TRUE; } /* reactive. */ else @@ -386,10 +400,10 @@ globle int ParseDefclass( ***********************************************************/ static intBool ValidClassName( void *theEnv, - char *theClassName, + const char *theClassName, DEFCLASS **theDefclass) { - *theDefclass = (DEFCLASS *) EnvFindDefclass(theEnv,theClassName); + *theDefclass = (DEFCLASS *) EnvFindDefclassInModule(theEnv,theClassName); if (*theDefclass != NULL) { /* =================================== @@ -441,10 +455,10 @@ static intBool ValidClassName( ***************************************************************/ static intBool ParseSimpleQualifier( void *theEnv, - char *readSource, - char *classQualifier, - char *clearRelation, - char *setRelation, + const char *readSource, + const char *classQualifier, + const char *clearRelation, + const char *setRelation, intBool *alreadyTestedFlag, intBool *binaryFlag) { @@ -491,7 +505,7 @@ ParseSimpleQualifierError: ***************************************************/ static intBool ReadUntilClosingParen( void *theEnv, - char *readSource, + const char *readSource, struct token *inputToken) { int cnt = 1,lparen_read = FALSE; @@ -562,7 +576,7 @@ static void AddClass( form progeny links with all direct superclasses =============================================== */ cls->hashTableIndex = HashClass(GetDefclassNamePointer((void *) cls)); - ctmp = (DEFCLASS *) EnvFindDefclass(theEnv,EnvGetDefclassName(theEnv,(void *) cls)); + ctmp = (DEFCLASS *) EnvFindDefclassInModule(theEnv,EnvGetDefclassName(theEnv,(void *) cls)); if (ctmp != NULL) { @@ -600,7 +614,7 @@ static void AddClass( #if DEBUGGING_FUNCTIONS if (EnvGetConserveMemory(theEnv) == FALSE) - SetDefclassPPForm((void *) cls,CopyPPBuffer(theEnv)); + EnvSetDefclassPPForm(theEnv,(void *) cls,CopyPPBuffer(theEnv)); #endif #if DEFMODULE_CONSTRUCT @@ -609,7 +623,7 @@ static void AddClass( Create a bitmap indicating whether this class is in scope or not for every module ========================================= */ - CreateClassScopeMap(theEnv,cls); + cls->scopeMap = (BITMAP_HN *) CreateClassScopeMap(theEnv,cls); #endif @@ -635,7 +649,7 @@ static void BuildSubclassLinks( void *theEnv, DEFCLASS *cls) { - register unsigned i; + long i; for (i = 0 ; i < cls->directSuperclasses.classCount ; i++) AddClassLink(theEnv,&cls->directSuperclasses.classArray[i]->directSubclasses,cls,-1); @@ -657,8 +671,8 @@ static void FormInstanceTemplate( DEFCLASS *cls) { TEMP_SLOT_LINK *islots = NULL,*stmp; - unsigned scnt = 0; - register unsigned i; + short scnt = 0; + long i; /* ======================== Get direct class's slots @@ -717,7 +731,7 @@ static void FormSlotNameMap( void *theEnv, DEFCLASS *cls) { - register unsigned i; + long i; cls->maxSlotNameID = 0; cls->slotNameMap = NULL; @@ -752,7 +766,7 @@ static TEMP_SLOT_LINK *MergeSlots( void *theEnv, TEMP_SLOT_LINK *old, DEFCLASS *cls, - unsigned *scnt, + short *scnt, int src) { TEMP_SLOT_LINK *cur,*tmp; @@ -808,7 +822,7 @@ static void PackSlots( TEMP_SLOT_LINK *slots) { TEMP_SLOT_LINK *stmp,*sprv; - register unsigned i; + long i; stmp = slots; while (stmp != NULL) @@ -844,16 +858,17 @@ static void PackSlots( SIDE EFFECTS : Scope bitmap created and attached NOTES : Uses FindImportedConstruct() ********************************************************/ -static void CreateClassScopeMap( +globle void *CreateClassScopeMap( void *theEnv, DEFCLASS *theDefclass) { unsigned scopeMapSize; char *scopeMap; - char *className; + const char *className; struct defmodule *matchModule, *theModule; int moduleID,count; + void *theBitMap; className = ValueToString(theDefclass->header.name); matchModule = theDefclass->header.whichModule->theModule; @@ -874,9 +889,10 @@ static void CreateClassScopeMap( SetBitMap(scopeMap,moduleID); } RestoreCurrentModule(theEnv); - theDefclass->scopeMap = (BITMAP_HN *) AddBitMap(theEnv,scopeMap,scopeMapSize); - IncrementBitMapCount(theDefclass->scopeMap); + theBitMap = (BITMAP_HN *) EnvAddBitMap(theEnv,scopeMap,scopeMapSize); + IncrementBitMapCount(theBitMap); rm(theEnv,(void *) scopeMap,scopeMapSize); + return(theBitMap); } #endif @@ -911,7 +927,7 @@ static void CreatePublicSlotMessageHandlers( void *theEnv, DEFCLASS *theDefclass) { - register unsigned i; + long i; register SLOT_DESC *sd; for (i = 0 ; i < theDefclass->slotCount ; i++) diff --git a/src/classpsr.h b/src/classpsr.h index 3a0ccfa..dcf01cb 100644 --- a/src/classpsr.h +++ b/src/classpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,31 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.24: Added allowed-classes slot facet. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Added support to allow CreateClassScopeMap to */ +/* be used by other functions. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_classpsr @@ -33,7 +52,11 @@ #define LOCALE extern #endif -LOCALE int ParseDefclass(void *,char *); +LOCALE int ParseDefclass(void *,const char *); + +#if DEFMODULE_CONSTRUCT +LOCALE void *CreateClassScopeMap(void *,DEFCLASS *); +#endif #endif diff --git a/src/clips.h b/src/clips.h index 826ec23..ee78cc7 100644 --- a/src/clips.h +++ b/src/clips.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* API HEADER FILE */ /*******************************************************/ @@ -19,11 +19,19 @@ /* 6.24: Added filertr.h and tmpltfun.h to include */ /* list. */ /* */ +/* 6.30: Added classpsr.h, iofun.h, and strngrtr.h to */ +/* include list. */ +/* */ /*************************************************************/ #ifndef _H_API #define _H_API +#ifndef _STDIO_INCLUDED_ +#define _STDIO_INCLUDED_ +#include <stdio.h> +#endif + #include "setup.h" #ifndef _H_argacces #include "argacces.h" @@ -38,12 +46,12 @@ #ifndef _H_symbol #include "symbol.h" #endif -#ifndef _H_router + #include "router.h" -#endif -#ifndef _H_filertr #include "filertr.h" -#endif +#include "strngrtr.h" + +#include "iofun.h" #include "sysdep.h" #include "bmathfun.h" @@ -118,6 +126,7 @@ #include "classexm.h" #include "classinf.h" #include "classini.h" +#include "classpsr.h" #include "defins.h" #include "inscom.h" #include "insfile.h" diff --git a/src/clsltpsr.c b/src/clsltpsr.c index 1f4abbd..fac13b0 100644 --- a/src/clsltpsr.c +++ b/src/clsltpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CLASS PARSER MODULE */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Parsing Routines for Defclass Construct */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -21,6 +21,13 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /**************************************************************/ /* ========================================= @@ -112,12 +119,13 @@ static SLOT_DESC *NewSlot(void *,SYMBOL_HN *); static TEMP_SLOT_LINK *InsertSlot(void *,TEMP_SLOT_LINK *,SLOT_DESC *); -static int ParseSimpleFacet(void *,char *,char*,char *,int,char *,char *,char *,char *,SYMBOL_HN **); -static intBool ParseDefaultFacet(void *,char *,char *,SLOT_DESC *); -static void BuildCompositeFacets(void *,SLOT_DESC *,PACKED_CLASS_LINKS *,char *, +static int ParseSimpleFacet(void *,const char *,char*,const char *,int,const char *, + const char *,const char *,const char *,SYMBOL_HN **); +static intBool ParseDefaultFacet(void *,const char *,char *,SLOT_DESC *); +static void BuildCompositeFacets(void *,SLOT_DESC *,PACKED_CLASS_LINKS *,const char *, CONSTRAINT_PARSE_RECORD *); static intBool CheckForFacetConflicts(void *,SLOT_DESC *,CONSTRAINT_PARSE_RECORD *); -static intBool EvaluateSlotDefaultValue(void *,SLOT_DESC *,char *); +static intBool EvaluateSlotDefaultValue(void *,SLOT_DESC *,const char *); /* ========================================= ***************************************** @@ -146,7 +154,7 @@ static intBool EvaluateSlotDefaultValue(void *,SLOT_DESC *,char *); ************************************************************/ globle TEMP_SLOT_LINK *ParseSlot( void *theEnv, - char *readSource, + const char *readSource, TEMP_SLOT_LINK *slist, PACKED_CLASS_LINKS *preclist, int multiSlot, @@ -321,18 +329,18 @@ globle TEMP_SLOT_LINK *ParseSlot( SyntaxErrorMessage(theEnv,"defclass slot"); goto ParseSlotError; } - + if (DefclassData(theEnv)->ClassDefaultsMode == CONVENIENCE_MODE) { if (! TestBitMap(specbits,CREATE_ACCESSOR_BIT)) { slot->createReadAccessor = TRUE; - + if (! slot->noWrite) - { slot->createWriteAccessor = TRUE; } + { slot->createWriteAccessor = TRUE; } } } - + if (slot->composite) BuildCompositeFacets(theEnv,slot,preclist,specbits,&parsedConstraint); if (CheckForFacetConflicts(theEnv,slot,&parsedConstraint) == FALSE) @@ -519,14 +527,14 @@ static TEMP_SLOT_LINK *InsertSlot( *****************************************************************/ static int ParseSimpleFacet( void *theEnv, - char *readSource, + const char *readSource, char *specbits, - char *facetName, + const char *facetName, int testBit, - char *clearRelation, - char *setRelation, - char *alternateRelation, - char *varRelation, + const char *clearRelation, + const char *setRelation, + const char *alternateRelation, + const char *varRelation, SYMBOL_HN **facetSymbolicValue) { int rtnCode; @@ -604,7 +612,7 @@ ParseSimpleFacetError: *************************************************************/ static intBool ParseDefaultFacet( void *theEnv, - char *readSource, + const char *readSource, char *specbits, SLOT_DESC *slot) { @@ -673,11 +681,11 @@ static void BuildCompositeFacets( void *theEnv, SLOT_DESC *sd, PACKED_CLASS_LINKS *preclist, - char *specbits, + const char *specbits, CONSTRAINT_PARSE_RECORD *parsedConstraint) { SLOT_DESC *compslot = NULL; - register unsigned i; + long i; for (i = 1 ; i < preclist->classCount ; i++) { @@ -770,8 +778,8 @@ static intBool CheckForFacetConflicts( { ReturnExpression(theEnv,sd->constraint->minFields); ReturnExpression(theEnv,sd->constraint->maxFields); - sd->constraint->minFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1L)); - sd->constraint->maxFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1L)); + sd->constraint->minFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1LL)); + sd->constraint->maxFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1LL)); } } if (sd->noDefault && sd->noWrite) @@ -811,7 +819,7 @@ static intBool CheckForFacetConflicts( static intBool EvaluateSlotDefaultValue( void *theEnv, SLOT_DESC *sd, - char *specbits) + const char *specbits) { DATA_OBJECT temp; int oldce,olddcc,vCode; diff --git a/src/clsltpsr.h b/src/clsltpsr.h index fd18363..1c653ff 100644 --- a/src/clsltpsr.h +++ b/src/clsltpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,24 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ -/* Revision History: */ -/* */ +/* Revision History: */ +/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_clsltpsr @@ -47,7 +59,7 @@ typedef struct tempSlotLink #define LOCALE extern #endif -LOCALE TEMP_SLOT_LINK *ParseSlot(void *,char *,TEMP_SLOT_LINK *,PACKED_CLASS_LINKS *,int,int); +LOCALE TEMP_SLOT_LINK *ParseSlot(void *,const char *,TEMP_SLOT_LINK *,PACKED_CLASS_LINKS *,int,int); LOCALE void DeleteSlots(void *,TEMP_SLOT_LINK *); #ifndef _CLSLTPSR_SOURCE_ diff --git a/src/commline.c b/src/commline.c index 82bf30e..d3b4069 100644 --- a/src/commline.c +++ b/src/commline.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* COMMAND LINE MODULE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -24,6 +24,39 @@ /* additional functions for use by an interface */ /* layered on top of CLIPS. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Metrowerks CodeWarrior (MAC_MCW, IBM_MCW) is */ +/* no longer supported. */ +/* */ +/* UTF-8 support. */ +/* */ +/* Command history and editing support */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added before command execution callback */ +/* function. */ +/* */ +/* Fixed RouteCommand return value. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ #define _COMMLINE_SOURCE_ @@ -43,12 +76,14 @@ #include "exprnpsr.h" #include "filecom.h" #include "memalloc.h" +#include "multifld.h" #include "prcdrfun.h" #include "prcdrpsr.h" #include "router.h" #include "scanner.h" #include "strngrtr.h" #include "symbol.h" +#include "sysdep.h" #include "utility.h" #include "commline.h" @@ -58,9 +93,9 @@ /***************************************/ #if ! RUN_TIME - static int DoString(char *,int,int *); - static int DoComment(char *,int); - static int DoWhiteSpace(char *,int); + static int DoString(const char *,int,int *); + static int DoComment(const char *,int); + static int DoWhiteSpace(const char *,int); static int DefaultGetNextEvent(void *); #endif static void DeallocateCommandLineData(void *); @@ -74,12 +109,12 @@ globle void InitializeCommandLineData( { AllocateEnvironmentData(theEnv,COMMANDLINE_DATA,sizeof(struct commandLineData),DeallocateCommandLineData); -#if ! RUN_TIME +#if ! RUN_TIME CommandLineData(theEnv)->BannerString = BANNER_STRING; CommandLineData(theEnv)->EventFunction = DefaultGetNextEvent; #endif } - + /*******************************************************/ /* DeallocateCommandLineData: Deallocates environment */ /* data for the command line functionality. */ @@ -88,10 +123,13 @@ static void DeallocateCommandLineData( void *theEnv) { #if ! RUN_TIME - if (CommandLineData(theEnv)->CommandString != NULL) + if (CommandLineData(theEnv)->CommandString != NULL) { rm(theEnv,CommandLineData(theEnv)->CommandString,CommandLineData(theEnv)->MaximumCharacters); } + + if (CommandLineData(theEnv)->CurrentCommand != NULL) + { ReturnExpression(theEnv,CommandLineData(theEnv)->CurrentCommand); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -111,7 +149,7 @@ globle int ExpandCommandString( void *theEnv, int inchar) { - register int k; + size_t k; k = RouterData(theEnv)->CommandBufferInputCount; CommandLineData(theEnv)->CommandString = ExpandStringWithChar(theEnv,inchar,CommandLineData(theEnv)->CommandString,&RouterData(theEnv)->CommandBufferInputCount, @@ -129,6 +167,7 @@ globle void FlushCommandString( CommandLineData(theEnv)->CommandString = NULL; CommandLineData(theEnv)->MaximumCharacters = 0; RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; } /*********************************************************************************/ @@ -136,9 +175,9 @@ globle void FlushCommandString( /*********************************************************************************/ globle void SetCommandString( void *theEnv, - char *str) + const char *str) { - unsigned length; + size_t length; FlushCommandString(theEnv); length = strlen(str); @@ -146,7 +185,7 @@ globle void SetCommandString( genrealloc(theEnv,CommandLineData(theEnv)->CommandString,(unsigned) CommandLineData(theEnv)->MaximumCharacters, (unsigned) CommandLineData(theEnv)->MaximumCharacters + length + 1); - strcpy(CommandLineData(theEnv)->CommandString,str); + genstrcpy(CommandLineData(theEnv)->CommandString,str); CommandLineData(theEnv)->MaximumCharacters += (length + 1); RouterData(theEnv)->CommandBufferInputCount += (int) length; } @@ -157,7 +196,7 @@ globle void SetCommandString( /*************************************************************/ globle void SetNCommandString( void *theEnv, - char *str, + const char *str, unsigned length) { FlushCommandString(theEnv); @@ -165,7 +204,7 @@ globle void SetNCommandString( genrealloc(theEnv,CommandLineData(theEnv)->CommandString,(unsigned) CommandLineData(theEnv)->MaximumCharacters, (unsigned) CommandLineData(theEnv)->MaximumCharacters + length + 1); - strncpy(CommandLineData(theEnv)->CommandString,str,length); + genstrncpy(CommandLineData(theEnv)->CommandString,str,length); CommandLineData(theEnv)->CommandString[CommandLineData(theEnv)->MaximumCharacters + length] = 0; CommandLineData(theEnv)->MaximumCharacters += (length + 1); RouterData(theEnv)->CommandBufferInputCount += (int) length; @@ -176,18 +215,31 @@ globle void SetNCommandString( /******************************************************************************/ globle void AppendCommandString( void *theEnv, - char *str) + const char *str) { CommandLineData(theEnv)->CommandString = AppendToString(theEnv,str,CommandLineData(theEnv)->CommandString,&RouterData(theEnv)->CommandBufferInputCount,&CommandLineData(theEnv)->MaximumCharacters); } +/******************************************************************************/ +/* InsertCommandString: Inserts a value in the contents of the CommandString. */ +/******************************************************************************/ +globle void InsertCommandString( + void *theEnv, + const char *str, + unsigned int position) + { + CommandLineData(theEnv)->CommandString = + InsertInString(theEnv,str,position,CommandLineData(theEnv)->CommandString, + &RouterData(theEnv)->CommandBufferInputCount,&CommandLineData(theEnv)->MaximumCharacters); + } + /************************************************************/ /* AppendNCommandString: Appends a value up to N characters */ /* to the contents of the CommandString. */ /************************************************************/ globle void AppendNCommandString( void *theEnv, - char *str, + const char *str, unsigned length) { CommandLineData(theEnv)->CommandString = AppendNToString(theEnv,str,CommandLineData(theEnv)->CommandString,length,&RouterData(theEnv)->CommandBufferInputCount,&CommandLineData(theEnv)->MaximumCharacters); @@ -213,7 +265,7 @@ globle char *GetCommandString( /* contains an error. */ /**************************************************************************/ globle int CompleteCommand( - char *mstring) + const char *mstring) { int i; char inchar; @@ -327,7 +379,7 @@ globle int CompleteCommand( default: if (depth == 0) { - if (isprint(inchar)) + if (isprint(inchar) || IsUTF8MultiByteStart(inchar)) { while ((inchar = mstring[i++]) != EOS) { @@ -356,7 +408,7 @@ globle int CompleteCommand( /* until the closing quotation mark is encountered. */ /***********************************************************/ static int DoString( - char *str, + const char *str, int pos, int *complete) { @@ -417,7 +469,7 @@ static int DoString( /* until a line feed or carriage return is encountered. */ /*************************************************************/ static int DoComment( - char *str, + const char *str, int pos) { int inchar; @@ -440,7 +492,7 @@ static int DoComment( /* tabs, and form feeds that is contained within a string. */ /**************************************************************/ static int DoWhiteSpace( - char *str, + const char *str, int pos) { int inchar; @@ -468,9 +520,13 @@ globle void CommandLoop( EnvPrintRouter(theEnv,WPROMPT,CommandLineData(theEnv)->BannerString); SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); - PeriodicCleanup(theEnv,TRUE,FALSE); + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; while (TRUE) { @@ -482,7 +538,7 @@ globle void CommandLoop( if (BatchActive(theEnv) == TRUE) { - inchar = LLGetcBatch(theEnv,"stdin",TRUE); + inchar = LLGetcBatch(theEnv,STDIN,TRUE); if (inchar == EOF) { (*CommandLineData(theEnv)->EventFunction)(theEnv); } else @@ -516,7 +572,7 @@ globle void CommandLoop( ExecuteIfCommandComplete(theEnv); } } - + /***********************************************************/ /* CommandLoopBatch: Loop which waits for commands from a */ /* batch file and then executes them. Returns when there */ @@ -527,9 +583,13 @@ globle void CommandLoopBatch( { SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); - PeriodicCleanup(theEnv,TRUE,FALSE); + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + PrintPrompt(theEnv); RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; CommandLoopBatchDriver(theEnv); } @@ -546,7 +606,7 @@ globle void CommandLoopOnceThenBatch( CommandLoopBatchDriver(theEnv); } - + /*********************************************************/ /* CommandLoopBatchDriver: Loop which waits for commands */ /* from a batch file and then executes them. Returns */ @@ -560,11 +620,11 @@ globle void CommandLoopBatchDriver( while (TRUE) { if (GetHaltCommandLoopBatch(theEnv) == TRUE) - { + { CloseAllBatchSources(theEnv); SetHaltCommandLoopBatch(theEnv,FALSE); } - + /*===================================================*/ /* If a batch file is active, grab the command input */ /* directly from the batch file, otherwise call the */ @@ -573,7 +633,7 @@ globle void CommandLoopBatchDriver( if (BatchActive(theEnv) == TRUE) { - inchar = LLGetcBatch(theEnv,"stdin",TRUE); + inchar = LLGetcBatch(theEnv,STDIN,TRUE); if (inchar == EOF) { return; } else @@ -615,22 +675,32 @@ globle void CommandLoopBatchDriver( globle intBool ExecuteIfCommandComplete( void *theEnv) { - if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || - (RouterData(theEnv)->CommandBufferInputCount <= 0)) + if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || + (RouterData(theEnv)->CommandBufferInputCount == 0) || + (RouterData(theEnv)->AwaitingInput == FALSE)) { return FALSE; } - + + if (CommandLineData(theEnv)->BeforeCommandExecutionFunction != NULL) + { + if (! (*CommandLineData(theEnv)->BeforeCommandExecutionFunction)(theEnv)) + { return FALSE; } + } + FlushPPBuffer(theEnv); SetPPBufferStatus(theEnv,OFF); - RouterData(theEnv)->CommandBufferInputCount = -1; + RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = FALSE; RouteCommand(theEnv,CommandLineData(theEnv)->CommandString,TRUE); FlushPPBuffer(theEnv); SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); FlushCommandString(theEnv); - FlushBindList(theEnv); - PeriodicCleanup(theEnv,TRUE,FALSE); + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + PrintPrompt(theEnv); - + return TRUE; } @@ -640,13 +710,14 @@ globle intBool ExecuteIfCommandComplete( globle intBool CommandCompleteAndNotEmpty( void *theEnv) { - if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || - (RouterData(theEnv)->CommandBufferInputCount <= 0)) + if ((CompleteCommand(CommandLineData(theEnv)->CommandString) == 0) || + (RouterData(theEnv)->CommandBufferInputCount == 0) || + (RouterData(theEnv)->AwaitingInput == FALSE)) { return FALSE; } - + return TRUE; } - + /*******************************************/ /* PrintPrompt: Prints the command prompt. */ /*******************************************/ @@ -679,18 +750,31 @@ globle void SetAfterPromptFunction( CommandLineData(theEnv)->AfterPromptFunction = funptr; } -/************************************************/ -/* RouteCommand: Processes a completed command. */ -/************************************************/ +/***********************************************************/ +/* SetBeforeCommandExecutionFunction: Replaces the current */ +/* value of BeforeCommandExecutionFunction. */ +/***********************************************************/ +globle void SetBeforeCommandExecutionFunction( + void *theEnv, + int (*funptr)(void *)) + { + CommandLineData(theEnv)->BeforeCommandExecutionFunction = funptr; + } + +/********************************************************/ +/* RouteCommand: Processes a completed command. Returns */ +/* 1 if a command could be parsed, otherwise 0. */ +/********************************************************/ globle intBool RouteCommand( void *theEnv, - char *command, + const char *command, int printResult) { DATA_OBJECT result; struct expr *top; - char *commandName; + const char *commandName; struct token theToken; + int danglingConstructs; if (command == NULL) { return(0); } @@ -715,17 +799,19 @@ globle intBool RouteCommand( CloseStringSource(theEnv,"command"); if (printResult) { - PrintAtom(theEnv,"stdout",theToken.type,theToken.value); - EnvPrintRouter(theEnv,"stdout","\n"); + PrintAtom(theEnv,STDOUT,theToken.type,theToken.value); + EnvPrintRouter(theEnv,STDOUT,"\n"); } return(1); } - /*============================*/ - /* Evaluate global variables. */ - /*============================*/ + /*=====================*/ + /* Evaluate variables. */ + /*=====================*/ - if (theToken.type == GBL_VARIABLE) + if ((theToken.type == GBL_VARIABLE) || + (theToken.type == SF_VARIABLE) || + (theToken.type == MF_VARIABLE)) { CloseStringSource(theEnv,"command"); top = GenConstant(theEnv,theToken.type,theToken.value); @@ -733,8 +819,8 @@ globle intBool RouteCommand( rtn_struct(theEnv,expr,top); if (printResult) { - PrintDataObject(theEnv,"stdout",&result); - EnvPrintRouter(theEnv,"stdout","\n"); + PrintDataObject(theEnv,STDOUT,&result); + EnvPrintRouter(theEnv,STDOUT,"\n"); } return(1); } @@ -748,7 +834,7 @@ globle intBool RouteCommand( if (theToken.type != LPAREN) { PrintErrorID(theEnv,"COMMLINE",1,FALSE); - EnvPrintRouter(theEnv,WERROR,"Expected a '(', constant, or global variable\n"); + EnvPrintRouter(theEnv,WERROR,"Expected a '(', constant, or variable\n"); CloseStringSource(theEnv,"command"); return(0); } @@ -787,7 +873,8 @@ globle intBool RouteCommand( EnvPrintRouter(theEnv,WERROR,"\n"); } DestroyPPBuffer(theEnv); - return(errorFlag); + if (errorFlag) return 0; + else return 1; } } #endif @@ -796,6 +883,7 @@ globle intBool RouteCommand( /* Parse a function call. */ /*========================*/ + danglingConstructs = ConstructData(theEnv)->DanglingConstructs; CommandLineData(theEnv)->ParsingTopLevelCommand = TRUE; top = Function2Parse(theEnv,"command",commandName); CommandLineData(theEnv)->ParsingTopLevelCommand = FALSE; @@ -811,18 +899,32 @@ globle intBool RouteCommand( /* Evaluate function call. */ /*=========================*/ - if (top == NULL) return(0); - CommandLineData(theEnv)->EvaluatingTopLevelCommand = TRUE; + if (top == NULL) + { + ConstructData(theEnv)->DanglingConstructs = danglingConstructs; + return(0); + } + ExpressionInstall(theEnv,top); + + CommandLineData(theEnv)->EvaluatingTopLevelCommand = TRUE; + CommandLineData(theEnv)->CurrentCommand = top; EvaluateExpression(theEnv,top,&result); - ExpressionDeinstall(theEnv,top); + CommandLineData(theEnv)->CurrentCommand = NULL; CommandLineData(theEnv)->EvaluatingTopLevelCommand = FALSE; + + ExpressionDeinstall(theEnv,top); ReturnExpression(theEnv,top); + ConstructData(theEnv)->DanglingConstructs = danglingConstructs; + + /*=================================================*/ + /* Print the return value of the function/command. */ + /*=================================================*/ if ((result.type != RVOID) && printResult) { - PrintDataObject(theEnv,"stdout",&result); - EnvPrintRouter(theEnv,"stdout","\n"); + PrintDataObject(theEnv,STDOUT,&result); + EnvPrintRouter(theEnv,STDOUT,"\n"); } return(1); @@ -839,12 +941,12 @@ static int DefaultGetNextEvent( { int inchar; - inchar = EnvGetcRouter(theEnv,"stdin"); + inchar = EnvGetcRouter(theEnv,STDIN); if (inchar == EOF) inchar = '\n'; ExpandCommandString(theEnv,(char) inchar); - + return 0; } @@ -875,16 +977,16 @@ globle intBool TopLevelCommand( /* GetCommandCompletionString: Returns the last token in a */ /* string if it is a valid token for command completion. */ /***********************************************************/ -globle char *GetCommandCompletionString( +globle const char *GetCommandCompletionString( void *theEnv, - char *theString, - unsigned maxPosition) + const char *theString, + size_t maxPosition) { struct token lastToken; struct token theToken; char lastChar; - char *rs; - unsigned length; + const char *rs; + size_t length; /*=========================*/ /* Get the command string. */ @@ -953,8 +1055,8 @@ globle char *GetCommandCompletionString( globle void SetHaltCommandLoopBatch( void *theEnv, int value) - { - CommandLineData(theEnv)->HaltCommandLoopBatch = value; + { + CommandLineData(theEnv)->HaltCommandLoopBatch = value; } /*******************************************************************/ diff --git a/src/commline.h b/src/commline.h index a61ced8..383c961 100644 --- a/src/commline.h +++ b/src/commline.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* COMMAND LINE HEADER FILE */ /*******************************************************/ @@ -23,6 +23,32 @@ /* additional functions for use by an interface */ /* layered on top of CLIPS. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Metrowerks CodeWarrior (MAC_MCW, IBM_MCW) is */ +/* no longer supported. */ +/* */ +/* UTF-8 support. */ +/* */ +/* Command history and editing support */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added before command execution callback */ +/* function. */ +/* */ +/* Fixed RouteCommand return value. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_commline @@ -32,16 +58,18 @@ #define COMMANDLINE_DATA 40 struct commandLineData - { + { int EvaluatingTopLevelCommand; int HaltCommandLoopBatch; #if ! RUN_TIME + struct expr *CurrentCommand; char *CommandString; - unsigned MaximumCharacters; + size_t MaximumCharacters; int ParsingTopLevelCommand; - char *BannerString; + const char *BannerString; int (*EventFunction)(void *); int (*AfterPromptFunction)(void *); + int (*BeforeCommandExecutionFunction)(void *); #endif }; @@ -60,22 +88,24 @@ struct commandLineData LOCALE void InitializeCommandLineData(void *); LOCALE int ExpandCommandString(void *,int); LOCALE void FlushCommandString(void *); - LOCALE void SetCommandString(void *,char *); - LOCALE void AppendCommandString(void *,char *); + LOCALE void SetCommandString(void *,const char *); + LOCALE void AppendCommandString(void *,const char *); + LOCALE void InsertCommandString(void *,const char *,unsigned); LOCALE char *GetCommandString(void *); - LOCALE int CompleteCommand(char *); + LOCALE int CompleteCommand(const char *); LOCALE void CommandLoop(void *); LOCALE void CommandLoopBatch(void *); LOCALE void CommandLoopBatchDriver(void *); LOCALE void PrintPrompt(void *); LOCALE void PrintBanner(void *); LOCALE void SetAfterPromptFunction(void *,int (*)(void *)); - LOCALE intBool RouteCommand(void *,char *,int); + LOCALE void SetBeforeCommandExecutionFunction(void *,int (*)(void *)); + LOCALE intBool RouteCommand(void *,const char *,int); LOCALE int (*SetEventFunction(void *,int (*)(void *)))(void *); LOCALE intBool TopLevelCommand(void *); - LOCALE void AppendNCommandString(void *,char *,unsigned); - LOCALE void SetNCommandString(void *,char *,unsigned); - LOCALE char *GetCommandCompletionString(void *,char *,unsigned); + LOCALE void AppendNCommandString(void *,const char *,unsigned); + LOCALE void SetNCommandString(void *,const char *,unsigned); + LOCALE const char *GetCommandCompletionString(void *,const char *,size_t); LOCALE intBool ExecuteIfCommandComplete(void *); LOCALE void CommandLoopOnceThenBatch(void *); LOCALE intBool CommandCompleteAndNotEmpty(void *); diff --git a/src/conscomp.c b/src/conscomp.c index 794e950..9c6500d 100644 --- a/src/conscomp.c +++ b/src/conscomp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/04/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONSTRUCT COMPILER MODULE */ /*******************************************************/ @@ -12,12 +12,13 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* Barry Cameron */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Modifications to use the system constant */ /* FILENAME_MAX to check file name lengths. */ /* DR0856 */ @@ -37,6 +38,22 @@ /* Support for run-time programs directly passing */ /* the hash tables for initialization. */ /* */ +/* 6.30: Added path name argument to constructs-to-c. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, MAC_MCW, */ +/* IBM_TBC, IBM_MSC, IBM_ICB, IBM_ZTC, and */ +/* IBM_SC). */ +/* */ +/* Use genstrcpy instead of strcpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _CONSCOMP_SOURCE_ @@ -94,7 +111,7 @@ /* DEFINITIONS */ /***************/ -#define FSIZE 80 +#define EXTRA_FILE_NAME 20 /**********************************************/ /* CONSTRUCT CODES DEFINITIONS: The codes F, */ @@ -121,10 +138,10 @@ /***************************************/ void ConstructsToCCommand(void *); - static int ConstructsToC(void *,char *,int,int); + static int ConstructsToC(void *,const char *,const char *,char *,long long,long long); static void WriteFunctionExternDeclarations(void *,FILE *); - static int FunctionsToCode(void *theEnv,char *); - static int WriteInitializationFunction(void *,char *); + static int FunctionsToCode(void *theEnv,const char *,const char *,char *); + static int WriteInitializationFunction(void *,const char *,const char *,char *); static void DumpExpression(void *,struct expr *); static void MarkConstruct(void *,struct constructHeader *,void *); static void HashedExpressionsToCode(void *); @@ -138,11 +155,11 @@ globle void InitializeConstructCompilerData( void *theEnv) { AllocateEnvironmentData(theEnv,CONSTRUCT_COMPILER_DATA,sizeof(struct constructCompilerData),DeallocateConstructCompilerData); - + ConstructCompilerData(theEnv)->MaxIndices = 2000; ConstructCompilerData(theEnv)->CodeGeneratorCount = 0; } - + /************************************************************/ /* DeallocateConstructCompilerData: Deallocates environment */ /* data for the constructs-to-c command. */ @@ -152,7 +169,7 @@ static void DeallocateConstructCompilerData( { struct CodeGeneratorItem *tmpPtr, *nextPtr; int i; - + tmpPtr = ConstructCompilerData(theEnv)->ListOfCodeGeneratorItems; while (tmpPtr != NULL) { @@ -160,10 +177,10 @@ static void DeallocateConstructCompilerData( for (i = 0; i < tmpPtr->arrayCount ; i++) { rm(theEnv,tmpPtr->arrayNames[i],strlen(tmpPtr->arrayNames[i]) + 1); } - + if (tmpPtr->arrayCount != 0) { rm(theEnv,tmpPtr->arrayNames,sizeof(char *) * tmpPtr->arrayCount); } - + rtn_struct(theEnv,CodeGeneratorItem,tmpPtr); tmpPtr = nextPtr; } @@ -176,11 +193,14 @@ static void DeallocateConstructCompilerData( globle void ConstructsToCCommand( void *theEnv) { - char *fileName; + const char *fileName; + char *fileNameBuffer; + const char *pathName; DATA_OBJECT theArg; int argCount; - int id, max, nameLength; -#if VAX_VMS || IBM_MSC || IBM_TBC || IBM_ICB || IBM_ZTC || IBM_SC + long long id, max; + int nameLength, pathLength; +#if VAX_VMS || WIN_MVC int i; #endif @@ -188,7 +208,7 @@ globle void ConstructsToCCommand( /* Check for appropriate number of arguments. */ /*============================================*/ - if ((argCount = EnvArgRangeCheck(theEnv,"constructs-to-c",2,3)) == -1) return; + if ((argCount = EnvArgRangeCheck(theEnv,"constructs-to-c",2,4)) == -1) return; /*====================================================*/ /* Get the name of the file in which to place C code. */ @@ -205,7 +225,7 @@ globle void ConstructsToCCommand( /* PCs can't contain a period. */ /*================================*/ -#if VAX_VMS || IBM_MSC || IBM_TBC || IBM_ICB || IBM_ZTC || IBM_SC +#if VAX_VMS || WIN_MVC for (i = 0 ; *(fileName+i) ; i++) { if (*(fileName+i) == '.') @@ -227,7 +247,7 @@ globle void ConstructsToCCommand( /* characters is less than the supported maximum. */ /*==========================================================*/ - if ((nameLength + 20) > FILENAME_MAX) + if ((nameLength + EXTRA_FILE_NAME) > FILENAME_MAX) { PrintErrorID(theEnv,"CONSCOMP",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Aborting because the base file name may cause the fopen maximum of "); @@ -258,28 +278,46 @@ globle void ConstructsToCCommand( if (EnvArgTypeCheck(theEnv,"constructs-to-c",2,INTEGER,&theArg) == FALSE) { return; } - id = DOToInteger(theArg); + id = DOToLong(theArg); if (id < 0) { ExpectedTypeError1(theEnv,"constructs-to-c",2,"positive integer"); return; } + /*==================================================*/ + /* Get the path name argument if one was specified. */ + /*==================================================*/ + + if (argCount == 3) + { + if (EnvArgTypeCheck(theEnv,"constructs-to-c",3,SYMBOL_OR_STRING,&theArg) == FALSE) + { return; } + + pathName = DOToString(theArg); + pathLength = (int) strlen(pathName); + } + else + { + pathName = ""; + pathLength = 0; + } + /*===========================================*/ /* Get the maximum number of data structures */ /* to store per file argument (if supplied). */ /*===========================================*/ - if (argCount == 3) + if (argCount == 4) { - if (EnvArgTypeCheck(theEnv,"constructs-to-c",3,INTEGER,&theArg) == FALSE) + if (EnvArgTypeCheck(theEnv,"constructs-to-c",4,INTEGER,&theArg) == FALSE) { return; } - max = DOToInteger(theArg); + max = DOToLong(theArg); if (max < 0) { - ExpectedTypeError1(theEnv,"constructs-to-c",3,"positive integer"); + ExpectedTypeError1(theEnv,"constructs-to-c",4,"positive integer"); return; } } @@ -291,7 +329,11 @@ globle void ConstructsToCCommand( /* generate the C code. */ /*============================*/ - ConstructsToC(theEnv,fileName,id,max); + fileNameBuffer = (char *) genalloc(theEnv,nameLength + pathLength + EXTRA_FILE_NAME); + + ConstructsToC(theEnv,fileName,pathName,fileNameBuffer,id,max); + + genfree(theEnv,fileNameBuffer,nameLength + pathLength + EXTRA_FILE_NAME); } /***************************************/ @@ -300,11 +342,12 @@ globle void ConstructsToCCommand( /***************************************/ static int ConstructsToC( void *theEnv, - char *fileName, - int theImageID, - int max) + const char *fileName, + const char *pathName, + char *fileNameBuffer, + long long theImageID, + long long max) { - char fname[FILENAME_MAX+1]; int fileVersion; struct CodeGeneratorItem *cgPtr; @@ -314,7 +357,29 @@ static int ConstructsToC( /* in each file. */ /*===============================================*/ - ConstructCompilerData(theEnv)->MaxIndices = max; + ConstructCompilerData(theEnv)->MaxIndices = (int) max; /* TBD */ + + /*=====================================================*/ + /* Open a header file for dumping general information. */ + /*=====================================================*/ + + gensprintf(fileNameBuffer,"%s%s.h",pathName,fileName); + if ((ConstructCompilerData(theEnv)->HeaderFP = GenOpen(theEnv,fileNameBuffer,"w")) == NULL) + { + OpenErrorMessage(theEnv,"constructs-to-c",fileNameBuffer); + return(0); + } + + /*============================================*/ + /* Open a file for dumping fixup information. */ + /*============================================*/ + + gensprintf(fileNameBuffer,"%s%s_init.c",pathName,fileName); + if ((ConstructCompilerData(theEnv)->FixupFP = GenOpen(theEnv,fileNameBuffer,"w")) == NULL) + { + OpenErrorMessage(theEnv,"constructs-to-c",fileNameBuffer); + return(0); + } /*==================================*/ /* Call the list of functions to be */ @@ -326,36 +391,19 @@ static int ConstructsToC( cgPtr = cgPtr->next) { if (cgPtr->beforeFunction != NULL) (*cgPtr->beforeFunction)(theEnv); } - /*=================================================*/ - /* Do a periodic cleanup without using heuristics */ - /* to get rid of as much garbage as possible so */ - /* that it isn't written out as C data structures. */ - /*=================================================*/ - - PeriodicCleanup(theEnv,FALSE,FALSE); - /*=====================================*/ /* Initialize some global information. */ /*=====================================*/ ConstructCompilerData(theEnv)->FilePrefix = fileName; - ConstructCompilerData(theEnv)->ImageID = theImageID; + ConstructCompilerData(theEnv)->PathName = pathName; + ConstructCompilerData(theEnv)->FileNameBuffer = fileNameBuffer; + ConstructCompilerData(theEnv)->ImageID = (int) theImageID; /* TBD */ ConstructCompilerData(theEnv)->ExpressionFP = NULL; ConstructCompilerData(theEnv)->ExpressionVersion = 1; ConstructCompilerData(theEnv)->ExpressionHeader = TRUE; ConstructCompilerData(theEnv)->ExpressionCount = 0; - /*=====================================================*/ - /* Open a header file for dumping general information. */ - /*=====================================================*/ - - sprintf(fname,"%s.h",fileName); - if ((ConstructCompilerData(theEnv)->HeaderFP = GenOpen(theEnv,fname,"w")) == NULL) - { - OpenErrorMessage(theEnv,"constructs-to-c",fname); - return(0); - } - fprintf(ConstructCompilerData(theEnv)->HeaderFP,"#ifndef _CONSTRUCT_COMPILER_HEADER_\n"); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"#define _CONSTRUCT_COMPILER_HEADER_\n\n"); @@ -378,20 +426,13 @@ static int ConstructsToC( fprintf(ConstructCompilerData(theEnv)->HeaderFP,"/* EXTERN ARRAY DEFINITIONS */\n"); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"/****************************/\n\n"); - /*============================================*/ - /* Open a file for dumping fixup information. */ - /*============================================*/ - - sprintf(fname,"%s_init.c",fileName); - if ((ConstructCompilerData(theEnv)->FixupFP = GenOpen(theEnv,fname,"w")) == NULL) - { - OpenErrorMessage(theEnv,"constructs-to-c",fname); - return(0); - } + /*================================================*/ + /* Write out the first portion of the fixup file. */ + /*================================================*/ fprintf(ConstructCompilerData(theEnv)->FixupFP,"#include \"%s.h\"\n",fileName); fprintf(ConstructCompilerData(theEnv)->FixupFP,"\n"); - + fprintf(ConstructCompilerData(theEnv)->FixupFP,"\n"); fprintf(ConstructCompilerData(theEnv)->FixupFP,"/**********************************/\n"); fprintf(ConstructCompilerData(theEnv)->FixupFP,"/* CONSTRUCT IMAGE FIXUP FUNCTION */\n"); @@ -407,13 +448,16 @@ static int ConstructsToC( /* expressions, and constructs. */ /*==================================*/ - AtomicValuesToCode(theEnv,fileName); + AtomicValuesToCode(theEnv,fileName,pathName,fileNameBuffer); - FunctionsToCode(theEnv,fileName); + FunctionsToCode(theEnv,fileName,pathName,fileNameBuffer); HashedExpressionsToCode(theEnv); - ConstraintsToCode(theEnv,fileName,4,ConstructCompilerData(theEnv)->HeaderFP,ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->MaxIndices); + ConstraintsToCode(theEnv,fileName,pathName,fileNameBuffer,4, + ConstructCompilerData(theEnv)->HeaderFP, + ConstructCompilerData(theEnv)->ImageID, + ConstructCompilerData(theEnv)->MaxIndices); /*===============================*/ /* Call each code generator item */ @@ -427,7 +471,7 @@ static int ConstructsToC( { if (cgPtr->generateFunction != NULL) { - (*cgPtr->generateFunction)(theEnv,fileName,fileVersion,ConstructCompilerData(theEnv)->HeaderFP,ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->MaxIndices); + (*cgPtr->generateFunction)(theEnv,fileName,pathName,fileNameBuffer,fileVersion,ConstructCompilerData(theEnv)->HeaderFP,ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->MaxIndices); fileVersion++; } } @@ -463,7 +507,7 @@ static int ConstructsToC( /* Write the initialization function. */ /*====================================*/ - WriteInitializationFunction(theEnv,fileName); + WriteInitializationFunction(theEnv,fileName,pathName,fileNameBuffer); /*========================*/ /* Close the header file. */ @@ -507,6 +551,10 @@ static void WriteFunctionExternDeclarations( fprintf(fp,"int "); break; + case 'g': + fprintf(fp,"long long "); + break; + case 'l': fprintf(fp,"long "); break; @@ -531,6 +579,7 @@ static void WriteFunctionExternDeclarations( case 'a': case 'x': + case 'y': fprintf(fp,"void * "); break; @@ -549,11 +598,12 @@ static void WriteFunctionExternDeclarations( } fprintf(fp,"%s(",theFunction->actualFunctionName); - + switch(theFunction->returnValueType) { case 'i': case 'b': + case 'g': case 'l': case 'f': case 'd': @@ -563,8 +613,9 @@ static void WriteFunctionExternDeclarations( case 'c': case 'a': case 'x': + case 'y': case 'v': - if (theFunction->environmentAware) + if (theFunction->environmentAware) { fprintf(fp,"void *"); } else { fprintf(fp,"void"); } @@ -575,13 +626,11 @@ static void WriteFunctionExternDeclarations( case 'n': case 'j': case 'k': - if (theFunction->environmentAware) + if (theFunction->environmentAware) { fprintf(fp,"void *,DATA_OBJECT_PTR_ARG"); } else { fprintf(fp,"DATA_OBJECT_PTR_ARG"); } break; - default: - break; } fprintf(fp,");\n"); @@ -595,7 +644,9 @@ static void WriteFunctionExternDeclarations( /****************************************************/ static int FunctionsToCode( void *theEnv, - char *fileName) + const char *fileName, + const char *pathName, + char *fileNameBuffer) { short i = 0; FILE *fp; @@ -618,7 +669,7 @@ static int FunctionsToCode( /* function definition data structures. */ /*=======================================*/ - if ((fp = NewCFile(theEnv,fileName,2,version,FALSE)) == NULL) + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,2,version,FALSE)) == NULL) { return(0); } /*===============================================*/ @@ -663,7 +714,7 @@ static int FunctionsToCode( version++; if (fctnPtr != NULL) { - if ((fp = NewCFile(theEnv,fileName,2,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,2,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -697,9 +748,10 @@ globle void PrintFunctionReference( /******************************************/ static int WriteInitializationFunction( void *theEnv, - char *fileName) + const char *fileName, + const char *pathName, + char *fileNameBuffer) { - char fname[FILENAME_MAX+1]; FILE *fp; struct CodeGeneratorItem *cgPtr; @@ -707,10 +759,10 @@ static int WriteInitializationFunction( /* Open the initialization file. */ /*===============================*/ - sprintf(fname,"%s.c",fileName); - if ((fp = GenOpen(theEnv,fname,"w")) == NULL) + gensprintf(fileNameBuffer,"%s%s.c",pathName,fileName); + if ((fp = GenOpen(theEnv,fileNameBuffer,"w")) == NULL) { - OpenErrorMessage(theEnv,"constructs-to-c",fname); + OpenErrorMessage(theEnv,"constructs-to-c",fileNameBuffer); return(FALSE); } @@ -746,10 +798,9 @@ static int WriteInitializationFunction( fprintf(fp," if (theEnv != NULL) return(NULL);\n\n"); fprintf(fp," theEnv = CreateRuntimeEnvironment(sht%d,fht%d,iht%d,bmht%d);\n\n", ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->ImageID, - ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->ImageID); + ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->ImageID); fprintf(fp," EnvClear(theEnv);\n"); - fprintf(fp," PeriodicCleanup(theEnv,TRUE,FALSE);\n"); fprintf(fp," RefreshSpecialSymbols(theEnv);\n"); fprintf(fp," InstallFunctionList(theEnv,P%d_1);\n\n",ConstructCompilerData(theEnv)->ImageID); @@ -794,21 +845,25 @@ static int WriteInitializationFunction( /**************************************************/ globle FILE *NewCFile( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int id, int version, int reopenOldFile) { - char fname[FILENAME_MAX+1]; FILE *newFP; - sprintf(fname,"%s%d_%d.c",fileName,id,version); + gensprintf(fileNameBuffer,"%s%s%d_%d.c",pathName,fileName,id,version); - newFP = GenOpen(theEnv,fname,(char *) (reopenOldFile ? "a" : "w")); + if (reopenOldFile) + { newFP = GenOpen(theEnv,fileNameBuffer,"a"); } + else + { newFP = GenOpen(theEnv,fileNameBuffer,"w"); } if (newFP == NULL) { - OpenErrorMessage(theEnv,"constructs-to-c",fname); + OpenErrorMessage(theEnv,"constructs-to-c",fileNameBuffer); return(NULL); } @@ -900,7 +955,10 @@ globle int ExpressionToCode( if (ConstructCompilerData(theEnv)->ExpressionHeader == TRUE) { - if ((ConstructCompilerData(theEnv)->ExpressionFP = NewCFile(theEnv,ConstructCompilerData(theEnv)->FilePrefix,3,ConstructCompilerData(theEnv)->ExpressionVersion,FALSE)) == NULL) + if ((ConstructCompilerData(theEnv)->ExpressionFP = NewCFile(theEnv,ConstructCompilerData(theEnv)->FilePrefix, + ConstructCompilerData(theEnv)->PathName, + ConstructCompilerData(theEnv)->FileNameBuffer, + 3,ConstructCompilerData(theEnv)->ExpressionVersion,FALSE)) == NULL) { return(-1); } fprintf(ConstructCompilerData(theEnv)->ExpressionFP,"struct expr E%d_%d[] = {\n",ConstructCompilerData(theEnv)->ImageID,ConstructCompilerData(theEnv)->ExpressionVersion); @@ -1094,7 +1152,7 @@ globle void ConstructsToCCommandDefinition( { EnvDefineFunction2(theEnv,"constructs-to-c",'v', PTIEF ConstructsToCCommand, - "ConstructsToCCommand", "23*kii"); + "ConstructsToCCommand", "24*kiki"); } /*********************************************************/ @@ -1105,11 +1163,11 @@ globle void ConstructsToCCommandDefinition( /*********************************************************/ globle struct CodeGeneratorItem *AddCodeGeneratorItem( void *theEnv, - char *name, + const char *name, int priority, void (*beforeFunction)(void *), void (*initFunction)(void *,FILE *,int,int), - int (*generateFunction)(void *,char *,int,FILE *,int,int), + int (*generateFunction)(void *,const char *,const char *,char *,int,FILE *,int,int), int arrayCount) { struct CodeGeneratorItem *newPtr, *currentPtr, *lastPtr = NULL; @@ -1150,12 +1208,12 @@ globle struct CodeGeneratorItem *AddCodeGeneratorItem( for (i = 0 ; i < arrayCount ; i++) { if (ConstructCompilerData(theEnv)->CodeGeneratorCount < PRIMARY_LEN) - { sprintf(theBuffer,"%c",PRIMARY_CODES[ConstructCompilerData(theEnv)->CodeGeneratorCount]); } + { gensprintf(theBuffer,"%c",PRIMARY_CODES[ConstructCompilerData(theEnv)->CodeGeneratorCount]); } else - { sprintf(theBuffer,"%c_",SECONDARY_CODES[ConstructCompilerData(theEnv)->CodeGeneratorCount - PRIMARY_LEN]); } + { gensprintf(theBuffer,"%c_",SECONDARY_CODES[ConstructCompilerData(theEnv)->CodeGeneratorCount - PRIMARY_LEN]); } ConstructCompilerData(theEnv)->CodeGeneratorCount++; newPtr->arrayNames[i] = (char *) gm2(theEnv,(strlen(theBuffer) + 1)); - strcpy(newPtr->arrayNames[i],theBuffer); + genstrcpy(newPtr->arrayNames[i],theBuffer); } } else @@ -1263,7 +1321,7 @@ globle FILE *CloseFileIfNeeded( if (codeFile->filePrefix == NULL) { return(NULL); } - theFile = NewCFile(theEnv,codeFile->filePrefix,codeFile->id,codeFile->version,TRUE); + theFile = NewCFile(theEnv,codeFile->filePrefix,codeFile->pathName,codeFile->fileNameBuffer,codeFile->id,codeFile->version,TRUE); if (theFile == NULL) { SystemError(theEnv,"CONSCOMP",4); @@ -1305,19 +1363,21 @@ globle FILE *CloseFileIfNeeded( globle FILE *OpenFileIfNeeded( void *theEnv, FILE *theFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, int *fileCount, int arrayVersion, FILE *headerFP, - char *structureName, + const char *structureName, char *structPrefix, int reopenOldFile, struct CodeGeneratorFile *codeFile) { char arrayName[80]; - char *newName; + const char *newName; int newID, newVersion; /*===========================================*/ @@ -1372,7 +1432,7 @@ globle FILE *OpenFileIfNeeded( /* Open the file. */ /*================*/ - if ((theFile = NewCFile(theEnv,newName,newID,newVersion,reopenOldFile)) == NULL) + if ((theFile = NewCFile(theEnv,newName,pathName,fileNameBuffer,newID,newVersion,reopenOldFile)) == NULL) { return(NULL); } /*=========================================*/ @@ -1384,7 +1444,7 @@ globle FILE *OpenFileIfNeeded( if (reopenOldFile == FALSE) { (*fileCount)++; - sprintf(arrayName,"%s%d_%d",structPrefix,imageID,arrayVersion); + gensprintf(arrayName,"%s%d_%d",structPrefix,imageID,arrayVersion); fprintf(theFile,"%s %s[] = {\n",structureName,arrayName); fprintf(headerFP,"extern %s %s[];\n",structureName,arrayName); } @@ -1416,16 +1476,13 @@ globle void MarkConstructBsaveIDs( /* Used with the MarkConstructBsaveIDs function to mark all */ /* occurences of a specific construct with a unique ID. */ /*************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkConstruct( void *theEnv, struct constructHeader *theConstruct, void *vTheBuffer) { long *count = (long *) vTheBuffer; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1443,8 +1500,8 @@ globle void ConstructHeaderToCode( int imageID, int maxIndices, int moduleCount, - char *constructModulePrefix, - char *constructPrefix) + const char *constructModulePrefix, + const char *constructPrefix) { /*================*/ /* Construct Name */ @@ -1503,7 +1560,7 @@ globle void ConstructModuleToCode( int imageID, int maxIndices, int constructIndex, - char *constructPrefix) + const char *constructPrefix) { struct defmoduleItemHeader *theModuleItem; @@ -1554,9 +1611,9 @@ globle void ConstructModuleToCode( /* for rule compiler stub. */ /************************************/ void ConstructsToCCommand( - void *theEnv) + void *theEnv) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif } diff --git a/src/conscomp.h b/src/conscomp.h index bbd7e87..153d569 100644 --- a/src/conscomp.h +++ b/src/conscomp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -16,7 +16,38 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.23: Modifications to use the system constant */ +/* FILENAME_MAX to check file name lengths. */ +/* DR0856 */ +/* */ +/* Corrected compilation errors for files */ +/* generated by constructs-to-c. DR0861 */ +/* */ +/* 6.24: Used EnvClear rather than Clear in */ +/* InitCImage initialization code. */ +/* */ +/* Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Removed SHORT_LINK_NAMES code as this option */ +/* is no longer supported. */ +/* */ +/* Support for run-time programs directly passing */ +/* the hash tables for initialization. */ +/* */ +/* 6.30: Added path name argument to constructs-to-c. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, MAC_MCW, */ +/* IBM_TBC, IBM_MSC, IBM_ICB, IBM_ZTC, and */ +/* IBM_SC). */ +/* */ +/* Use genstrcpy instead of strcpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ /* */ /*************************************************************/ @@ -45,10 +76,10 @@ struct CodeGeneratorItem { - char *name; + const char *name; void (*beforeFunction)(void *); void (*initFunction)(void *,FILE *,int,int); - int (*generateFunction)(void *,char *,int,FILE *,int,int); + int (*generateFunction)(void *,const char *,const char *,char *,int,FILE *,int,int); int priority; char **arrayNames; int arrayCount; @@ -56,13 +87,15 @@ struct CodeGeneratorItem }; struct constructCompilerData - { + { int ImageID; FILE *HeaderFP; int MaxIndices; FILE *ExpressionFP; FILE *FixupFP; - char *FilePrefix; + const char *FilePrefix; + const char *PathName; + char *FileNameBuffer; intBool ExpressionHeader; long ExpressionCount; int ExpressionVersion; @@ -83,7 +116,9 @@ struct constructCompilerData struct CodeGeneratorFile { - char *filePrefix; + const char *filePrefix; + const char *pathName; + char *fileNameBuffer; int id,version; }; @@ -95,21 +130,21 @@ struct CodeGeneratorFile LOCALE void InitializeConstructCompilerData(void *); LOCALE void ConstructsToCCommandDefinition(void *); - LOCALE FILE *NewCFile(void *,char *,int,int,int); + LOCALE FILE *NewCFile(void *,const char *,const char *,char *,int,int,int); LOCALE int ExpressionToCode(void *,FILE *,struct expr *); LOCALE void PrintFunctionReference(void *,FILE *,struct FunctionDefinition *); - LOCALE struct CodeGeneratorItem *AddCodeGeneratorItem(void *,char *,int, + LOCALE struct CodeGeneratorItem *AddCodeGeneratorItem(void *,const char *,int, void (*)(void *), void (*)(void *,FILE *,int,int), - int (*)(void *,char *,int,FILE *,int,int),int); + int (*)(void *,const char *,const char *,char *,int,FILE *,int,int),int); LOCALE FILE *CloseFileIfNeeded(void *,FILE *,int *,int *,int,int *,struct CodeGeneratorFile *); - LOCALE FILE *OpenFileIfNeeded(void *,FILE *,char *,int,int,int *,int,FILE *, - char *,char *,int,struct CodeGeneratorFile *); + LOCALE FILE *OpenFileIfNeeded(void *,FILE *,const char *,const char *,char *,int,int,int *, + int,FILE *,const char *,char *,int,struct CodeGeneratorFile *); LOCALE void MarkConstructBsaveIDs(void *,int); LOCALE void ConstructHeaderToCode(void *,FILE *,struct constructHeader *,int,int, - int,char *,char *); + int,const char *,const char *); LOCALE void ConstructModuleToCode(void *,FILE *,struct defmodule *,int,int, - int,char *); + int,const char *); LOCALE void PrintHashedExpressionReference(void *,FILE *,struct expr *,int,int); #endif diff --git a/src/constant.h b/src/constant.h index 1552cfb..9787580 100644 --- a/src/constant.h +++ b/src/constant.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/12/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* CONSTANTS HEADER FILE */ /*******************************************************/ @@ -16,6 +16,14 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Moved default type constants (NO_DEFAULT, */ +/* STATIC_DEFAULT, and DYNAMIC_DEFAULT) to */ +/* constant.h */ +/* */ +/* Added DATA_OBJECT_ARRAY primitive type. */ +/* */ +/* Added NESTED_RHS constant. */ +/* */ /*************************************************************/ #ifndef _H_constant @@ -38,6 +46,7 @@ #define ON 1 #define LHS 0 #define RHS 1 +#define NESTED_RHS 2 #define NEGATIVE 0 #define POSITIVE 1 #define EOS '\0' @@ -53,6 +62,10 @@ #define LOCAL_SAVE 1 #define VISIBLE_SAVE 2 +#define NO_DEFAULT 0 +#define STATIC_DEFAULT 1 +#define DYNAMIC_DEFAULT 2 + #ifndef WPROMPT_STRING #define WPROMPT_STRING "wclips" #endif @@ -66,15 +79,15 @@ #endif #ifndef VERSION_STRING -#define VERSION_STRING "6.24" +#define VERSION_STRING "6.30" #endif #ifndef CREATION_DATE_STRING -#define CREATION_DATE_STRING "06/15/06" +#define CREATION_DATE_STRING "3/17/15" #endif #ifndef BANNER_STRING -#define BANNER_STRING " CLIPS (V6.24 06/15/06)\n" +#define BANNER_STRING " CLIPS (6.30 3/17/15)\n" #endif /*************************/ @@ -138,6 +151,7 @@ #define SF_WILDCARD 37 #define MF_WILDCARD 38 #define BITMAPARRAY 39 +#define DATA_OBJECT_ARRAY 40 #define FACT_PN_CMP1 50 #define FACT_JN_CMP1 51 diff --git a/src/constrct.c b/src/constrct.c index 25f4b36..5e1796d 100644 --- a/src/constrct.c +++ b/src/constrct.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CONSTRUCT MODULE */ /*******************************************************/ @@ -24,6 +24,34 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added code for capturing errors/warnings */ +/* (EnvSetParserErrorCallback). */ +/* */ +/* Fixed issue with save function when multiple */ +/* defmodules exist. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ #define _CONSTRCT_SOURCE_ @@ -46,10 +74,13 @@ #include "exprnpsr.h" #include "multifld.h" #include "moduldef.h" +#include "modulutl.h" #include "sysdep.h" #include "utility.h" #include "commline.h" +#include "cstrcpsr.h" +#include "ruledef.h" /* TBD Remove */ #include "constrct.h" /***************************************/ @@ -67,11 +98,11 @@ globle void InitializeConstructData( { AllocateEnvironmentData(theEnv,CONSTRUCT_DATA,sizeof(struct constructData),DeallocateConstructData); -#if (! RUN_TIME) && (! BLOAD_ONLY) +#if (! RUN_TIME) && (! BLOAD_ONLY) ConstructData(theEnv)->WatchCompilations = ON; #endif } - + /****************************************************/ /* DeallocateConstructData: Deallocates environment */ /* data for constructs. */ @@ -87,7 +118,22 @@ static void DeallocateConstructData( DeallocateCallList(theEnv,ConstructData(theEnv)->ListOfResetFunctions); DeallocateCallList(theEnv,ConstructData(theEnv)->ListOfClearFunctions); DeallocateCallList(theEnv,ConstructData(theEnv)->ListOfClearReadyFunctions); - + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (ConstructData(theEnv)->ErrorString != NULL) + { genfree(theEnv,ConstructData(theEnv)->ErrorString,sizeof(ConstructData(theEnv)->ErrorString) + 1); } + + if (ConstructData(theEnv)->WarningString != NULL) + { genfree(theEnv,ConstructData(theEnv)->WarningString,sizeof(ConstructData(theEnv)->WarningString) + 1); } + + ConstructData(theEnv)->ErrorString = NULL; + ConstructData(theEnv)->WarningString = NULL; + + EnvSetParsingFileName(theEnv,NULL); + EnvSetWarningFileName(theEnv,NULL); + EnvSetErrorFileName(theEnv,NULL); +#endif + tmpPtr = ConstructData(theEnv)->ListOfConstructs; while (tmpPtr != NULL) { @@ -99,13 +145,29 @@ static void DeallocateConstructData( #if (! RUN_TIME) && (! BLOAD_ONLY) +/**************************************************/ +/* EnvSetParserErrorCallback: Allows the function */ +/* which is called when a construct parsing */ +/* error occurs to be changed. */ +/**************************************************/ +globle void (*EnvSetParserErrorCallback(void *theEnv, + void (*functionPtr)(void *,const char *,const char *,const char *,long))) + (void *,const char *,const char *,const char*,long) + { + void (*tmpPtr)(void *,const char *,const char *,const char *,long); + + tmpPtr = ConstructData(theEnv)->ParserErrorCallback; + ConstructData(theEnv)->ParserErrorCallback = functionPtr; + return(tmpPtr); + } + /*************************************************/ /* FindConstruct: Determines whether a construct */ /* type is in the ListOfConstructs. */ /*************************************************/ globle struct construct *FindConstruct( void *theEnv, - char *name) + const char *name) { struct construct *currentPtr; @@ -128,7 +190,7 @@ globle struct construct *FindConstruct( /***********************************************************/ globle int RemoveConstruct( void *theEnv, - char *name) + const char *name) { struct construct *currentPtr, *lastPtr = NULL; @@ -157,11 +219,13 @@ globle int RemoveConstruct( /************************************************/ globle int EnvSave( void *theEnv, - char *fileName) + const char *fileName) { struct callFunctionItem *saveFunction; FILE *filePtr; - void *defmodulePtr; + struct defmodule *defmodulePtr; + intBool updated = FALSE; + intBool unvisited = TRUE; /*=====================*/ /* Open the save file. */ @@ -176,19 +240,66 @@ globle int EnvSave( SetFastSave(theEnv,filePtr); - /*======================*/ - /* Save the constructs. */ - /*======================*/ - - for (defmodulePtr = EnvGetNextDefmodule(theEnv,NULL); - defmodulePtr != NULL; - defmodulePtr = EnvGetNextDefmodule(theEnv,defmodulePtr)) + /*================================*/ + /* Mark all modules as unvisited. */ + /*================================*/ + + MarkModulesAsUnvisited(theEnv); + + /*===============================================*/ + /* Save the constructs. Repeatedly loop over the */ + /* modules until each module has been save. */ + /*===============================================*/ + + while (unvisited) { - for (saveFunction = ConstructData(theEnv)->ListOfSaveFunctions; - saveFunction != NULL; - saveFunction = saveFunction->next) + unvisited = FALSE; + updated = FALSE; + + for (defmodulePtr = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL); + defmodulePtr != NULL; + defmodulePtr = (struct defmodule *) EnvGetNextDefmodule(theEnv,defmodulePtr)) { - ((* (void (*)(void *,void *,char *)) saveFunction->func))(theEnv,defmodulePtr,(char *) filePtr); + /*=================================================================*/ + /* We only want to save a module if all of the modules it imports */ + /* from have already been saved. Since there can't be circular */ + /* dependencies in imported modules, this should save the modules */ + /* that don't import anything first and then work back from those. */ + /*=================================================================*/ + + if (defmodulePtr->visitedFlag) + { /* Module has already been saved. */ } + else if (AllImportedModulesVisited(theEnv,defmodulePtr)) + { + for (saveFunction = ConstructData(theEnv)->ListOfSaveFunctions; + saveFunction != NULL; + saveFunction = saveFunction->next) + { + ((* (void (*)(void *,void *,char *)) saveFunction->func))(theEnv,defmodulePtr,(char *) filePtr); + } + + updated = TRUE; + defmodulePtr->visitedFlag = TRUE; + } + else + { unvisited = TRUE; } + } + + /*=====================================================================*/ + /* At least one module should be saved in every pass. If all have been */ + /* visited/saved, then both flags will be FALSE. If all remaining */ + /* unvisited/unsaved modules were visited/saved, then unvisited will */ + /* be FALSE and updated will be TRUE. If some, but not all, remaining */ + /* unvisited/unsaved modules are visited/saved, then unvisited will */ + /* be TRUE and updated will be TRUE. This leaves the case where there */ + /* are remaining unvisited/unsaved modules, but none were */ + /* visited/saved: unvisited is TRUE and updated is FALSE. */ + /*=====================================================================*/ + + if (unvisited && (! updated)) + { + SystemError(theEnv,"CONSTRCT",2); + break; } } @@ -219,7 +330,7 @@ globle int EnvSave( /*******************************************************/ globle intBool RemoveSaveFunction( void *theEnv, - char *name) + const char *name) { int found; @@ -248,8 +359,8 @@ globle void SetCompilationsWatch( /*************************************/ globle unsigned GetCompilationsWatch( void *theEnv) - { - return(ConstructData(theEnv)->WatchCompilations); + { + return(ConstructData(theEnv)->WatchCompilations); } /**********************************/ @@ -289,7 +400,7 @@ globle void InitializeConstructs( AddWatchItem(theEnv,"compilations",0,&ConstructData(theEnv)->WatchCompilations,30,NULL,NULL); #endif #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -343,7 +454,7 @@ globle void EnvReset( /* command prompt, reset the halt execution flag. */ /*================================================*/ - if (EvaluationData(theEnv)->CurrentEvaluationDepth == 0) SetHaltExecution(theEnv,FALSE); + if (UtilityData(theEnv)->CurrentGarbageFrame->topLevel) SetHaltExecution(theEnv,FALSE); /*=======================================================*/ /* Call the before reset function to determine if the */ @@ -352,7 +463,7 @@ globle void EnvReset( /* reset should proceed with activations on the agenda.] */ /*=======================================================*/ - if ((ConstructData(theEnv)->BeforeResetFunction != NULL) ? + if ((ConstructData(theEnv)->BeforeResetFunction != NULL) ? ((*ConstructData(theEnv)->BeforeResetFunction)(theEnv) == FALSE) : FALSE) { @@ -369,10 +480,10 @@ globle void EnvReset( for (resetPtr = ConstructData(theEnv)->ListOfResetFunctions; (resetPtr != NULL) && (GetHaltExecution(theEnv) == FALSE); resetPtr = resetPtr->next) - { + { if (resetPtr->environmentAware) { (*resetPtr->func)(theEnv); } - else + else { (* (void (*)(void)) resetPtr->func)(); } } @@ -387,9 +498,12 @@ globle void EnvReset( /* issued from an embedded controller. */ /*===========================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*===================================*/ /* A reset is no longer in progress. */ @@ -412,34 +526,13 @@ globle int (*SetBeforeResetFunction(void *theEnv, return(tempFunction); } -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -/*************************************/ -/* AddResetFunction: Adds a function */ -/* to ListOfResetFunctions. */ -/*************************************/ -globle intBool AddResetFunction( - char *name, - void (*functionPtr)(void), - int priority) - { - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - ConstructData(theEnv)->ListOfResetFunctions = - AddFunctionToCallList(theEnv,name,priority,(void (*)(void *)) functionPtr, - ConstructData(theEnv)->ListOfResetFunctions,FALSE); - return(TRUE); - } -#endif - /****************************************/ /* EnvAddResetFunction: Adds a function */ /* to ListOfResetFunctions. */ /****************************************/ globle intBool EnvAddResetFunction( void *theEnv, - char *name, + const char *name, void (*functionPtr)(void *), int priority) { @@ -455,7 +548,7 @@ globle intBool EnvAddResetFunction( /**********************************************/ globle intBool EnvRemoveResetFunction( void *theEnv, - char *name) + const char *name) { int found; @@ -466,7 +559,28 @@ globle intBool EnvRemoveResetFunction( return(FALSE); } - + +/*******************************************/ +/* EnvIncrementClearReadyLocks: Increments */ +/* the number of clear ready locks. */ +/*******************************************/ +globle void EnvIncrementClearReadyLocks( + void *theEnv) + { + ConstructData(theEnv)->ClearReadyLocks++; + } + +/*******************************************/ +/* EnvDecrementClearReadyLocks: Decrements */ +/* the number of clear locks. */ +/*******************************************/ +globle void EnvDecrementClearReadyLocks( + void *theEnv) + { + if (ConstructData(theEnv)->ClearReadyLocks > 0) + { ConstructData(theEnv)->ClearReadyLocks--; } + } + /*****************************************************/ /* EnvClear: C access routine for the clear command. */ /*****************************************************/ @@ -474,7 +588,7 @@ globle void EnvClear( void *theEnv) { struct callFunctionItem *theFunction; - + /*==========================================*/ /* Activate the watch router which captures */ /* trace output so that it is not displayed */ @@ -490,7 +604,9 @@ globle void EnvClear( /*===================================*/ ConstructData(theEnv)->ClearReadyInProgress = TRUE; - if (ClearReady(theEnv) == FALSE) + if ((ConstructData(theEnv)->ClearReadyLocks > 0) || + (ConstructData(theEnv)->DanglingConstructs > 0) || + (ClearReady(theEnv) == FALSE)) { PrintErrorID(theEnv,"CONSTRCT",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Some constructs are still in use. Clear cannot continue.\n"); @@ -511,10 +627,10 @@ globle void EnvClear( for (theFunction = ConstructData(theEnv)->ListOfClearFunctions; theFunction != NULL; theFunction = theFunction->next) - { + { if (theFunction->environmentAware) { (*theFunction->func)(theEnv); } - else + else { (* (void (*)(void)) theFunction->func)(); } } @@ -532,15 +648,30 @@ globle void EnvClear( /* issued from an embedded controller. */ /*===========================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*===========================*/ /* Clear has been completed. */ /*===========================*/ ConstructData(theEnv)->ClearInProgress = FALSE; + +#if DEFRULE_CONSTRUCT + if ((DefruleData(theEnv)->RightPrimeJoins != NULL) || + (DefruleData(theEnv)->LeftPrimeJoins != NULL)) + { SystemError(theEnv,"CONSTRCT",1); } +#endif + + /*============================*/ + /* Perform reset after clear. */ + /*============================*/ + + EnvReset(theEnv); } /*********************************************************/ @@ -573,7 +704,7 @@ globle intBool ClearReady( /******************************************/ globle intBool AddClearReadyFunction( void *theEnv, - char *name, + const char *name, int (*functionPtr)(void *), int priority) { @@ -590,7 +721,7 @@ globle intBool AddClearReadyFunction( /************************************************/ globle intBool RemoveClearReadyFunction( void *theEnv, - char *name) + const char *name) { int found; @@ -602,35 +733,13 @@ globle intBool RemoveClearReadyFunction( return(FALSE); } -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -/*************************************/ -/* AddClearFunction: Adds a function */ -/* to ListOfClearFunctions. */ -/*************************************/ -globle intBool AddClearFunction( - char *name, - void (*functionPtr)(void), - int priority) - { - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - ConstructData(theEnv)->ListOfClearFunctions = - AddFunctionToCallList(theEnv,name,priority, - (void (*)(void *)) functionPtr, - ConstructData(theEnv)->ListOfClearFunctions,FALSE); - return(1); - } -#endif - /****************************************/ /* EnvAddClearFunction: Adds a function */ /* to ListOfClearFunctions. */ /****************************************/ globle intBool EnvAddClearFunction( void *theEnv, - char *name, + const char *name, void (*functionPtr)(void *), int priority) { @@ -647,7 +756,7 @@ globle intBool EnvAddClearFunction( /**********************************************/ globle intBool EnvRemoveClearFunction( void *theEnv, - char *name) + const char *name) { int found; @@ -667,7 +776,7 @@ globle intBool EnvRemoveClearFunction( globle int ExecutingConstruct( void *theEnv) { - return(ConstructData(theEnv)->Executing); + return(ConstructData(theEnv)->Executing); } /********************************************/ @@ -683,61 +792,6 @@ globle void SetExecutingConstruct( ConstructData(theEnv)->Executing = value; } -/************************************************************/ -/* OldGetConstructList: Returns a list of all the construct */ -/* names in a multifield value. It doesn't check the */ -/* number of arguments. It assumes that the restriction */ -/* string in DefineFunction2 call was "00". */ -/************************************************************/ -globle void OldGetConstructList( - void *theEnv, - DATA_OBJECT_PTR returnValue, - void *(*nextFunction)(void *,void *), - char *(*nameFunction)(void *,void *)) - { - void *theConstruct; - unsigned long count = 0; - struct multifield *theList; - - /*====================================*/ - /* Determine the number of constructs */ - /* of the specified type. */ - /*====================================*/ - - for (theConstruct = (*nextFunction)(theEnv,NULL); - theConstruct != NULL; - theConstruct = (*nextFunction)(theEnv,theConstruct)) - { count++; } - - /*===========================*/ - /* Create a multifield large */ - /* enough to store the list. */ - /*===========================*/ - - SetpType(returnValue,MULTIFIELD); - SetpDOBegin(returnValue,1); - SetpDOEnd(returnValue,(long) count); - theList = (struct multifield *) EnvCreateMultifield(theEnv,count); - SetpValue(returnValue,(void *) theList); - - /*====================================*/ - /* Store the names in the multifield. */ - /*====================================*/ - - for (theConstruct = (*nextFunction)(theEnv,NULL), count = 1; - theConstruct != NULL; - theConstruct = (*nextFunction)(theEnv,theConstruct), count++) - { - if (EvaluationData(theEnv)->HaltExecution == TRUE) - { - EnvSetMultifieldErrorValue(theEnv,returnValue); - return; - } - SetMFType(theList,count,SYMBOL); - SetMFValue(theList,count,EnvAddSymbol(theEnv,(*nameFunction)(theEnv,theConstruct))); - } - } - /*******************************************************/ /* DeinstallConstructHeader: Decrements the busy count */ /* of a construct name and frees its pretty print */ @@ -751,7 +805,7 @@ globle void DeinstallConstructHeader( DecrementSymbolCount(theEnv,theHeader->name); if (theHeader->ppForm != NULL) { - rm(theEnv,theHeader->ppForm, + rm(theEnv,(void *) theHeader->ppForm, sizeof(char) * (strlen(theHeader->ppForm) + 1)); theHeader->ppForm = NULL; } @@ -775,7 +829,7 @@ globle void DestroyConstructHeader( { if (theHeader->ppForm != NULL) { - rm(theEnv,theHeader->ppForm, + rm(theEnv,(void *) theHeader->ppForm, sizeof(char) * (strlen(theHeader->ppForm) + 1)); theHeader->ppForm = NULL; } @@ -793,12 +847,12 @@ globle void DestroyConstructHeader( /*****************************************************/ globle struct construct *AddConstruct( void *theEnv, - char *name, - char *pluralName, - int (*parseFunction)(void *,char *), - void *(*findFunction)(void *,char *), + const char *name, + const char *pluralName, + int (*parseFunction)(void *,const char *), + void *(*findFunction)(void *,const char *), SYMBOL_HN *(*getConstructNameFunction)(struct constructHeader *), - char *(*getPPFormFunction)(void *,struct constructHeader *), + const char *(*getPPFormFunction)(void *,struct constructHeader *), struct defmoduleItemHeader *(*getModuleItemFunction)(struct constructHeader *), void *(*getNextItemFunction)(void *,void *), void (*setNextItemFunction)(struct constructHeader *,struct constructHeader *), @@ -844,26 +898,92 @@ globle struct construct *AddConstruct( /************************************/ globle intBool AddSaveFunction( void *theEnv, - char *name, - void (*functionPtr)(void *,void *,char *), + const char *name, + void (*functionPtr)(void *,void *,const char *), int priority) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(name) -#pragma unused(functionPtr) -#pragma unused(priority) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) ConstructData(theEnv)->ListOfSaveFunctions = AddFunctionToCallList(theEnv,name,priority, (void (*)(void *)) functionPtr, ConstructData(theEnv)->ListOfSaveFunctions,TRUE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif return(1); } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool AddClearFunction( + const char *name, + void (*functionPtr)(void), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + ConstructData(theEnv)->ListOfClearFunctions = + AddFunctionToCallList(theEnv,name,priority, + (void (*)(void *)) functionPtr, + ConstructData(theEnv)->ListOfClearFunctions,FALSE); + return(1); + } + +globle intBool AddResetFunction( + const char *name, + void (*functionPtr)(void), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + ConstructData(theEnv)->ListOfResetFunctions = + AddFunctionToCallList(theEnv,name,priority,(void (*)(void *)) functionPtr, + ConstructData(theEnv)->ListOfResetFunctions,FALSE); + return(TRUE); + } + +globle void Clear() + { + EnvClear(GetCurrentEnvironment()); + } + +globle intBool RemoveClearFunction( + const char *name) + { + return EnvRemoveClearFunction(GetCurrentEnvironment(),name); + } + +globle intBool RemoveResetFunction( + const char *name) + { + return EnvRemoveResetFunction(GetCurrentEnvironment(),name); + } + +globle void Reset() + { + EnvReset(GetCurrentEnvironment()); + } + +#if (! RUN_TIME) && (! BLOAD_ONLY) + +globle int Save( + const char *fileName) + { + return EnvSave(GetCurrentEnvironment(),fileName); + } +#endif + +#endif + + diff --git a/src/constrct.h b/src/constrct.h index 85f76b0..9c61936 100644 --- a/src/constrct.h +++ b/src/constrct.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CONSTRUCT MODULE */ /*******************************************************/ @@ -16,7 +16,38 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added code for capturing errors/warnings */ +/* (EnvSetParserErrorCallback). */ +/* */ +/* Fixed issue with save function when multiple */ +/* defmodules exist. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ /* */ /*************************************************************/ @@ -39,7 +70,7 @@ struct construct; struct constructHeader { struct symbolHashNode *name; - char *ppForm; + const char *ppForm; struct defmoduleItemHeader *whichModule; long bsaveID; struct constructHeader *next; @@ -50,12 +81,12 @@ struct constructHeader struct construct { - char *constructName; - char *pluralName; - int (*parseFunction)(void *,char *); - void *(*findFunction)(void *,char *); + const char *constructName; + const char *pluralName; + int (*parseFunction)(void *,const char *); + void *(*findFunction)(void *,const char *); struct symbolHashNode *(*getConstructNameFunction)(struct constructHeader *); - char *(*getPPFormFunction)(void *,struct constructHeader *); + const char *(*getPPFormFunction)(void *,struct constructHeader *); struct defmoduleItemHeader *(*getModuleItemFunction)(struct constructHeader *); void *(*getNextItemFunction)(void *,void *); void (*setNextItemFunction)(struct constructHeader *,struct constructHeader *); @@ -75,15 +106,32 @@ struct construct #define CONSTRUCT_DATA 42 struct constructData - { + { int ClearReadyInProgress; int ClearInProgress; int ResetReadyInProgress; int ResetInProgress; + short ClearReadyLocks; + int DanglingConstructs; #if (! RUN_TIME) && (! BLOAD_ONLY) - struct callFunctionItem *ListOfSaveFunctions; + struct callFunctionItem *ListOfSaveFunctions; intBool PrintWhileLoading; unsigned WatchCompilations; + int CheckSyntaxMode; + int ParsingConstruct; + char *ErrorString; + char *WarningString; + char *ParsingFileName; + char *ErrorFileName; + char *WarningFileName; + long ErrLineNumber; + long WrnLineNumber; + int errorCaptureRouterCount; + size_t MaxErrChars; + size_t CurErrPos; + size_t MaxWrnChars; + size_t CurWrnPos; + void (*ParserErrorCallback)(void *,const char *,const char *,const char *,long); #endif struct construct *ListOfConstructs; struct callFunctionItem *ListOfResetFunctions; @@ -91,7 +139,6 @@ struct constructData struct callFunctionItem *ListOfClearReadyFunctions; int Executing; int (*BeforeResetFunction)(void *); - int CheckSyntaxMode; }; #define ConstructData(theEnv) ((struct constructData *) GetEnvironmentData(theEnv,CONSTRUCT_DATA)) @@ -106,46 +153,33 @@ struct constructData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Clear(theEnv) EnvClear(theEnv) -#define Reset(theEnv) EnvReset(theEnv) -#define Save(theEnv,a) EnvSave(theEnv,a) -#define RemoveClearFunction(theEnv,a) EnvRemoveClearFunction(theEnv,a) -#define RemoveResetFunction(theEnv,a) EnvRemoveResetFunction(theEnv,a) -#else -#define Clear() EnvClear(GetCurrentEnvironment()) -#define Reset() EnvReset(GetCurrentEnvironment()) -#define Save(a) EnvSave(GetCurrentEnvironment(),a) -#define RemoveClearFunction(a) EnvRemoveClearFunction(GetCurrentEnvironment(),a) -#define RemoveResetFunction(a) EnvRemoveResetFunction(GetCurrentEnvironment(),a) -#endif + LOCALE void EnvClear(void *); + LOCALE void EnvReset(void *); + LOCALE int EnvSave(void *,const char *); LOCALE void InitializeConstructData(void *); - LOCALE int EnvSave(void *,char *); - LOCALE intBool AddSaveFunction(void *,char *,void (*)(void *,void *,char *),int); - LOCALE intBool RemoveSaveFunction(void *,char *); - LOCALE void EnvReset(void *); - LOCALE intBool EnvAddResetFunction(void *,char *,void (*)(void *),int); - LOCALE intBool AddResetFunction(char *,void (*)(void),int); - LOCALE intBool EnvRemoveResetFunction(void *,char *); - LOCALE void EnvClear(void *); - LOCALE intBool AddClearReadyFunction(void *,char *,int (*)(void *),int); - LOCALE intBool RemoveClearReadyFunction(void *,char *); - LOCALE intBool EnvAddClearFunction(void *,char *,void (*)(void *),int); - LOCALE intBool AddClearFunction(char *,void (*)(void),int); - LOCALE intBool EnvRemoveClearFunction(void *,char *); - LOCALE struct construct *AddConstruct(void *,char *,char *, - int (*)(void *,char *), - void *(*)(void *,char *), + LOCALE intBool AddSaveFunction(void *,const char *,void (*)(void *,void *,const char *),int); + LOCALE intBool RemoveSaveFunction(void *,const char *); + LOCALE intBool EnvAddResetFunction(void *,const char *,void (*)(void *),int); + LOCALE intBool EnvRemoveResetFunction(void *,const char *); + LOCALE intBool AddClearReadyFunction(void *,const char *,int (*)(void *),int); + LOCALE intBool RemoveClearReadyFunction(void *,const char *); + LOCALE intBool EnvAddClearFunction(void *,const char *,void (*)(void *),int); + LOCALE intBool EnvRemoveClearFunction(void *,const char *); + LOCALE void EnvIncrementClearReadyLocks(void *); + LOCALE void EnvDecrementClearReadyLocks(void *); + LOCALE struct construct *AddConstruct(void *,const char *,const char *, + int (*)(void *,const char *), + void *(*)(void *,const char *), SYMBOL_HN *(*)(struct constructHeader *), - char *(*)(void *,struct constructHeader *), + const char *(*)(void *,struct constructHeader *), struct defmoduleItemHeader *(*)(struct constructHeader *), void *(*)(void *,void *), void (*)(struct constructHeader *,struct constructHeader *), intBool (*)(void *,void *), int (*)(void *,void *), void (*)(void *,void *)); - LOCALE int RemoveConstruct(void *,char *); + LOCALE int RemoveConstruct(void *,const char *); LOCALE void SetCompilationsWatch(void *,unsigned); LOCALE unsigned GetCompilationsWatch(void *); LOCALE void SetPrintWhileLoading(void *,intBool); @@ -154,20 +188,33 @@ struct constructData LOCALE void SetExecutingConstruct(void *,int); LOCALE void InitializeConstructs(void *); LOCALE int (*SetBeforeResetFunction(void *,int (*)(void *)))(void *); - LOCALE void OldGetConstructList(void *,DATA_OBJECT *, - void *(*)(void *,void *), - char *(*)(void *,void *)); LOCALE void ResetCommand(void *); LOCALE void ClearCommand(void *); LOCALE intBool ClearReady(void *); - LOCALE struct construct *FindConstruct(void *,char *); + LOCALE struct construct *FindConstruct(void *,const char *); LOCALE void DeinstallConstructHeader(void *,struct constructHeader *); LOCALE void DestroyConstructHeader(void *,struct constructHeader *); + LOCALE void (*EnvSetParserErrorCallback(void *theEnv, + void (*functionPtr)(void *,const char *,const char *, + const char *,long))) + (void *,const char *,const char *,const char*,long); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool AddClearFunction(const char *,void (*)(void),int); + LOCALE intBool AddResetFunction(const char *,void (*)(void),int); + LOCALE void Clear(void); + LOCALE void Reset(void); + LOCALE intBool RemoveClearFunction(const char *); + LOCALE intBool RemoveResetFunction(const char *); +#if (! RUN_TIME) && (! BLOAD_ONLY) + LOCALE int Save(const char *); +#endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ +#endif /* _H_constrct */ diff --git a/src/constrnt.c b/src/constrnt.c index 671f18b..3dc6284 100644 --- a/src/constrnt.c +++ b/src/constrnt.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT MODULE */ /*******************************************************/ @@ -16,15 +16,24 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Added allowed-classes slot facet. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _CONSTRNT_SOURCE_ @@ -73,9 +82,9 @@ globle void InitializeConstraints( #endif AllocateEnvironmentData(theEnv,CONSTRAINT_DATA,sizeof(struct constraintData),DeallocateConstraintData); - + ConstraintData(theEnv)->StaticConstraintChecking = TRUE; - + #if (! RUN_TIME) && (! BLOAD_ONLY) ConstraintData(theEnv)->ConstraintHashtable = (struct constraintRecord **) @@ -95,7 +104,7 @@ globle void InitializeConstraints( EnvDefineFunction2(theEnv,"set-static-constraint-checking",'b',SSCCommand,"SSCCommand", "11"); #endif } - + /*****************************************************/ /* DeallocateConstraintData: Deallocates environment */ /* data for constraints. */ @@ -103,7 +112,7 @@ globle void InitializeConstraints( static void DeallocateConstraintData( void *theEnv) { -#if ! RUN_TIME +#if ! RUN_TIME struct constraintRecord *tmpPtr, *nextPtr; int i; @@ -121,17 +130,16 @@ static void DeallocateConstraintData( rm(theEnv,ConstraintData(theEnv)->ConstraintHashtable, (int) sizeof (struct constraintRecord *) * SIZE_CONSTRAINT_HASH); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif - + #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) if (ConstraintData(theEnv)->NumberOfConstraints != 0) { - genlongfree(theEnv,(void *) ConstraintData(theEnv)->ConstraintArray, - (unsigned long) (sizeof(CONSTRAINT_RECORD) * - ConstraintData(theEnv)->NumberOfConstraints)); + genfree(theEnv,(void *) ConstraintData(theEnv)->ConstraintArray, + (sizeof(CONSTRAINT_RECORD) * ConstraintData(theEnv)->NumberOfConstraints)); } #endif } @@ -258,15 +266,15 @@ globle void RemoveConstraint( /* HashConstraint: Returns a hash */ /* value for a given constraint. */ /***********************************/ -globle int HashConstraint( +globle unsigned long HashConstraint( struct constraintRecord *theConstraint) { int i = 0; - unsigned int count = 0; - int hashValue; + unsigned long count = 0; + unsigned long hashValue; struct expr *tmpPtr; - count += (unsigned) + count += (unsigned long) (theConstraint->anyAllowed * 17) + (theConstraint->symbolsAllowed * 5) + (theConstraint->stringsAllowed * 23) + @@ -275,15 +283,15 @@ globle int HashConstraint( (theConstraint->instanceNamesAllowed * 31) + (theConstraint->instanceAddressesAllowed * 17); - count += (unsigned) + count += (unsigned long) (theConstraint->externalAddressesAllowed * 29) + (theConstraint->voidAllowed * 29) + (theConstraint->multifieldsAllowed * 29) + (theConstraint->factAddressesAllowed * 79) + (theConstraint->anyRestriction * 59) + (theConstraint->symbolRestriction * 61); - - count += (unsigned) + + count += (unsigned long) (theConstraint->stringRestriction * 3) + (theConstraint->floatRestriction * 37) + (theConstraint->integerRestriction * 9) + @@ -309,10 +317,10 @@ globle int HashConstraint( { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); } if (theConstraint->multifield != NULL) - { count += (unsigned) HashConstraint(theConstraint->multifield); } + { count += HashConstraint(theConstraint->multifield); } + + hashValue = (unsigned long) (count % SIZE_CONSTRAINT_HASH); - hashValue = (int) (count % SIZE_CONSTRAINT_HASH); - if (hashValue < 0) hashValue = - hashValue; return(hashValue); } @@ -420,7 +428,7 @@ globle struct constraintRecord *AddConstraint( struct constraintRecord *theConstraint) { struct constraintRecord *tmpPtr; - int hashValue; + unsigned long hashValue; if (theConstraint == NULL) return(NULL); @@ -591,8 +599,8 @@ globle intBool EnvSetDynamicConstraintChecking( /******************************************************/ globle intBool EnvGetDynamicConstraintChecking( void *theEnv) - { - return(ConstraintData(theEnv)->DynamicConstraintChecking); + { + return(ConstraintData(theEnv)->DynamicConstraintChecking); } /*****************************************************/ @@ -616,7 +624,36 @@ globle intBool EnvSetStaticConstraintChecking( /*****************************************************/ globle intBool EnvGetStaticConstraintChecking( void *theEnv) - { - return(ConstraintData(theEnv)->StaticConstraintChecking); + { + return(ConstraintData(theEnv)->StaticConstraintChecking); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool SetDynamicConstraintChecking( + int value) + { + return EnvSetDynamicConstraintChecking(GetCurrentEnvironment(),value); + } + +globle intBool GetDynamicConstraintChecking() + { + return EnvGetDynamicConstraintChecking(GetCurrentEnvironment()); + } + +globle intBool SetStaticConstraintChecking( + int value) + { + return EnvSetStaticConstraintChecking(GetCurrentEnvironment(),value); + } + +globle intBool GetStaticConstraintChecking() + { + return EnvGetStaticConstraintChecking(GetCurrentEnvironment()); + } + +#endif diff --git a/src/constrnt.h b/src/constrnt.h index 273563a..2b5a482 100644 --- a/src/constrnt.h +++ b/src/constrnt.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT HEADER FILE */ /*******************************************************/ @@ -18,10 +18,21 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_constrnt @@ -84,7 +95,7 @@ typedef struct constraintRecord CONSTRAINT_RECORD; #define CONSTRAINT_DATA 43 struct constraintData - { + { struct constraintRecord **ConstraintHashtable; intBool StaticConstraintChecking; intBool DynamicConstraintChecking; @@ -96,18 +107,6 @@ struct constraintData #define ConstraintData(theEnv) ((struct constraintData *) GetEnvironmentData(theEnv,CONSTRAINT_DATA)) -#if ENVIRONMENT_API_ONLY -#define GetDynamicConstraintChecking(theEnv) EnvGetDynamicConstraintChecking(theEnv) -#define GetStaticConstraintChecking(theEnv) EnvGetStaticConstraintChecking(theEnv) -#define SetDynamicConstraintChecking(theEnv,a) EnvSetDynamicConstraintChecking(theEnv,a) -#define SetStaticConstraintChecking(theEnv,a) EnvSetStaticConstraintChecking(theEnv,a) -#else -#define GetDynamicConstraintChecking() EnvGetDynamicConstraintChecking(GetCurrentEnvironment()) -#define GetStaticConstraintChecking() EnvGetStaticConstraintChecking(GetCurrentEnvironment()) -#define SetDynamicConstraintChecking(a) EnvSetDynamicConstraintChecking(GetCurrentEnvironment(),a) -#define SetStaticConstraintChecking(a) EnvSetStaticConstraintChecking(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeConstraints(void *); LOCALE int GDCCommand(void *); LOCALE int SDCCommand(void *d); @@ -118,13 +117,22 @@ struct constraintData LOCALE intBool EnvSetStaticConstraintChecking(void *,int); LOCALE intBool EnvGetStaticConstraintChecking(void *); #if (! BLOAD_ONLY) && (! RUN_TIME) - LOCALE int HashConstraint(struct constraintRecord *); + LOCALE unsigned long HashConstraint(struct constraintRecord *); LOCALE struct constraintRecord *AddConstraint(void *,struct constraintRecord *); #endif #if (! RUN_TIME) LOCALE void RemoveConstraint(void *,struct constraintRecord *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool SetDynamicConstraintChecking(int); + LOCALE intBool GetDynamicConstraintChecking(void); + LOCALE intBool SetStaticConstraintChecking(int); + LOCALE intBool GetStaticConstraintChecking(void); + +#endif + #endif diff --git a/src/crstrtgy.c b/src/crstrtgy.c index b5e9394..baca134 100644 --- a/src/crstrtgy.c +++ b/src/crstrtgy.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONFLICT RESOLUTION STRATEGY MODULE */ /*******************************************************/ @@ -19,12 +19,26 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES */ /* compilation flag. */ /* */ +/* 6.30: Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Removed pseudo-facts used for not CEs. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _CRSTRTGY_SOURCE_ @@ -43,24 +57,27 @@ #include "argacces.h" #include "agenda.h" #include "envrnmnt.h" +#include "memalloc.h" + #include "crstrtgy.h" -#define GetMatchingItem(x,i) (x->basis->binds[i].gm.theMatch->matchingItem) +#define GetMatchingItem(x,i) ((x->basis->binds[i].gm.theMatch != NULL) ? \ + (x->basis->binds[i].gm.theMatch->matchingItem) : NULL) /***************************************/ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static ACTIVATION *PlaceDepthActivation(ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceBreadthActivation(ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceLEXActivation(void *,ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceMEAActivation(void *,ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceComplexityActivation(ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceSimplicityActivation(ACTIVATION *,ACTIVATION *); - static ACTIVATION *PlaceRandomActivation(ACTIVATION *,ACTIVATION *); - static struct partialMatch *SortPartialMatch(void *,struct partialMatch *); + static ACTIVATION *PlaceDepthActivation(ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceBreadthActivation(ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceLEXActivation(void *,ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceMEAActivation(void *,ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceComplexityActivation(ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceSimplicityActivation(ACTIVATION *,struct salienceGroup *); + static ACTIVATION *PlaceRandomActivation(ACTIVATION *,struct salienceGroup *); static int ComparePartialMatches(void *,ACTIVATION *,ACTIVATION *); - static char *GetStrategyName(int); + static const char *GetStrategyName(int); + static unsigned long long *SortPartialMatch(void *,struct partialMatch *); /******************************************************************/ /* PlaceActivation: Coordinates placement of an activation on the */ @@ -69,7 +86,8 @@ globle void PlaceActivation( void *theEnv, ACTIVATION **whichAgenda, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { ACTIVATION *placeAfter = NULL; @@ -86,38 +104,43 @@ globle void PlaceActivation( /* current conflict resolution strategy. */ /*==============================================*/ - if (*whichAgenda != NULL) switch (AgendaData(theEnv)->Strategy) + if (*whichAgenda != NULL) { - case DEPTH_STRATEGY: - placeAfter = PlaceDepthActivation(*whichAgenda,newActivation); - break; - - case BREADTH_STRATEGY: - placeAfter = PlaceBreadthActivation(*whichAgenda,newActivation); - break; + switch (AgendaData(theEnv)->Strategy) + { + case DEPTH_STRATEGY: + placeAfter = PlaceDepthActivation(newActivation,theGroup); + break; - case LEX_STRATEGY: - placeAfter = PlaceLEXActivation(theEnv,*whichAgenda,newActivation); - break; + case BREADTH_STRATEGY: + placeAfter = PlaceBreadthActivation(newActivation,theGroup); + break; - case MEA_STRATEGY: - placeAfter = PlaceMEAActivation(theEnv,*whichAgenda,newActivation); - break; + case LEX_STRATEGY: + placeAfter = PlaceLEXActivation(theEnv,newActivation,theGroup); + break; - case COMPLEXITY_STRATEGY: - placeAfter = PlaceComplexityActivation(*whichAgenda,newActivation); - break; + case MEA_STRATEGY: + placeAfter = PlaceMEAActivation(theEnv,newActivation,theGroup); + break; - case SIMPLICITY_STRATEGY: - placeAfter = PlaceSimplicityActivation(*whichAgenda,newActivation); - break; + case COMPLEXITY_STRATEGY: + placeAfter = PlaceComplexityActivation(newActivation,theGroup); + break; - case RANDOM_STRATEGY: - placeAfter = PlaceRandomActivation(*whichAgenda,newActivation); - break; + case SIMPLICITY_STRATEGY: + placeAfter = PlaceSimplicityActivation(newActivation,theGroup); + break; - default: - break; + case RANDOM_STRATEGY: + placeAfter = PlaceRandomActivation(newActivation,theGroup); + break; + } + } + else + { + theGroup->first = newActivation; + theGroup->last = newActivation; } /*==============================================================*/ @@ -148,20 +171,21 @@ globle void PlaceActivation( /* activation should be placed at the beginning of the agenda). */ /*******************************************************************/ static ACTIVATION *PlaceDepthActivation( - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience; - unsigned long timetag; - ACTIVATION *lastAct; + ACTIVATION *lastAct, *actPtr; + unsigned long long timetag; /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ - salience = newActivation->salience; timetag = newActivation->timetag; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -172,24 +196,32 @@ static ACTIVATION *PlaceDepthActivation( /* depth first traversal). */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) + if (timetag < actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; - } - else if (actPtr->salience < salience) - { return(lastAct); } - else if (timetag < actPtr->timetag) - { - lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else - { return(lastAct); } + { break; } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -205,20 +237,26 @@ static ACTIVATION *PlaceDepthActivation( /* activation should be placed at the beginning of the agenda). */ /*******************************************************************/ static ACTIVATION *PlaceBreadthActivation( - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience; - unsigned long timetag; - ACTIVATION *lastAct; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ - salience = newActivation->salience; timetag = newActivation->timetag; - lastAct = NULL; + if (theGroup->last == NULL) + { + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } + } + else + { lastAct = theGroup->last; } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -229,24 +267,40 @@ static ACTIVATION *PlaceBreadthActivation( /* first traversal). */ /*=========================================================*/ + actPtr = theGroup->last; while (actPtr != NULL) { - if (actPtr->salience > salience) + if (timetag < actPtr->timetag) { - lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->first) + { + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } + break; + } + else + { actPtr = actPtr->prev; } } - else if (actPtr->salience < salience) - { return(lastAct); } - else if (timetag > actPtr->timetag) + else { lastAct = actPtr; - actPtr = actPtr->next; + break; } - else - { return(lastAct); } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -263,28 +317,41 @@ static ACTIVATION *PlaceBreadthActivation( /*******************************************************************/ static ACTIVATION *PlaceLEXActivation( void *theEnv, - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience; - unsigned long timetag; - ACTIVATION *lastAct; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; int flag; - /*===============================================*/ - /* Sort the fact identifiers for the activation. */ - /*===============================================*/ - - if (newActivation->sortedBasis == NULL) - { newActivation->sortedBasis = SortPartialMatch(theEnv,newActivation->basis); } - /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ timetag = newActivation->timetag; - salience = newActivation->salience; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } + + /*================================================*/ + /* Look first at the very end of the group to see */ + /* if the activation should be placed there. */ + /*================================================*/ + + actPtr = theGroup->last; + if (actPtr != NULL) + { + flag = ComparePartialMatches(theEnv,actPtr,newActivation); + + if ((flag == LESS_THAN) || + ((flag == EQUAL) && (timetag > actPtr->timetag))) + { + theGroup->last = newActivation; + + return(actPtr); + } + } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -294,39 +361,47 @@ static ACTIVATION *PlaceLEXActivation( /* determining placement. */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) + flag = ComparePartialMatches(theEnv,actPtr,newActivation); + + if (flag == LESS_THAN) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } - else if (actPtr->salience < salience) - { return(lastAct); } - else + else if (flag == GREATER_THAN) + { break; } + else /* flag == EQUAL */ { - flag = ComparePartialMatches(theEnv,actPtr,newActivation); - - if (flag == LESS_THAN) + if (timetag > actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; - } - else if (flag == GREATER_THAN) - { return(lastAct); } - else /* flag == EQUAL */ - { - if (timetag > actPtr->timetag) - { - lastAct = actPtr; - actPtr = actPtr->next; - } + if (actPtr == theGroup->last) + { break; } else - { return(lastAct); } + { actPtr = actPtr->next; } } + else + { break; } } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -343,25 +418,70 @@ static ACTIVATION *PlaceLEXActivation( /*******************************************************************/ static ACTIVATION *PlaceMEAActivation( void *theEnv, - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience; - unsigned long timetag; - ACTIVATION *lastAct; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; int flag; - long int cWhoset, oWhoset; - - if (newActivation->sortedBasis == NULL) - { newActivation->sortedBasis = SortPartialMatch(theEnv,newActivation->basis); } + long long cWhoset = 0, oWhoset = 0; + intBool cSet, oSet; /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ timetag = newActivation->timetag; - salience = newActivation->salience; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } + + /*================================================*/ + /* Look first at the very end of the group to see */ + /* if the activation should be placed there. */ + /*================================================*/ + + actPtr = theGroup->last; + if (actPtr != NULL) + { + if (GetMatchingItem(newActivation,0) != NULL) + { + cWhoset = GetMatchingItem(newActivation,0)->timeTag; + cSet = TRUE; + } + else + { cSet = FALSE; } + + if (GetMatchingItem(actPtr,0) != NULL) + { + oWhoset = GetMatchingItem(actPtr,0)->timeTag; + oSet = TRUE; + } + else + { oSet = FALSE; } + + if ((cSet == FALSE) && (oSet == FALSE)) + { flag = ComparePartialMatches(theEnv,actPtr,newActivation); } + else if ((cSet == TRUE) && (oSet == FALSE)) + { flag = GREATER_THAN; } + else if ((cSet == FALSE) && (oSet == TRUE)) + { flag = LESS_THAN; } + else if (oWhoset < cWhoset) + { flag = GREATER_THAN; } + else if (oWhoset > cWhoset) + { flag = LESS_THAN; } + else + { flag = ComparePartialMatches(theEnv,actPtr,newActivation); } + + if ((flag == LESS_THAN) || + ((flag == EQUAL) && (timetag > actPtr->timetag))) + { + theGroup->last = newActivation; + + return(actPtr); + } + } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -371,56 +491,66 @@ static ACTIVATION *PlaceMEAActivation( /* determining placement. */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) + cWhoset = -1; + oWhoset = -1; + if (GetMatchingItem(newActivation,0) != NULL) + { cWhoset = GetMatchingItem(newActivation,0)->timeTag; } + + if (GetMatchingItem(actPtr,0) != NULL) + { oWhoset = GetMatchingItem(actPtr,0)->timeTag; } + + if (oWhoset < cWhoset) { - lastAct = actPtr; - actPtr = actPtr->next; + if (cWhoset > 0) flag = GREATER_THAN; + else flag = LESS_THAN; + } + else if (oWhoset > cWhoset) + { + if (oWhoset > 0) flag = LESS_THAN; + else flag = GREATER_THAN; } - else if (actPtr->salience < salience) - { return(lastAct); } else + { flag = ComparePartialMatches(theEnv,actPtr,newActivation); } + + if (flag == LESS_THAN) { - cWhoset = -1; - oWhoset = -1; - if (GetMatchingItem(newActivation,0) != NULL) - { cWhoset = GetMatchingItem(newActivation,0)->timeTag; } - if (GetMatchingItem(actPtr,0) != NULL) - { oWhoset = GetMatchingItem(actPtr,0)->timeTag; } - if (oWhoset < cWhoset) - { - if (cWhoset > 0) flag = GREATER_THAN; - else flag = LESS_THAN; - } - else if (oWhoset > cWhoset) - { - if (oWhoset > 0) flag = LESS_THAN; - else flag = GREATER_THAN; - } + lastAct = actPtr; + if (actPtr == theGroup->last) + { break; } else - { flag = ComparePartialMatches(theEnv,actPtr,newActivation); } - - if (flag == LESS_THAN) + { actPtr = actPtr->next; } + } + else if (flag == GREATER_THAN) + { break; } + else /* flag == EQUAL */ + { + if (timetag > actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; - } - else if (flag == GREATER_THAN) - { return(lastAct); } - else /* flag == EQUAL */ - { - if (timetag > actPtr->timetag) - { - lastAct = actPtr; - actPtr = actPtr->next; - } + if (actPtr == theGroup->last) + { break; } else - { return(lastAct); } + { actPtr = actPtr->next; } } + else + { break; } } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -436,21 +566,23 @@ static ACTIVATION *PlaceMEAActivation( /* should be placed at the beginning of the agenda). */ /*********************************************************************/ static ACTIVATION *PlaceComplexityActivation( - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience, complexity; - unsigned long timetag; - ACTIVATION *lastAct; + int complexity; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; /*========================================*/ /* Set up initial information for search. */ /*========================================*/ timetag = newActivation->timetag; - salience = newActivation->salience; complexity = newActivation->theRule->complexity; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -460,31 +592,42 @@ static ACTIVATION *PlaceComplexityActivation( /* activations of equal or lessor complexity. */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) - { - lastAct = actPtr; - actPtr = actPtr->next; - } - else if (actPtr->salience < salience) - { return(lastAct); } - else if (complexity < (int) actPtr->theRule->complexity) + if (complexity < (int) actPtr->theRule->complexity) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else if (complexity > (int) actPtr->theRule->complexity) - { return(lastAct); } + { break; } else if (timetag > actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else - { return(lastAct); } + { break; } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -500,21 +643,23 @@ static ACTIVATION *PlaceComplexityActivation( /* should be placed at the beginning of the agenda). */ /*********************************************************************/ static ACTIVATION *PlaceSimplicityActivation( - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience, complexity; - unsigned long timetag; - ACTIVATION *lastAct; + int complexity; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ timetag = newActivation->timetag; - salience = newActivation->salience; complexity = newActivation->theRule->complexity; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -524,31 +669,42 @@ static ACTIVATION *PlaceSimplicityActivation( /* activations of equal or greater complexity. */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) + if (complexity > (int) actPtr->theRule->complexity) { lastAct = actPtr; - actPtr = actPtr->next; - } - else if (actPtr->salience < salience) - { return(lastAct); } - else if (complexity > (int) actPtr->theRule->complexity) - { - lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else if (complexity < (int) actPtr->theRule->complexity) - { return(lastAct); } + { break; } else if (timetag > actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else - { return(lastAct); } + { break; } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -564,21 +720,23 @@ static ACTIVATION *PlaceSimplicityActivation( /* activation should be placed at the beginning of the agenda). */ /*******************************************************************/ static ACTIVATION *PlaceRandomActivation( - ACTIVATION *actPtr, - ACTIVATION *newActivation) + ACTIVATION *newActivation, + struct salienceGroup *theGroup) { - int salience, randomID; - unsigned long timetag; - ACTIVATION *lastAct; + int randomID; + unsigned long long timetag; + ACTIVATION *lastAct, *actPtr; /*============================================*/ /* Set up initial information for the search. */ /*============================================*/ timetag = newActivation->timetag; - salience = newActivation->salience; randomID = newActivation->randomID; - lastAct = NULL; + if (theGroup->prev == NULL) + { lastAct = NULL; } + else + { lastAct = theGroup->prev->last; } /*=========================================================*/ /* Find the insertion point in the agenda. The activation */ @@ -588,31 +746,42 @@ static ACTIVATION *PlaceRandomActivation( /* determined through the generation of a random number. */ /*=========================================================*/ + actPtr = theGroup->first; while (actPtr != NULL) { - if (actPtr->salience > salience) - { - lastAct = actPtr; - actPtr = actPtr->next; - } - else if (actPtr->salience < salience) - { return(lastAct); } - else if (randomID > actPtr->randomID) + if (randomID > actPtr->randomID) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else if (randomID < actPtr->randomID) - { return(lastAct); } + { break; } else if (timetag > actPtr->timetag) { lastAct = actPtr; - actPtr = actPtr->next; + if (actPtr == theGroup->last) + { break; } + else + { actPtr = actPtr->next; } } else - { return(lastAct); } + { break; } } + /*========================================*/ + /* Update the salience group information. */ + /*========================================*/ + + if ((lastAct == NULL) || + ((theGroup->prev != NULL) && (theGroup->prev->last == lastAct))) + { theGroup->first = newActivation; } + + if ((theGroup->last == NULL) || (theGroup->last == lastAct)) + { theGroup->last = newActivation; } + /*===========================================*/ /* Return the insertion point in the agenda. */ /*===========================================*/ @@ -620,23 +789,35 @@ static ACTIVATION *PlaceRandomActivation( return(lastAct); } -/******************************************************************/ -/* SortPartialMatch: Copies a partial match and then sorts the */ -/* fact-indices in the copied partial match in ascending order. */ -/******************************************************************/ -static struct partialMatch *SortPartialMatch( +/*********************************************************/ +/* SortPartialMatch: Creates an array of sorted timetags */ +/* in ascending order from a partial match. */ +/*********************************************************/ +static unsigned long long *SortPartialMatch( void *theEnv, struct partialMatch *binds) { - struct partialMatch *nbinds; - struct alphaMatch *temp; - int flag, j, k; + unsigned long long *nbinds; + unsigned long long temp; + int flag; + unsigned j, k; - /*=================*/ - /* Copy the array. */ - /*=================*/ + /*====================================================*/ + /* Copy the array. Use 0 to represent the timetags of */ + /* negated patterns. Patterns matching fact/instances */ + /* should have timetags greater than 0. */ + /*====================================================*/ + + nbinds = (unsigned long long *) get_mem(theEnv,sizeof(long long) * binds->bcount); - nbinds = CopyPartialMatch(theEnv,binds,0,0); + for (j = 0; j < (unsigned) binds->bcount; j++) + { + if ((binds->binds[j].gm.theMatch != NULL) && + (binds->binds[j].gm.theMatch->matchingItem != NULL)) + { nbinds[j] = binds->binds[j].gm.theMatch->matchingItem->timeTag; } + else + { nbinds[j] = 0; } + } /*=================*/ /* Sort the array. */ @@ -649,17 +830,12 @@ static struct partialMatch *SortPartialMatch( flag = FALSE; for (j = 0 ; j < k ; j++) { - if ((nbinds->binds[j].gm.theMatch->matchingItem != NULL) && - (nbinds->binds[j + 1].gm.theMatch->matchingItem != NULL)) + if (nbinds[j] < nbinds[j + 1]) { - if (nbinds->binds[j].gm.theMatch->matchingItem->timeTag < - nbinds->binds[j + 1].gm.theMatch->matchingItem->timeTag) - { - temp = nbinds->binds[j].gm.theMatch; - nbinds->binds[j].gm.theMatch = nbinds->binds[j+1].gm.theMatch; - nbinds->binds[j+1].gm.theMatch = temp; - flag = TRUE; - } + temp = nbinds[j]; + nbinds[j] = nbinds[j+1]; + nbinds[j+1] = temp; + flag = TRUE; } } } @@ -683,14 +859,15 @@ static int ComparePartialMatches( ACTIVATION *newActivation) { int cCount, oCount, mCount, i; + unsigned long long *basis1, *basis2; /*=================================================*/ /* If the activation already on the agenda doesn't */ /* have a set of sorted timetags, then create one. */ /*=================================================*/ - if (actPtr->sortedBasis == NULL) - { actPtr->sortedBasis = SortPartialMatch(theEnv,actPtr->basis); } + basis1 = SortPartialMatch(theEnv,newActivation->basis); + basis2 = SortPartialMatch(theEnv,actPtr->basis); /*==============================================================*/ /* Determine the number of timetags in each of the activations. */ @@ -698,8 +875,9 @@ static int ComparePartialMatches( /* two numbers. */ /*==============================================================*/ - cCount = newActivation->sortedBasis->bcount; - oCount = actPtr->sortedBasis->bcount; + cCount = newActivation->basis->bcount; + oCount = actPtr->basis->bcount; + if (oCount > cCount) mCount = cCount; else mCount = oCount; @@ -713,22 +891,23 @@ static int ComparePartialMatches( for (i = 0 ; i < mCount ; i++) { - if ((actPtr->sortedBasis->binds[i].gm.theMatch->matchingItem != NULL) && - (newActivation->sortedBasis->binds[i].gm.theMatch->matchingItem != NULL)) + if (basis1[i] < basis2[i]) { - if (newActivation->sortedBasis->binds[i].gm.theMatch->matchingItem->timeTag < - actPtr->sortedBasis->binds[i].gm.theMatch->matchingItem->timeTag) - { return(LESS_THAN); } - else if (newActivation->sortedBasis->binds[i].gm.theMatch->matchingItem->timeTag > - actPtr->sortedBasis->binds[i].gm.theMatch->matchingItem->timeTag) - { return(GREATER_THAN); } + rtn_mem(theEnv,sizeof(long long) * cCount,basis1); + rtn_mem(theEnv,sizeof(long long) * oCount,basis2); + return(LESS_THAN); + } + else if (basis1[i] > basis2[i]) + { + rtn_mem(theEnv,sizeof(long long) * cCount,basis1); + rtn_mem(theEnv,sizeof(long long) * oCount,basis2); + return(GREATER_THAN); } - else if (newActivation->sortedBasis->binds[i].gm.theMatch->matchingItem != NULL) - { return(GREATER_THAN); } - else if (actPtr->sortedBasis->binds[i].gm.theMatch->matchingItem != NULL) - { return(LESS_THAN); } } + rtn_mem(theEnv,sizeof(long long) * cCount,basis1); + rtn_mem(theEnv,sizeof(long long) * oCount,basis2); + /*==========================================================*/ /* If the sorted timetags are identical up to the number of */ /* timetags contained in the smaller partial match, then */ @@ -770,7 +949,7 @@ globle int EnvSetStrategy( int value) { int oldStrategy; - + oldStrategy = AgendaData(theEnv)->Strategy; AgendaData(theEnv)->Strategy = value; @@ -809,9 +988,9 @@ globle void *SetStrategyCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; int oldStrategy; - + oldStrategy = AgendaData(theEnv)->Strategy; /*=====================================================*/ @@ -863,10 +1042,10 @@ globle void *SetStrategyCommand( /* to a specified strategy, return a character string */ /* of the strategy's name. */ /**********************************************************/ -static char *GetStrategyName( +static const char *GetStrategyName( int strategy) { - char *sname; + const char *sname; switch (strategy) { @@ -899,5 +1078,24 @@ static char *GetStrategyName( return(sname); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle int SetStrategy( + int value) + { + return EnvSetStrategy(GetCurrentEnvironment(),value); + } + +globle int GetStrategy() + { + return EnvGetStrategy(GetCurrentEnvironment()); + } + +#endif + #endif /* DEFRULE_CONSTRUCT */ diff --git a/src/crstrtgy.h b/src/crstrtgy.h index c8daf06..997c691 100644 --- a/src/crstrtgy.h +++ b/src/crstrtgy.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONFLICT RESOLUTION STRATEGY HEADER MODULE */ /*******************************************************/ @@ -19,12 +19,26 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES */ /* compilation flag. */ /* */ +/* 6.30: Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Removed pseudo-facts used for not CEs. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_crstrtgy @@ -54,21 +68,19 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetStrategy(theEnv) EnvGetStrategy(theEnv) -#define SetStrategy(theEnv,a) EnvSetStrategy(theEnv,a) -#else -#define GetStrategy() EnvGetStrategy(GetCurrentEnvironment()) -#define SetStrategy(a) EnvSetStrategy(GetCurrentEnvironment(),a) -#endif - - LOCALE void PlaceActivation(void *,ACTIVATION **,ACTIVATION *); + LOCALE void PlaceActivation(void *,ACTIVATION **,ACTIVATION *,struct salienceGroup *); LOCALE int EnvSetStrategy(void *,int); LOCALE int EnvGetStrategy(void *); LOCALE void *SetStrategyCommand(void *); LOCALE void *GetStrategyCommand(void *); +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE int SetStrategy(int); + LOCALE int GetStrategy(void); + #endif +#endif /* _H_crstrtgy */ diff --git a/src/cstrcbin.c b/src/cstrcbin.c index e955dea..8f3b775 100644 --- a/src/cstrcbin.c +++ b/src/cstrcbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT BINARY LOAD/SAVE MODULE */ /*******************************************************/ @@ -11,7 +11,7 @@ /* headers. */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ diff --git a/src/cstrcbin.h b/src/cstrcbin.h index 9545adc..645f9af 100644 --- a/src/cstrcbin.h +++ b/src/cstrcbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ diff --git a/src/cstrccmp.h b/src/cstrccmp.h index 6d80110..ceaf8f7 100644 --- a/src/cstrccmp.h +++ b/src/cstrccmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT CONSTRUCTS-TO-C HEADER */ /*******************************************************/ @@ -18,6 +18,8 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed ANSI_COMPILER compilation flag. */ +/* */ /*************************************************************/ #ifndef _H_cstrccmp @@ -38,13 +40,9 @@ #include <stdio.h> #endif -#if ANSI_COMPILER LOCALE void MarkConstructHeaders(int); -#else - LOCALE void MarkConstructHeaders(); -#endif -#endif +#endif /* _H_cstrccmp */ diff --git a/src/cstrccom.c b/src/cstrccom.c index 84c86a5..22df487 100644 --- a/src/cstrccom.c +++ b/src/cstrccom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONSTRUCT COMMANDS MODULE */ /*******************************************************/ @@ -14,11 +14,12 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Modified GetConstructList to remove buffer */ /* overflow problem with large construct/module */ /* names. DR0858 */ @@ -36,6 +37,13 @@ /* */ /* Added ConstructsDeletable function. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Change find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _CSTRCCOM_SOURCE_ @@ -54,6 +62,7 @@ #include "router.h" #include "utility.h" #include "commline.h" +#include "sysdep.h" #if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE #include "bload.h" @@ -70,10 +79,10 @@ /***************************************/ #if DEBUGGING_FUNCTIONS - static void ConstructPrintWatch(void *,char *,struct construct *,void *, + static void ConstructPrintWatch(void *,const char *,struct construct *,void *, unsigned (*)(void *,void *)); - static unsigned ConstructWatchSupport(void *,struct construct *,char *, - char *,EXPRESSION *,intBool, + static unsigned ConstructWatchSupport(void *,struct construct *,const char *, + const char *,EXPRESSION *,intBool, unsigned,unsigned (*)(void *,void *), void (*)(void *,unsigned,void *)); #endif @@ -104,7 +113,7 @@ globle void AddConstructToModule( /****************************************************/ globle intBool DeleteNamedConstruct( void *theEnv, - char *constructName, + const char *constructName, struct construct *constructClass) { #if (! BLOAD_ONLY) @@ -151,20 +160,63 @@ globle intBool DeleteNamedConstruct( return(FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,constructName,constructClass) #endif return(FALSE); #endif } -/*******************************************/ -/* FindNamedConstruct: Generic routine for */ -/* searching for a specified construct. */ -/*******************************************/ -globle void *FindNamedConstruct( +/********************************************************/ +/* FindNamedConstructInModuleOrImports: Generic routine */ +/* for searching for a specified construct. */ +/********************************************************/ +globle void *FindNamedConstructInModuleOrImports( + void *theEnv, + const char *constructName, + struct construct *constructClass) + { + void *theConstruct; + int count; + + /*================================================*/ + /* First look in the current or specified module. */ + /*================================================*/ + + theConstruct = FindNamedConstructInModule(theEnv,constructName,constructClass); + if (theConstruct != NULL) return theConstruct; + + /*=====================================*/ + /* If there's a module specifier, then */ + /* the construct does not exist. */ + /*=====================================*/ + + if (FindModuleSeparator(constructName)) + { return(NULL); } + + /*========================================*/ + /* Otherwise, search in imported modules. */ + /*========================================*/ + + theConstruct = FindImportedConstruct(theEnv,constructClass->constructName,NULL, + constructName,&count,TRUE,NULL); + + if (count > 1) + { + AmbiguousReferenceErrorMessage(theEnv,constructClass->constructName,constructName); + return(NULL); + } + + return(theConstruct); + } + +/***********************************************/ +/* FindNamedConstructInModule: Generic routine */ +/* for searching for a specified construct. */ +/***********************************************/ +globle void *FindNamedConstructInModule( void *theEnv, - char *constructName, + const char *constructName, struct construct *constructClass) { void *theConstruct; @@ -201,6 +253,18 @@ globle void *FindNamedConstruct( } /*===============================================*/ + /* If we find the symbol for the construct name, */ + /* but it has a count of 0, then it can't be for */ + /* a construct that's currently defined. */ + /*===============================================*/ + + if (findValue->count == 0) + { + RestoreCurrentModule(theEnv); + return(NULL); + } + + /*===============================================*/ /* Loop through every construct of the specified */ /* class in the current module checking to see */ /* if the construct's name matches the construct */ @@ -222,7 +286,7 @@ globle void *FindNamedConstruct( /*=============================*/ /* Restore the current module. */ /*=============================*/ - + RestoreCurrentModule(theEnv); /*====================================*/ @@ -239,17 +303,17 @@ globle void *FindNamedConstruct( /*****************************************/ globle void UndefconstructCommand( void *theEnv, - char *command, + const char *command, struct construct *constructClass) { - char *constructName; + const char *constructName; char buffer[80]; /*==============================================*/ /* Get the name of the construct to be deleted. */ /*==============================================*/ - sprintf(buffer,"%s name",constructClass->constructName); + gensprintf(buffer,"%s name",constructClass->constructName); constructName = GetConstructName(theEnv,command,buffer); if (constructName == NULL) return; @@ -295,10 +359,10 @@ globle void UndefconstructCommand( /******************************************/ globle void PPConstructCommand( void *theEnv, - char *command, + const char *command, struct construct *constructClass) { - char *constructName; + const char *constructName; char buffer[80]; /*===============================*/ @@ -306,7 +370,7 @@ globle void PPConstructCommand( /* to be "pretty printed." */ /*===============================*/ - sprintf(buffer,"%s name",constructClass->constructName); + gensprintf(buffer,"%s name",constructClass->constructName); constructName = GetConstructName(theEnv,command,buffer); if (constructName == NULL) return; @@ -326,8 +390,8 @@ globle void PPConstructCommand( /***********************************/ globle int PPConstruct( void *theEnv, - char *constructName, - char *logicalName, + const char *constructName, + const char *logicalName, struct construct *constructClass) { void *constructPtr; @@ -371,10 +435,10 @@ globle int PPConstruct( /*********************************************/ globle SYMBOL_HN *GetConstructModuleCommand( void *theEnv, - char *command, + const char *command, struct construct *constructClass) { - char *constructName; + const char *constructName; char buffer[80]; struct defmodule *constructModule; @@ -383,7 +447,7 @@ globle SYMBOL_HN *GetConstructModuleCommand( /* we want to determine its module. */ /*=========================================*/ - sprintf(buffer,"%s name",constructClass->constructName); + gensprintf(buffer,"%s name",constructClass->constructName); constructName = GetConstructName(theEnv,command,buffer); if (constructName == NULL) return((SYMBOL_HN *) EnvFalseSymbol(theEnv)); @@ -412,7 +476,7 @@ globle SYMBOL_HN *GetConstructModuleCommand( /******************************************/ globle struct defmodule *GetConstructModule( void *theEnv, - char *constructName, + const char *constructName, struct construct *constructClass) { struct constructHeader *constructPtr; @@ -457,7 +521,7 @@ globle intBool Undefconstruct( struct construct *constructClass) { #if BLOAD_ONLY || RUN_TIME -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theConstruct) #pragma unused(constructClass) #pragma unused(theEnv) @@ -516,9 +580,14 @@ globle intBool Undefconstruct( /* Perform periodic cleanup if embedded. */ /*=======================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && + (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && + (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*============================================*/ /* Return TRUE if all constructs successfully */ @@ -552,9 +621,14 @@ globle intBool Undefconstruct( /* Perform periodic cleanup if embedded. */ /*=======================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && + (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && + (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*=============================*/ /* Return TRUE to indicate the */ @@ -572,10 +646,10 @@ globle intBool Undefconstruct( globle void SaveConstruct( void *theEnv, void *theModule, - char *logicalName, + const char *logicalName, struct construct *constructClass) { - char *ppform; + const char *ppform; struct constructHeader *theConstruct; /*==========================*/ @@ -625,7 +699,7 @@ globle void SaveConstruct( /* GetConstructModuleName: Generic routine for returning */ /* the name of the module to which a construct belongs */ /*********************************************************/ -globle char *GetConstructModuleName( +globle const char *GetConstructModuleName( struct constructHeader *theConstruct) { return(EnvGetDefmoduleName(NULL,(void *) theConstruct->whichModule->theModule)); } @@ -633,7 +707,7 @@ globle char *GetConstructModuleName( /* GetConstructNameString: Generic routine for returning */ /* the name string of a construct. */ /*********************************************************/ -globle char *GetConstructNameString( +globle const char *GetConstructNameString( struct constructHeader *theConstruct) { return(ValueToString(theConstruct->name)); } @@ -641,18 +715,15 @@ globle char *GetConstructNameString( /* EnvGetConstructNameString: Generic routine for */ /* returning the name string of a construct. */ /**************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetConstructNameString( +globle const char *EnvGetConstructNameString( void *theEnv, struct constructHeader *theConstruct) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(ValueToString(theConstruct->name)); + return(ValueToString(theConstruct->name)); } /**********************************************************/ @@ -669,7 +740,7 @@ globle SYMBOL_HN *GetConstructNamePointer( /************************************************/ globle void GetConstructListFunction( void *theEnv, - char *functionName, + const char *functionName, DATA_OBJECT_PTR returnValue, struct construct *constructClass) { @@ -757,13 +828,9 @@ globle void GetConstructList( SYMBOL_HN *theName; struct defmodule *loopModule; int allModules = FALSE; -#if IBM_TBC - unsigned largestConstructNameSize, bufferSize = 80; /* prevents warning */ -#else - unsigned largestConstructNameSize = 0, bufferSize = 80; /* prevents warning */ -#endif + size_t largestConstructNameSize = 0, bufferSize = 80; /* prevents warning */ char *buffer; - + /*==========================*/ /* Save the current module. */ /*==========================*/ @@ -790,56 +857,56 @@ globle void GetConstructList( loopModule = theModule; while (loopModule != NULL) { - unsigned tempSize; + size_t tempSize; /*======================================================*/ /* Set the current module to the module being examined. */ /*======================================================*/ - + EnvSetCurrentModule(theEnv,(void *) loopModule); /*===========================================*/ /* Loop over every construct in the module. */ /*===========================================*/ - + theConstruct = NULL; largestConstructNameSize = 0; - + while ((theConstruct = (*constructClass->getNextItemFunction)(theEnv,theConstruct)) != NULL) - { + { /*================================*/ /* Increment the construct count. */ /*================================*/ - - count++; + + count++; /*=================================================*/ /* Is this the largest construct name encountered? */ /*=================================================*/ - + tempSize = strlen(ValueToString((*constructClass->getConstructNameFunction)((struct constructHeader *) theConstruct))); if (tempSize > largestConstructNameSize) { largestConstructNameSize = tempSize; } } - + /*========================================*/ /* Determine the size of the module name. */ /*========================================*/ - + tempSize = strlen(EnvGetDefmoduleName(theEnv,loopModule)); /*======================================================*/ /* The buffer must be large enough for the module name, */ /* the largest name of all the constructs, and the ::. */ /*======================================================*/ - + if ((tempSize + largestConstructNameSize + 5) > bufferSize) { bufferSize = tempSize + largestConstructNameSize + 5; } /*=============================*/ /* Move on to the next module. */ /*=============================*/ - + if (allModules) loopModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,loopModule); else loopModule = NULL; } @@ -847,9 +914,9 @@ globle void GetConstructList( /*===========================*/ /* Allocate the name buffer. */ /*===========================*/ - + buffer = (char *) genalloc(theEnv,bufferSize); - + /*================================*/ /* Create the multifield value to */ /* store the construct names. */ @@ -889,9 +956,9 @@ globle void GetConstructList( SetMFType(theList,count,SYMBOL); if (allModules) { - strcpy(buffer,EnvGetDefmoduleName(theEnv,loopModule)); - strcat(buffer,"::"); - strcat(buffer,ValueToString(theName)); + genstrcpy(buffer,EnvGetDefmoduleName(theEnv,loopModule)); + genstrcat(buffer,"::"); + genstrcat(buffer,ValueToString(theName)); SetMFValue(theList,count,EnvAddSymbol(theEnv,buffer)); } else @@ -912,9 +979,9 @@ globle void GetConstructList( /*=========================*/ /* Return the name buffer. */ /*=========================*/ - + genfree(theEnv,buffer,bufferSize); - + /*=============================*/ /* Restore the current module. */ /*=============================*/ @@ -928,7 +995,7 @@ globle void GetConstructList( /*********************************************/ globle void ListConstructCommand( void *theEnv, - char *functionName, + const char *functionName, struct construct *constructClass) { struct defmodule *theModule; @@ -1000,7 +1067,7 @@ globle void ListConstructCommand( globle void ListConstruct( void *theEnv, struct construct *constructClass, - char *logicalName, + const char *logicalName, struct defmodule *theModule) { void *constructPtr; @@ -1115,18 +1182,15 @@ globle struct defmoduleItemHeader *GetConstructModuleItem( /* GetConstructPPForm: Returns the pretty print */ /* representation for the specified construct. */ /*************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *GetConstructPPForm( +globle const char *GetConstructPPForm( void *theEnv, struct constructHeader *theConstruct) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(theConstruct->ppForm); + return(theConstruct->ppForm); } /****************************************************/ @@ -1211,7 +1275,7 @@ globle long DoForAllConstructs( struct defmoduleItemHeader *theModuleItem; void *theModule; long moduleCount = 0L; - + /*==========================*/ /* Save the current module. */ /*==========================*/ @@ -1284,7 +1348,7 @@ globle void DoForAllConstructsInModule( { struct constructHeader *theConstruct; struct defmoduleItemHeader *theModuleItem; - + /*==========================*/ /* Save the current module. */ /*==========================*/ @@ -1335,7 +1399,7 @@ globle void DoForAllConstructsInModule( /*****************************************************/ globle void InitializeConstructHeader( void *theEnv, - char *constructType, + const char *constructType, struct constructHeader *theConstruct, SYMBOL_HN *theConstructName) { @@ -1361,7 +1425,7 @@ globle void InitializeConstructHeader( globle void SetConstructPPForm( void *theEnv, struct constructHeader *theConstruct, - char *ppForm) + const char *ppForm) { if (theConstruct->ppForm != NULL) { @@ -1380,7 +1444,7 @@ globle void SetConstructPPForm( globle unsigned ConstructPrintWatchAccess( void *theEnv, struct construct *constructClass, - char *logName, + const char *logName, EXPRESSION *argExprs, unsigned (*getWatchFunc)(void *,void *), void (*setWatchFunc)(void *,unsigned,void *)) @@ -1412,8 +1476,8 @@ globle unsigned ConstructSetWatchAccess( static unsigned ConstructWatchSupport( void *theEnv, struct construct *constructClass, - char *funcName, - char *logName, + const char *funcName, + const char *logName, EXPRESSION *argExprs, intBool setFlag, unsigned newState, @@ -1561,13 +1625,16 @@ static unsigned ConstructWatchSupport( /*************************************************/ static void ConstructPrintWatch( void *theEnv, - char *logName, + const char *logName, struct construct *constructClass, void *theConstruct, unsigned (*getWatchFunc)(void *,void *)) { EnvPrintRouter(theEnv,logName,ValueToString((*constructClass->getConstructNameFunction)((struct constructHeader *) theConstruct))); - EnvPrintRouter(theEnv,logName,(char *) ((*getWatchFunc)(theEnv,theConstruct) ? " = on\n" : " = off\n")); + if ((*getWatchFunc)(theEnv,theConstruct)) + EnvPrintRouter(theEnv,logName," = on\n"); + else + EnvPrintRouter(theEnv,logName," = off\n"); } #endif /* DEBUGGING_FUNCTIONS */ @@ -1580,11 +1647,11 @@ static void ConstructPrintWatch( globle void *LookupConstruct( void *theEnv, struct construct *constructClass, - char *constructName, + const char *constructName, intBool moduleNameAllowed) { void *theConstruct; - char *constructType; + const char *constructType; int moduleCount; /*============================================*/ @@ -1630,14 +1697,11 @@ globle void *LookupConstruct( /* ConstructsDeletable: Returns a boolean value indicating */ /* whether constructs in general can be deleted. */ /***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool ConstructsDeletable( void *theEnv) { #if BLOAD_ONLY || RUN_TIME || ((! BLOAD) && (! BLOAD_AND_BSAVE)) -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif diff --git a/src/cstrccom.h b/src/cstrccom.h index 0bee9ed..27b4fb7 100644 --- a/src/cstrccom.h +++ b/src/cstrccom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CONSTRUCT COMMAND HEADER MODULE */ /*******************************************************/ @@ -20,6 +20,13 @@ /* */ /* Added ConstructsDeletable function. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_cstrccom @@ -46,28 +53,29 @@ #if (! RUN_TIME) LOCALE void AddConstructToModule(struct constructHeader *); #endif - LOCALE intBool DeleteNamedConstruct(void *,char *,struct construct *); - LOCALE void *FindNamedConstruct(void *,char *,struct construct *); - LOCALE void UndefconstructCommand(void *,char *,struct construct *); - LOCALE int PPConstruct(void *,char *,char *,struct construct *); - LOCALE SYMBOL_HN *GetConstructModuleCommand(void *,char *,struct construct *); - LOCALE struct defmodule *GetConstructModule(void *,char *,struct construct *); + LOCALE intBool DeleteNamedConstruct(void *,const char *,struct construct *); + LOCALE void *FindNamedConstructInModule(void *,const char *,struct construct *); + LOCALE void *FindNamedConstructInModuleOrImports(void *,const char *,struct construct *); + LOCALE void UndefconstructCommand(void *,const char *,struct construct *); + LOCALE int PPConstruct(void *,const char *,const char *,struct construct *); + LOCALE SYMBOL_HN *GetConstructModuleCommand(void *,const char *,struct construct *); + LOCALE struct defmodule *GetConstructModule(void *,const char *,struct construct *); LOCALE intBool Undefconstruct(void *,void *,struct construct *); - LOCALE void SaveConstruct(void *,void *,char *,struct construct *); - LOCALE char *GetConstructNameString(struct constructHeader *); - LOCALE char *EnvGetConstructNameString(void *,struct constructHeader *); - LOCALE char *GetConstructModuleName(struct constructHeader *); + LOCALE void SaveConstruct(void *,void *,const char *,struct construct *); + LOCALE const char *GetConstructNameString(struct constructHeader *); + LOCALE const char *EnvGetConstructNameString(void *,struct constructHeader *); + LOCALE const char *GetConstructModuleName(struct constructHeader *); LOCALE SYMBOL_HN *GetConstructNamePointer(struct constructHeader *); - LOCALE void GetConstructListFunction(void *,char *,DATA_OBJECT_PTR, + LOCALE void GetConstructListFunction(void *,const char *,DATA_OBJECT_PTR, struct construct *); LOCALE void GetConstructList(void *,DATA_OBJECT_PTR,struct construct *, struct defmodule *); - LOCALE void ListConstructCommand(void *,char *,struct construct *); - LOCALE void ListConstruct(void *,struct construct *,char *,struct defmodule *); + LOCALE void ListConstructCommand(void *,const char *,struct construct *); + LOCALE void ListConstruct(void *,struct construct *,const char *,struct defmodule *); LOCALE void SetNextConstruct(struct constructHeader *,struct constructHeader *); LOCALE struct defmoduleItemHeader *GetConstructModuleItem(struct constructHeader *); - LOCALE char *GetConstructPPForm(void *,struct constructHeader *); - LOCALE void PPConstructCommand(void *,char *,struct construct *); + LOCALE const char *GetConstructPPForm(void *,struct constructHeader *); + LOCALE void PPConstructCommand(void *,const char *,struct construct *); LOCALE struct constructHeader *GetNextConstructItem(void *,struct constructHeader *,int); LOCALE struct defmoduleItemHeader *GetConstructModuleItemByIndex(void *,struct defmodule *,int); LOCALE void FreeConstructHeaderModule(void *,struct defmoduleItemHeader *, @@ -78,11 +86,11 @@ LOCALE void DoForAllConstructsInModule(void *,void *, void (*)(void *,struct constructHeader *,void *), int,int,void *); - LOCALE void InitializeConstructHeader(void *,char *,struct constructHeader *,SYMBOL_HN *); - LOCALE void SetConstructPPForm(void *,struct constructHeader *,char *); - LOCALE void *LookupConstruct(void *,struct construct *,char *,intBool); + LOCALE void InitializeConstructHeader(void *,const char *,struct constructHeader *,SYMBOL_HN *); + LOCALE void SetConstructPPForm(void *,struct constructHeader *,const char *); + LOCALE void *LookupConstruct(void *,struct construct *,const char *,intBool); #if DEBUGGING_FUNCTIONS - LOCALE unsigned ConstructPrintWatchAccess(void *,struct construct *,char *, + LOCALE unsigned ConstructPrintWatchAccess(void *,struct construct *,const char *, EXPRESSION *, unsigned (*)(void *,void *), void (*)(void *,unsigned,void *)); diff --git a/src/cstrcpsr.c b/src/cstrcpsr.c index b01a652..80168b2 100644 --- a/src/cstrcpsr.c +++ b/src/cstrcpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT PARSER MODULE */ /*******************************************************/ @@ -25,6 +25,22 @@ /* */ /* Added pragmas to remove compilation warnings. */ /* */ +/* 6.30: Added code for capturing errors/warnings. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, MAC_MCW, */ +/* and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #define _CSTRCPSR_SOURCE_ @@ -36,6 +52,7 @@ #include <stdio.h> #define _STDIO_INCLUDED_ #include <stdlib.h> +#include <string.h> #include "envrnmnt.h" #include "router.h" @@ -43,6 +60,7 @@ #include "constrct.h" #include "prcdrpsr.h" #include "exprnpsr.h" +#include "memalloc.h" #include "modulutl.h" #include "modulpsr.h" #include "sysdep.h" @@ -54,7 +72,18 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int FindConstructBeginning(void *,char *,struct token *,int,int *); + static int FindConstructBeginning(void *,const char *,struct token *,int,int *); + +/************************************************/ +/* Load: C access routine for the load command. */ +/************************************************/ +#if ALLOW_ENVIRONMENT_GLOBALS +globle int Load( + const char *fileName) + { + return EnvLoad(GetCurrentEnvironment(),fileName); + } +#endif /************************************************************/ /* EnvLoad: C access routine for the load command. Returns */ @@ -65,9 +94,10 @@ /************************************************************/ globle int EnvLoad( void *theEnv, - char *fileName) + const char *fileName) { FILE *theFile; + char *oldParsingFileName; int noErrorsDetected; /*=======================================*/ @@ -83,7 +113,15 @@ globle int EnvLoad( /*===================================================*/ SetFastLoad(theEnv,theFile); + + oldParsingFileName = CopyString(theEnv,EnvGetParsingFileName(theEnv)); + EnvSetParsingFileName(theEnv,fileName); + noErrorsDetected = LoadConstructsFromLogicalName(theEnv,(char *) theFile); + + EnvSetParsingFileName(theEnv,oldParsingFileName); + DeleteString(theEnv,oldParsingFileName); + SetFastLoad(theEnv,NULL); /*=================*/ @@ -102,43 +140,106 @@ globle int EnvLoad( return(-1); } -/************************************************************/ -/* EnvStringLoad: C access routine for the load command. */ -/* Returns 0 if the string is null, -1 if the string is */ -/* valid but an error occurred while loading constructs, */ -/* and 1 if the string is valid and no errors occured */ -/* while loading. */ -/************************************************************/ -globle int EnvStringLoad( +/*******************************************************/ +/* EnvSetParsingFileName: Sets the file name currently */ +/* being parsed by the load/batch command. */ +/*******************************************************/ +globle void EnvSetParsingFileName( void *theEnv, - char *theString) + const char *fileName) { - int noErrorsDetected; + char *fileNameCopy = NULL; - /*===================================*/ - /* Test whether the string is null. */ - /*===================================*/ + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; - if (theString == NULL) return(0); + if (fileName != NULL) + { + fileNameCopy = (char *) genalloc(theEnv,strlen(fileName) + 1); + genstrcpy(fileNameCopy,fileName); + } - /*===================================================*/ - /* Read in the constructs. Enabling fast load allows */ - /* the router system to be bypassed for quicker load */ - /* times. */ - /*===================================================*/ + if (ConstructData(theEnv)->ParsingFileName != NULL) + { genfree(theEnv,ConstructData(theEnv)->ParsingFileName,strlen(ConstructData(theEnv)->ParsingFileName) + 1); } - SetFastCharLoad(theEnv,theString); - noErrorsDetected = LoadConstructsFromLogicalName(theEnv,theString); - SetFastCharLoad(theEnv,NULL); + ConstructData(theEnv)->ParsingFileName = fileNameCopy; + } - /*========================================*/ - /* If no errors occurred during the load, */ - /* return 1, otherwise return -1. */ - /*========================================*/ +/**********************************************************/ +/* EnvGetParsingFileName: Returns the file name currently */ +/* being parsed by the load/batch command. */ +/**********************************************************/ +globle char *EnvGetParsingFileName( + void *theEnv) + { + return ConstructData(theEnv)->ParsingFileName; + } - if (noErrorsDetected) return(1); +/**********************************************/ +/* EnvSetErrorFileName: Sets the file name */ +/* associated with the last error detected. */ +/**********************************************/ +globle void EnvSetErrorFileName( + void *theEnv, + const char *fileName) + { + char *fileNameCopy = NULL; - return(-1); + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; + + if (fileName != NULL) + { + fileNameCopy = (char *) genalloc(theEnv,strlen(fileName) + 1); + genstrcpy(fileNameCopy,fileName); + } + + if (ConstructData(theEnv)->ErrorFileName != NULL) + { genfree(theEnv,ConstructData(theEnv)->ErrorFileName,strlen(ConstructData(theEnv)->ErrorFileName) + 1); } + + ConstructData(theEnv)->ErrorFileName = fileNameCopy; + } + +/**********************************************/ +/* EnvGetErrorFileName: Returns the file name */ +/* associated with the last error detected. */ +/**********************************************/ +globle char *EnvGetErrorFileName( + void *theEnv) + { + return ConstructData(theEnv)->ErrorFileName; + } + +/************************************************/ +/* EnvSetWarningFileName: Sets the file name */ +/* associated with the last warning detected. */ +/************************************************/ +globle void EnvSetWarningFileName( + void *theEnv, + const char *fileName) + { + char *fileNameCopy = NULL; + + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; + + if (fileName != NULL) + { + fileNameCopy = (char *) genalloc(theEnv,strlen(fileName) + 1); + genstrcpy(fileNameCopy,fileName); + } + + if (ConstructData(theEnv)->WarningFileName != NULL) + { genfree(theEnv,ConstructData(theEnv)->WarningFileName,strlen(ConstructData(theEnv)->WarningFileName) + 1); } + + ConstructData(theEnv)->WarningFileName = fileNameCopy; + } + +/************************************************/ +/* EnvGetWarningFileName: Returns the file name */ +/* associated with the last warning detected. */ +/************************************************/ +globle char *EnvGetWarningFileName( + void *theEnv) + { + return ConstructData(theEnv)->WarningFileName; } /*****************************************************************/ @@ -147,26 +248,52 @@ globle int EnvStringLoad( /*****************************************************************/ globle int LoadConstructsFromLogicalName( void *theEnv, - char *readSource) + const char *readSource) { int constructFlag; struct token theToken; int noErrors = TRUE; int foundConstruct; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; + long oldLineCountValue; + const char *oldLineCountRouter; + + /*===================================================*/ + /* Create a router to capture the error information. */ + /*===================================================*/ + + CreateErrorCaptureRouter(theEnv); + + /*==============================*/ + /* Initialize the line counter. */ + /*==============================*/ + + oldLineCountValue = SetLineCount(theEnv,1); + oldLineCountRouter = RouterData(theEnv)->LineCountRouter; + RouterData(theEnv)->LineCountRouter = readSource; /*=========================================*/ /* Reset the halt execution and evaluation */ /* error flags in preparation for parsing. */ /*=========================================*/ - if (EvaluationData(theEnv)->CurrentEvaluationDepth == 0) SetHaltExecution(theEnv,FALSE); + if (UtilityData(theEnv)->CurrentGarbageFrame->topLevel) SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); + /*==========================================*/ + /* Set up the frame for garbage collection. */ + /*==========================================*/ + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + /*========================================================*/ /* Find the beginning of the first construct in the file. */ /*========================================================*/ - EvaluationData(theEnv)->CurrentEvaluationDepth++; GetToken(theEnv,readSource,&theToken); foundConstruct = FindConstructBeginning(theEnv,readSource,&theToken,FALSE,&noErrors); @@ -200,6 +327,9 @@ globle int LoadConstructsFromLogicalName( EnvPrintRouter(theEnv,WERROR,"\nERROR:\n"); PrintInChunks(theEnv,WERROR,GetPPBuffer(theEnv)); EnvPrintRouter(theEnv,WERROR,"\n"); + + FlushParsingMessages(theEnv); + noErrors = FALSE; GetToken(theEnv,readSource,&theToken); foundConstruct = FindConstructBeginning(theEnv,readSource,&theToken,TRUE,&noErrors); @@ -211,6 +341,7 @@ globle int LoadConstructsFromLogicalName( else { + FlushParsingMessages(theEnv); GetToken(theEnv,readSource,&theToken); foundConstruct = FindConstructBeginning(theEnv,readSource,&theToken,FALSE,&noErrors); } @@ -219,18 +350,18 @@ globle int LoadConstructsFromLogicalName( /* Yield time if necessary to foreground applications. */ /*=====================================================*/ - if (foundConstruct) + if (foundConstruct) { IncrementSymbolCount(theToken.value); } - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); - YieldTime(theEnv); - EvaluationData(theEnv)->CurrentEvaluationDepth++; - if (foundConstruct) + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + + YieldTime(theEnv); + + if (foundConstruct) { DecrementSymbolCount(theEnv,(SYMBOL_HN *) theToken.value); } } - EvaluationData(theEnv)->CurrentEvaluationDepth--; - /*========================================================*/ /* Print a carriage return if a single character is being */ /* printed to indicate constructs are being processed. */ @@ -253,6 +384,28 @@ globle int LoadConstructsFromLogicalName( DestroyPPBuffer(theEnv); + /*======================================*/ + /* Remove the garbage collection frame. */ + /*======================================*/ + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + + /*==============================*/ + /* Deactivate the line counter. */ + /*==============================*/ + + SetLineCount(theEnv,oldLineCountValue); + RouterData(theEnv)->LineCountRouter = oldLineCountRouter; + + /*===========================================*/ + /* Invoke the parser error callback function */ + /* and delete the error capture router. */ + /*===========================================*/ + + FlushParsingMessages(theEnv); + DeleteErrorCaptureRouter(theEnv); + /*==========================================================*/ /* Return a boolean flag which indicates whether any errors */ /* were encountered while loading the constructs. */ @@ -269,7 +422,7 @@ globle int LoadConstructsFromLogicalName( /********************************************************************/ static int FindConstructBeginning( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int errorCorrection, int *noErrors) @@ -366,6 +519,169 @@ static int FindConstructBeginning( return(FALSE); } +#if (! RUN_TIME) && (! BLOAD_ONLY) + +/*************************************************/ +/* FindError: Find routine for the error router. */ +/*************************************************/ +static int FindError( + void *theEnv, + const char *logicalName) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + + if ( (strcmp(logicalName,WERROR) == 0) || + (strcmp(logicalName,WWARNING) == 0) ) + { return(TRUE); } + + return(FALSE); + } + +/***************************************************/ +/* PrintError: Print routine for the error router. */ +/***************************************************/ +static int PrintError( + void *theEnv, + const char *logicalName, + const char *str) + { + if (strcmp(logicalName,WERROR) == 0) + { + ConstructData(theEnv)->ErrorString = + AppendToString(theEnv,str,ConstructData(theEnv)->ErrorString, + &ConstructData(theEnv)->CurErrPos, + &ConstructData(theEnv)->MaxErrChars); + } + else if (strcmp(logicalName,WWARNING) == 0) + { + ConstructData(theEnv)->WarningString = + AppendToString(theEnv,str,ConstructData(theEnv)->WarningString, + &ConstructData(theEnv)->CurWrnPos, + &ConstructData(theEnv)->MaxWrnChars); + } + + EnvDeactivateRouter(theEnv,"error-capture"); + EnvPrintRouter(theEnv,logicalName,str); + EnvActivateRouter(theEnv,"error-capture"); + + return(1); + } + +/***********************************************/ +/* CreateErrorCaptureRouter: Creates the error */ +/* capture router if it doesn't exists. */ +/***********************************************/ +globle void CreateErrorCaptureRouter( + void *theEnv) + { + /*===========================================================*/ + /* Don't bother creating the error capture router if there's */ + /* no parser callback. The implication of this is that the */ + /* parser callback should be created before any routines */ + /* which could generate errors are called. */ + /*===========================================================*/ + + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; + + /*=======================================================*/ + /* If the router hasn't already been created, create it. */ + /*=======================================================*/ + + if (ConstructData(theEnv)->errorCaptureRouterCount == 0) + { + EnvAddRouter(theEnv,"error-capture", 40, + FindError, PrintError, + NULL, NULL,NULL); + } + + /*==================================================*/ + /* Increment the count for the number of references */ + /* that want the error capture router functioning. */ + /*==================================================*/ + + ConstructData(theEnv)->errorCaptureRouterCount++; + } + +/***********************************************/ +/* DeleteErrorCaptureRouter: Deletes the error */ +/* capture router if it exists. */ +/***********************************************/ +globle void DeleteErrorCaptureRouter( + void *theEnv) + { + /*===========================================================*/ + /* Don't bother deleting the error capture router if there's */ + /* no parser callback. The implication of this is that the */ + /* parser callback should be created before any routines */ + /* which could generate errors are called. */ + /*===========================================================*/ + + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; + + ConstructData(theEnv)->errorCaptureRouterCount--; + + if (ConstructData(theEnv)->errorCaptureRouterCount == 0) + { EnvDeleteRouter(theEnv,"error-capture"); } + } + +/*******************************************************/ +/* FlushParsingMessages: Invokes the callback routines */ +/* for any existing warning/error messages. */ +/*******************************************************/ +globle void FlushParsingMessages( + void *theEnv) + { + /*===========================================================*/ + /* Don't bother flushing the error capture router if there's */ + /* no parser callback. The implication of this is that the */ + /* parser callback should be created before any routines */ + /* which could generate errors are called. */ + /*===========================================================*/ + + if (ConstructData(theEnv)->ParserErrorCallback == NULL) return; + + /*=================================*/ + /* If an error occurred invoke the */ + /* parser error callback function. */ + /*=================================*/ + + if (ConstructData(theEnv)->ErrorString != NULL) + { + (*ConstructData(theEnv)->ParserErrorCallback)(theEnv,EnvGetErrorFileName(theEnv), + NULL,ConstructData(theEnv)->ErrorString, + ConstructData(theEnv)->ErrLineNumber); + } + + if (ConstructData(theEnv)->WarningString != NULL) + { + (*ConstructData(theEnv)->ParserErrorCallback)(theEnv,EnvGetWarningFileName(theEnv), + ConstructData(theEnv)->WarningString,NULL, + ConstructData(theEnv)->WrnLineNumber); + } + + /*===================================*/ + /* Delete the error capture strings. */ + /*===================================*/ + + EnvSetErrorFileName(theEnv,NULL); + if (ConstructData(theEnv)->ErrorString != NULL) + { genfree(theEnv,ConstructData(theEnv)->ErrorString,strlen(ConstructData(theEnv)->ErrorString) + 1); } + ConstructData(theEnv)->ErrorString = NULL; + ConstructData(theEnv)->CurErrPos = 0; + ConstructData(theEnv)->MaxErrChars = 0; + + EnvSetWarningFileName(theEnv,NULL); + if (ConstructData(theEnv)->WarningString != NULL) + { genfree(theEnv,ConstructData(theEnv)->WarningString,strlen(ConstructData(theEnv)->WarningString) + 1); } + ConstructData(theEnv)->WarningString = NULL; + ConstructData(theEnv)->CurWrnPos = 0; + ConstructData(theEnv)->MaxWrnChars = 0; + } + +#endif + /***********************************************************/ /* ParseConstruct: Parses a construct. Returns an integer. */ /* -1 if the construct name has no parsing function, 0 */ @@ -374,11 +690,13 @@ static int FindConstructBeginning( /***********************************************************/ globle int ParseConstruct( void *theEnv, - char *name, - char *logicalName) + const char *name, + const char *logicalName) { struct construct *currentPtr; int rv, ov; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; /*=================================*/ /* Look for a valid construct name */ @@ -388,6 +706,15 @@ globle int ParseConstruct( currentPtr = FindConstruct(theEnv,name); if (currentPtr == NULL) return(-1); + /*==========================================*/ + /* Set up the frame for garbage collection. */ + /*==========================================*/ + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + /*==================================*/ /* Prepare the parsing environment. */ /*==================================*/ @@ -399,25 +726,32 @@ globle int ParseConstruct( PushRtnBrkContexts(theEnv); ExpressionData(theEnv)->ReturnContext = FALSE; ExpressionData(theEnv)->BreakContext = FALSE; - EvaluationData(theEnv)->CurrentEvaluationDepth++; /*=======================================*/ /* Call the construct's parsing routine. */ /*=======================================*/ + ConstructData(theEnv)->ParsingConstruct = TRUE; rv = (*currentPtr->parseFunction)(theEnv,logicalName); + ConstructData(theEnv)->ParsingConstruct = FALSE; /*===============================*/ /* Restore environment settings. */ /*===============================*/ - EvaluationData(theEnv)->CurrentEvaluationDepth--; PopRtnBrkContexts(theEnv); ClearParsedBindNames(theEnv); SetPPBufferStatus(theEnv,OFF); SetHaltExecution(theEnv,ov); + /*======================================*/ + /* Remove the garbage collection frame. */ + /*======================================*/ + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + /*==============================*/ /* Return the status of parsing */ /* the construct. */ @@ -431,22 +765,20 @@ globle int ParseConstruct( /* field of a construct. Returns name of the construct */ /* if no errors are detected, otherwise returns NULL. */ /*********************************************************/ -#if IBM_TBC && (! DEBUGGING_FUNCTIONS) -#pragma argsused -#endif globle SYMBOL_HN *GetConstructNameAndComment( void *theEnv, - char *readSource, + const char *readSource, struct token *inputToken, - char *constructName, - void *(*findFunction)(void *,char *), + const char *constructName, + void *(*findFunction)(void *,const char *), int (*deleteFunction)(void *,void *), - char *constructSymbol, + const char *constructSymbol, int fullMessageCR, int getComment, - int moduleNameAllowed) + int moduleNameAllowed, + int ignoreRedefinition) { -#if (MAC_MCW || IBM_MCW || MAC_XCD) && (! DEBUGGING_FUNCTIONS) +#if (MAC_XCD) && (! DEBUGGING_FUNCTIONS) #pragma unused(fullMessageCR) #endif SYMBOL_HN *name, *moduleName; @@ -573,19 +905,21 @@ globle SYMBOL_HN *GetConstructNameAndComment( if ((EnvGetWatchItem(theEnv,"compilations") == TRUE) && GetPrintWhileLoading(theEnv) && (! ConstructData(theEnv)->CheckSyntaxMode)) { - if (redefining) + const char *outRouter = WDIALOG; + if (redefining && (! ignoreRedefinition)) { + outRouter = WWARNING; PrintWarningID(theEnv,"CSTRCPSR",1,TRUE); - EnvPrintRouter(theEnv,WDIALOG,"Redefining "); + EnvPrintRouter(theEnv,outRouter,"Redefining "); } - else EnvPrintRouter(theEnv,WDIALOG,"Defining "); + else EnvPrintRouter(theEnv,outRouter,"Defining "); - EnvPrintRouter(theEnv,WDIALOG,constructName); - EnvPrintRouter(theEnv,WDIALOG,": "); - EnvPrintRouter(theEnv,WDIALOG,ValueToString(name)); + EnvPrintRouter(theEnv,outRouter,constructName); + EnvPrintRouter(theEnv,outRouter,": "); + EnvPrintRouter(theEnv,outRouter,ValueToString(name)); - if (fullMessageCR) EnvPrintRouter(theEnv,WDIALOG,"\n"); - else EnvPrintRouter(theEnv,WDIALOG," "); + if (fullMessageCR) EnvPrintRouter(theEnv,outRouter,"\n"); + else EnvPrintRouter(theEnv,outRouter," "); } else #endif @@ -684,10 +1018,10 @@ globle void RemoveConstructFromModule( /******************************************************/ globle void ImportExportConflictMessage( void *theEnv, - char *constructName, - char *itemName, - char *causedByConstruct, - char *causedByName) + const char *constructName, + const char *itemName, + const char *causedByConstruct, + const char *causedByName) { PrintErrorID(theEnv,"CSTRCPSR",3,TRUE); EnvPrintRouter(theEnv,WERROR,"Cannot define "); diff --git a/src/cstrcpsr.h b/src/cstrcpsr.h index 31cc66a..8010873 100644 --- a/src/cstrcpsr.h +++ b/src/cstrcpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT PARSER MODULE */ /*******************************************************/ @@ -17,35 +17,32 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Made the construct redefinition message more */ +/* prominent. */ +/* */ +/* Added pragmas to remove compilation warnings. */ +/* */ +/* 6.30: Added code for capturing errors/warnings. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, MAC_MCW, */ +/* and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ -// -//Copyright(c) 2012 Samsung Electronics Co., Ltd. All rights reserved -//on modified portion of CLIPS. -//Except as noted, this software is licensed under Apache License, Version 2. -//Please, see the LICENSE file for Apache License terms and conditions. -// -//This original version of this software is under public domain. Please, see -//the readme.txt file for original software license information. - - -// -// Open Service Platform -// Copyright (c) 2012 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - #ifndef _H_cstrcpsr #define _H_cstrcpsr @@ -70,23 +67,31 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Load(theEnv,a) EnvLoad(theEnv,a) -#else -#define Load(a) EnvLoad(GetCurrentEnvironment(),a) +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE int Load(const char *); #endif - LOCALE int EnvLoad(void *,char *); - LOCALE int EnvStringLoad(void *,char *); - LOCALE int LoadConstructsFromLogicalName(void *,char *); - LOCALE int ParseConstruct(void *,char *,char *); + LOCALE int EnvLoad(void *,const char *); + LOCALE int LoadConstructsFromLogicalName(void *,const char *); + LOCALE int ParseConstruct(void *,const char *,const char *); LOCALE void RemoveConstructFromModule(void *,struct constructHeader *); - LOCALE struct symbolHashNode *GetConstructNameAndComment(void *,char *, - struct token *,char *, - void *(*)(void *,char *), - int (*)(void *,void *), - char *,int,int,int); - LOCALE void ImportExportConflictMessage(void *,char *,char *,char *,char *); + LOCALE struct symbolHashNode *GetConstructNameAndComment(void *,const char *, + struct token *,const char *, + void *(*)(void *,const char *), + int (*)(void *,void *), + const char *,int,int,int,int); + LOCALE void ImportExportConflictMessage(void *,const char *,const char *,const char *,const char *); +#if (! RUN_TIME) && (! BLOAD_ONLY) + LOCALE void FlushParsingMessages(void *); + LOCALE char *EnvGetParsingFileName(void *); + LOCALE void EnvSetParsingFileName(void *,const char *); + LOCALE char *EnvGetErrorFileName(void *); + LOCALE void EnvSetErrorFileName(void *,const char *); + LOCALE char *EnvGetWarningFileName(void *); + LOCALE void EnvSetWarningFileName(void *,const char *); + LOCALE void CreateErrorCaptureRouter(void *); + LOCALE void DeleteErrorCaptureRouter(void *); +#endif #endif diff --git a/src/cstrnbin.c b/src/cstrnbin.c index 57f6474..ec2edcb 100644 --- a/src/cstrnbin.c +++ b/src/cstrnbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT BLOAD/BSAVE MODULE */ /*******************************************************/ @@ -14,11 +14,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #define _CSTRNBIN_SOURCE_ @@ -134,7 +137,7 @@ globle void WriteNeededConstraints( /* constraints in the constraint table. */ /*============================================*/ - GenWrite(&numberOfUsedConstraints,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&numberOfUsedConstraints,sizeof(unsigned long int),fp); if (numberOfUsedConstraints == 0) return; for (i = 0 ; i < SIZE_CONSTRAINT_HASH; i++) @@ -144,8 +147,7 @@ globle void WriteNeededConstraints( tmpPtr = tmpPtr->next) { CopyToBsaveConstraintRecord(theEnv,tmpPtr,&bsaveConstraints); - GenWrite(&bsaveConstraints, - (unsigned long) sizeof(BSAVE_CONSTRAINT_RECORD),fp); + GenWrite(&bsaveConstraints,sizeof(BSAVE_CONSTRAINT_RECORD),fp); } } } @@ -196,13 +198,11 @@ static void CopyToBsaveConstraintRecord( globle void ReadNeededConstraints( void *theEnv) { - GenReadBinary(theEnv,(void *) &ConstraintData(theEnv)->NumberOfConstraints,(unsigned long) - sizeof(unsigned long int)); + GenReadBinary(theEnv,(void *) &ConstraintData(theEnv)->NumberOfConstraints,sizeof(unsigned long int)); if (ConstraintData(theEnv)->NumberOfConstraints == 0) return; ConstraintData(theEnv)->ConstraintArray = (CONSTRAINT_RECORD *) - genlongalloc(theEnv,(unsigned long) (sizeof(CONSTRAINT_RECORD) * - ConstraintData(theEnv)->NumberOfConstraints)); + genalloc(theEnv,(sizeof(CONSTRAINT_RECORD) * ConstraintData(theEnv)->NumberOfConstraints)); BloadandRefresh(theEnv,ConstraintData(theEnv)->NumberOfConstraints,sizeof(BSAVE_CONSTRAINT_RECORD), CopyFromBsaveConstraintRecord); @@ -262,9 +262,8 @@ globle void ClearBloadedConstraints( { if (ConstraintData(theEnv)->NumberOfConstraints != 0) { - genlongfree(theEnv,(void *) ConstraintData(theEnv)->ConstraintArray, - (unsigned long) (sizeof(CONSTRAINT_RECORD) * - ConstraintData(theEnv)->NumberOfConstraints)); + genfree(theEnv,(void *) ConstraintData(theEnv)->ConstraintArray, + (sizeof(CONSTRAINT_RECORD) * ConstraintData(theEnv)->NumberOfConstraints)); ConstraintData(theEnv)->NumberOfConstraints = 0; } } diff --git a/src/cstrnbin.h b/src/cstrnbin.h index 7d9f597..4a2d545 100644 --- a/src/cstrnbin.h +++ b/src/cstrnbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT BLOAD/BSAVE/CONSTRUCTS-TO-C HEADER */ /*******************************************************/ @@ -17,6 +17,10 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added allowed-classes slot facet. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_cstrnbin @@ -53,6 +57,6 @@ LOCALE void ReadNeededConstraints(void *); LOCALE void ClearBloadedConstraints(void *); -#endif +#endif /* _H_cstrnbin */ diff --git a/src/cstrnchk.c b/src/cstrnchk.c index c9e87f5..aa6f467 100644 --- a/src/cstrnchk.c +++ b/src/cstrnchk.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONSTRAINT CHECKING MODULE */ /*******************************************************/ @@ -14,9 +14,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -25,6 +26,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Dynamic constraint checking for the */ +/* allowed-classes constraint now searches */ +/* imported modules. */ +/* */ /*************************************************************/ #define _CSTRNCHK_SOURCE_ @@ -57,7 +71,7 @@ static int CheckFunctionReturnType(int,CONSTRAINT_RECORD *); static intBool CheckTypeConstraint(int,CONSTRAINT_RECORD *); static intBool CheckRangeConstraint(void *,int,void *,CONSTRAINT_RECORD *); - static void PrintRange(void *,char *,CONSTRAINT_RECORD *); + static void PrintRange(void *,const char *,CONSTRAINT_RECORD *); /******************************************************/ /* CheckFunctionReturnType: Checks a functions return */ @@ -121,6 +135,10 @@ static int CheckFunctionReturnType( if (constraints->instanceAddressesAllowed) return(TRUE); else return(FALSE); + case 'y': + if (constraints->factAddressesAllowed) return(TRUE); + else return(FALSE); + case 'o': if (constraints->instanceNamesAllowed) return(TRUE); else return(FALSE); @@ -406,7 +424,7 @@ globle intBool CheckAllowedClassesConstraint( /* The constraint is satisfied if there */ /* aren't any class restrictions. */ /*======================================*/ - + if (constraints->classList == NULL) { return(TRUE); } @@ -414,7 +432,7 @@ globle intBool CheckAllowedClassesConstraint( /* Class restrictions only apply to */ /* instances and instance names. */ /*==================================*/ - + if ((type != INSTANCE_ADDRESS) && (type != INSTANCE_NAME)) { return(TRUE); } @@ -422,15 +440,15 @@ globle intBool CheckAllowedClassesConstraint( /* If an instance name is specified, determine */ /* whether the instance exists. */ /*=============================================*/ - + if (type == INSTANCE_ADDRESS) { ins = (INSTANCE_TYPE *) vPtr; } else { ins = FindInstanceBySymbol(theEnv,(SYMBOL_HN *) vPtr); } - + if (ins == NULL) { return(FALSE); } - + /*======================================================*/ /* Search through the class list to see if the instance */ /* belongs to one of the allowed classes in the list. */ @@ -441,7 +459,8 @@ globle intBool CheckAllowedClassesConstraint( tmpPtr != NULL; tmpPtr = tmpPtr->nextArg) { - cmpClass = (DEFCLASS *) EnvFindDefclass(theEnv,ValueToString(tmpPtr->value)); + //cmpClass = (DEFCLASS *) EnvFindDefclass(theEnv,ValueToString(tmpPtr->value)); + cmpClass = (DEFCLASS *) LookupDefclassByMdlOrScope(theEnv,ValueToString(tmpPtr->value)); if (cmpClass == NULL) continue; if (cmpClass == insClass) return(TRUE); if (EnvSubclassP(theEnv,insClass,cmpClass)) return(TRUE); @@ -455,7 +474,7 @@ globle intBool CheckAllowedClassesConstraint( return(FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(type) #pragma unused(vPtr) @@ -463,7 +482,7 @@ globle intBool CheckAllowedClassesConstraint( #endif return(TRUE); -#endif +#endif } /*************************************************************/ @@ -532,8 +551,8 @@ static intBool CheckRangeConstraint( /************************************************/ globle void ConstraintViolationErrorMessage( void *theEnv, - char *theWhat, - char *thePlace, + const char *theWhat, + const char *thePlace, int command, int thePattern, struct symbolHashNode *theSlot, @@ -623,7 +642,7 @@ globle void ConstraintViolationErrorMessage( else if (theField > 0) { EnvPrintRouter(theEnv,WERROR," for field #"); - PrintLongInteger(theEnv,WERROR,(long) theField); + PrintLongInteger(theEnv,WERROR,(long long) theField); } EnvPrintRouter(theEnv,WERROR,".\n"); @@ -635,7 +654,7 @@ globle void ConstraintViolationErrorMessage( /********************************************************************/ static void PrintRange( void *theEnv, - char *logicalName, + const char *logicalName, CONSTRAINT_RECORD *theConstraint) { if (theConstraint->minValue->value == SymbolData(theEnv)->NegativeInfinity) diff --git a/src/cstrnchk.h b/src/cstrnchk.h index 533be81..db1ac18 100644 --- a/src/cstrnchk.h +++ b/src/cstrnchk.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONSTRAINT CHECKING HEADER FILE */ /*******************************************************/ @@ -21,6 +21,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Dynamic constraint checking for the */ +/* allowed-classes constraint now searches */ +/* imported modules. */ +/* */ /*************************************************************/ #ifndef _H_cstrnchk @@ -56,7 +69,7 @@ LOCALE intBool CheckAllowedClassesConstraint(void *,int,void *,CONSTRAINT_RECORD *); LOCALE int ConstraintCheckExpressionChain(void *,struct expr *, CONSTRAINT_RECORD *); - LOCALE void ConstraintViolationErrorMessage(void *,char *,char *,int,int, + LOCALE void ConstraintViolationErrorMessage(void *,const char *,const char *,int,int, struct symbolHashNode *, int,int,CONSTRAINT_RECORD *, int); @@ -70,7 +83,7 @@ LOCALE intBool UnmatchableConstraint(struct constraintRecord *); #endif -#endif +#endif /* _H_cstrnchk */ diff --git a/src/cstrncmp.c b/src/cstrncmp.c index a719b27..1b54c92 100644 --- a/src/cstrncmp.c +++ b/src/cstrncmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -22,6 +22,12 @@ /* */ /* Added environment parameter to GenClose. */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _CSTRNCMP_SOURCE_ @@ -47,7 +53,9 @@ /***********************************************/ globle int ConstraintsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -100,7 +108,7 @@ globle int ConstraintsToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,fileID,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -186,7 +194,7 @@ globle int ConstraintsToCode( arrayVersion++; if (count < numberOfConstraints) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } diff --git a/src/cstrncmp.h b/src/cstrncmp.h index 8000780..026512f 100644 --- a/src/cstrncmp.h +++ b/src/cstrncmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT CONSTRUCTS-TO-C HEADER */ /*******************************************************/ @@ -17,6 +17,16 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added allowed-classes slot facet. */ +/* */ +/* Added environment parameter to GenClose. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_cstrncmp @@ -46,7 +56,7 @@ LOCALE void PrintConstraintReference(void *,FILE *,CONSTRAINT_RECORD *,int,int); LOCALE void ConstraintRecordToCode(FILE *,CONSTRAINT_RECORD *); - LOCALE int ConstraintsToCode(void *,char *,int,FILE *,int,int); + LOCALE int ConstraintsToCode(void *,const char *,const char *,char *,int,FILE *,int,int); -#endif +#endif /* _H_cstrncmp */ diff --git a/src/cstrnops.c b/src/cstrnops.c index cbaa0c8..dfb08c9 100644 --- a/src/cstrnops.c +++ b/src/cstrnops.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT OPERATIONS MODULE */ /*******************************************************/ @@ -295,7 +295,7 @@ static void IntersectAllowedValueExpressions( newConstraint->restrictionList = theHead; } - + /*************************************************/ /* IntersectAllowedClassExpressions: Creates the */ /* intersection of two allowed-classes lists. */ @@ -315,7 +315,7 @@ static void IntersectAllowedClassExpressions( /* each value to a list if it satisfies the */ /* restrictions for both constraint records. */ /*============================================*/ - + for (theList1 = constraint1->classList; theList1 != NULL; theList1 = theList1->nextArg) @@ -359,7 +359,7 @@ static void IntersectAllowedClassExpressions( newConstraint->classList = theHead; } - + /*********************************************************/ /* IntersectNumericExpressions: Creates the intersection */ /* of two range or two min/max-fields constraints. */ diff --git a/src/cstrnops.h b/src/cstrnops.h index 4d2686e..644ff67 100644 --- a/src/cstrnops.h +++ b/src/cstrnops.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT OPERATIONS HEADER FILE */ /*******************************************************/ @@ -48,6 +48,6 @@ LOCALE void RemoveConstantFromConstraint(void *,int,void *,CONSTRAINT_RECORD *); #endif -#endif +#endif /* (! RUN_TIME) */ -#endif +#endif /* _H_cstrnops */ diff --git a/src/cstrnpsr.c b/src/cstrnpsr.c index 1f55b52..434a988 100644 --- a/src/cstrnpsr.c +++ b/src/cstrnpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* CONSTRAINT PARSER MODULE */ /*******************************************************/ @@ -14,9 +14,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -25,6 +26,13 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Slot cardinality bug fix for minimum < 0. */ +/* */ /*************************************************************/ #define _CSTRNPSR_SOURCE_ @@ -42,6 +50,7 @@ #include "scanner.h" #include "cstrnutl.h" #include "cstrnchk.h" +#include "sysdep.h" #include "cstrnpsr.h" @@ -51,21 +60,21 @@ #if (! RUN_TIME) && (! BLOAD_ONLY) static intBool ParseRangeCardinalityAttribute(void *, - char *,CONSTRAINT_RECORD *, + const char *,CONSTRAINT_RECORD *, CONSTRAINT_PARSE_RECORD *, - char *,int); - static intBool ParseTypeAttribute(void *,char *,CONSTRAINT_RECORD *); + const char *,int); + static intBool ParseTypeAttribute(void *,const char *,CONSTRAINT_RECORD *); static void AddToRestrictionList(void *,int,CONSTRAINT_RECORD *, CONSTRAINT_RECORD *); - static intBool ParseAllowedValuesAttribute(void *,char *,char *, + static intBool ParseAllowedValuesAttribute(void *,const char *,const char *, CONSTRAINT_RECORD *, CONSTRAINT_PARSE_RECORD *); - static int GetConstraintTypeFromAllowedName(char *); - static int GetConstraintTypeFromTypeName(char *); - static int GetAttributeParseValue(char *,CONSTRAINT_PARSE_RECORD *); + static int GetConstraintTypeFromAllowedName(const char *); + static int GetConstraintTypeFromTypeName(const char *); + static int GetAttributeParseValue(const char *,CONSTRAINT_PARSE_RECORD *); static void SetRestrictionFlag(int,CONSTRAINT_RECORD *,int); - static void SetParseFlag(CONSTRAINT_PARSE_RECORD *,char *); - static void NoConjunctiveUseError(void *,char *,char *); + static void SetParseFlag(CONSTRAINT_PARSE_RECORD *,const char *); + static void NoConjunctiveUseError(void *,const char *,const char *); #endif /********************************************************************/ @@ -194,8 +203,8 @@ globle intBool CheckConstraintParseConflicts( /********************************************************/ globle void AttributeConflictErrorMessage( void *theEnv, - char *attribute1, - char *attribute2) + const char *attribute1, + const char *attribute2) { PrintErrorID(theEnv,"CSTRNPSR",1,TRUE); EnvPrintRouter(theEnv,WERROR,"The "); @@ -234,7 +243,7 @@ globle void InitializeConstraintParseRecord( /* standard constraints parseable by the routines in this module. */ /************************************************************************/ globle intBool StandardConstraint( - char *constraintName) + const char *constraintName) { if ((strcmp(constraintName,"type") == 0) || (strcmp(constraintName,"range") == 0) || @@ -260,8 +269,8 @@ globle intBool StandardConstraint( /***********************************************************************/ globle intBool ParseStandardConstraint( void *theEnv, - char *readSource, - char *constraintName, + const char *readSource, + const char *constraintName, CONSTRAINT_RECORD *constraints, CONSTRAINT_PARSE_RECORD *parsedConstraints, int multipleValuesAllowed) @@ -496,8 +505,8 @@ static void AddToRestrictionList( /*******************************************************************/ static intBool ParseAllowedValuesAttribute( void *theEnv, - char *readSource, - char *constraintName, + const char *readSource, + const char *constraintName, CONSTRAINT_RECORD *constraints, CONSTRAINT_PARSE_RECORD *parsedConstraints) { @@ -505,7 +514,7 @@ static intBool ParseAllowedValuesAttribute( int expectedType, restrictionType, error = FALSE; struct expr *newValue, *lastValue; int constantParsed = FALSE, variableParsed = FALSE; - char *tempPtr = NULL; + const char *tempPtr = NULL; /*======================================================*/ /* The allowed-values attribute is not allowed if other */ @@ -700,7 +709,7 @@ static intBool ParseAllowedValuesAttribute( else { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); return(FALSE); } @@ -710,7 +719,7 @@ static intBool ParseAllowedValuesAttribute( default: { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); } return(FALSE); @@ -738,7 +747,7 @@ static intBool ParseAllowedValuesAttribute( if (constantParsed && variableParsed) { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); return(FALSE); } @@ -773,7 +782,7 @@ static intBool ParseAllowedValuesAttribute( if ((! constantParsed) && (! variableParsed)) { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); return(FALSE); } @@ -825,9 +834,6 @@ static intBool ParseAllowedValuesAttribute( case INSTANCE_OR_INSTANCE_NAME: constraints->classRestriction = FALSE; break; - - default: - break; } } @@ -853,8 +859,8 @@ static intBool ParseAllowedValuesAttribute( /***********************************************************/ static void NoConjunctiveUseError( void *theEnv, - char *attribute1, - char *attribute2) + const char *attribute1, + const char *attribute2) { PrintErrorID(theEnv,"CSTRNPSR",3,TRUE); EnvPrintRouter(theEnv,WERROR,"The "); @@ -870,7 +876,7 @@ static void NoConjunctiveUseError( /**************************************************/ static intBool ParseTypeAttribute( void *theEnv, - char *readSource, + const char *readSource, CONSTRAINT_RECORD *constraints) { int typeParsed = FALSE; @@ -1016,15 +1022,15 @@ static intBool ParseTypeAttribute( /***************************************************************************/ static intBool ParseRangeCardinalityAttribute( void *theEnv, - char *readSource, + const char *readSource, CONSTRAINT_RECORD *constraints, CONSTRAINT_PARSE_RECORD *parsedConstraints, - char *constraintName, + const char *constraintName, int multipleValuesAllowed) { struct token inputToken; int range; - char *tempPtr = NULL; + const char *tempPtr = NULL; /*=================================*/ /* Determine if we're parsing the */ @@ -1089,6 +1095,13 @@ static intBool ParseRangeCardinalityAttribute( } else { + if (ValueToLong(inputToken.value) < 0LL) + { + PrintErrorID(theEnv,"CSTRNPSR",6,TRUE); + EnvPrintRouter(theEnv,WERROR,"Minimum cardinality value must be greater than or equal to zero\n"); + return(FALSE); + } + ReturnExpression(theEnv,constraints->minFields); constraints->minFields = GenConstant(theEnv,inputToken.type,inputToken.value); } @@ -1098,7 +1111,7 @@ static intBool ParseRangeCardinalityAttribute( else { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); return(FALSE); } @@ -1127,7 +1140,7 @@ static intBool ParseRangeCardinalityAttribute( else { char tempBuffer[120]; - sprintf(tempBuffer,"%s attribute",constraintName); + gensprintf(tempBuffer,"%s attribute",constraintName); SyntaxErrorMessage(theEnv,tempBuffer); return(FALSE); } @@ -1187,7 +1200,7 @@ static intBool ParseRangeCardinalityAttribute( /* associated with an allowed-... attribute. */ /******************************************************************/ static int GetConstraintTypeFromAllowedName( - char *constraintName) + const char *constraintName) { if (strcmp(constraintName,"allowed-values") == 0) return(UNKNOWN_VALUE); else if (strcmp(constraintName,"allowed-symbols") == 0) return(SYMBOL); @@ -1207,7 +1220,7 @@ static int GetConstraintTypeFromAllowedName( /* to its equivalent integer type restriction. */ /*******************************************************/ static int GetConstraintTypeFromTypeName( - char *constraintName) + const char *constraintName) { if (strcmp(constraintName,"SYMBOL") == 0) return(SYMBOL); else if (strcmp(constraintName,"STRING") == 0) return(STRING); @@ -1229,7 +1242,7 @@ static int GetConstraintTypeFromTypeName( /* whether a specific attribute has already been parsed. */ /**************************************************************/ static int GetAttributeParseValue( - char *constraintName, + const char *constraintName, CONSTRAINT_PARSE_RECORD *parsedConstraints) { if (strcmp(constraintName,"type") == 0) @@ -1309,9 +1322,6 @@ static void SetRestrictionFlag( case INSTANCE_OR_INSTANCE_NAME: constraints->classRestriction = value; break; - - default: - break; } } @@ -1321,7 +1331,7 @@ static void SetRestrictionFlag( /********************************************************************/ static void SetParseFlag( CONSTRAINT_PARSE_RECORD *parsedConstraints, - char *constraintName) + const char *constraintName) { if (strcmp(constraintName,"range") == 0) { parsedConstraints->range = TRUE; } diff --git a/src/cstrnpsr.h b/src/cstrnpsr.h index e85ec5d..cf5c4ca 100644 --- a/src/cstrnpsr.h +++ b/src/cstrnpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT PARSER HEADER FILE */ /*******************************************************/ @@ -16,10 +16,20 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_cstrnpsr @@ -58,11 +68,11 @@ struct constraintParseRecord typedef struct constraintParseRecord CONSTRAINT_PARSE_RECORD; LOCALE intBool CheckConstraintParseConflicts(void *,CONSTRAINT_RECORD *); - LOCALE void AttributeConflictErrorMessage(void *,char *,char *); + LOCALE void AttributeConflictErrorMessage(void *,const char *,const char *); #if (! RUN_TIME) && (! BLOAD_ONLY) LOCALE void InitializeConstraintParseRecord(CONSTRAINT_PARSE_RECORD *); - LOCALE intBool StandardConstraint(char *); - LOCALE intBool ParseStandardConstraint(void *,char *,char *, + LOCALE intBool StandardConstraint(const char *); + LOCALE intBool ParseStandardConstraint(void *,const char *,const char *, CONSTRAINT_RECORD *, CONSTRAINT_PARSE_RECORD *, int); @@ -70,9 +80,9 @@ typedef struct constraintParseRecord CONSTRAINT_PARSE_RECORD; CONSTRAINT_RECORD *,CONSTRAINT_RECORD *); LOCALE void OverlayConstraintParseRecord(CONSTRAINT_PARSE_RECORD *, CONSTRAINT_PARSE_RECORD *); -#endif +#endif /* (! RUN_TIME) && (! BLOAD_ONLY) */ -#endif +#endif /* _H_cstrnpsr */ diff --git a/src/cstrnutl.c b/src/cstrnutl.c index 3fcda5e..f871c83 100644 --- a/src/cstrnutl.c +++ b/src/cstrnutl.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT UTILITY MODULE */ /*******************************************************/ @@ -14,11 +14,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ +/* */ /* 6.24: Added allowed-classes slot facet. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ /*************************************************************/ #define _CSTRNUTL_SOURCE_ @@ -283,9 +286,6 @@ globle int SetConstraintType( rv = constraints->multifieldsAllowed; constraints->multifieldsAllowed = TRUE; break; - - default: - break; } if (theType != UNKNOWN_VALUE) constraints->anyAllowed = FALSE; @@ -506,6 +506,7 @@ globle CONSTRAINT_RECORD *FunctionCallToConstraintRecord( break; case 'i': + case 'g': case 'l': rv->integersAllowed = TRUE; break; @@ -554,12 +555,13 @@ globle CONSTRAINT_RECORD *FunctionCallToConstraintRecord( rv->instanceAddressesAllowed = TRUE; break; + case 'y': + rv->factAddressesAllowed = TRUE; + break; + case 'v': rv->voidAllowed = TRUE; break; - - default: - break; } return(rv); @@ -681,9 +683,6 @@ globle CONSTRAINT_RECORD *ArgumentTypeToConstraintRecord( case 'v': rv->voidAllowed = TRUE; break; - - default: - break; } return(rv); diff --git a/src/cstrnutl.h b/src/cstrnutl.h index 2ea8ded..a763749 100644 --- a/src/cstrnutl.h +++ b/src/cstrnutl.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRAINT UTILITY HEADER FILE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ /* */ @@ -52,6 +52,6 @@ LOCALE CONSTRAINT_RECORD *FunctionCallToConstraintRecord(void *,void *); LOCALE CONSTRAINT_RECORD *ExpressionToConstraintRecord(void *,struct expr *); -#endif +#endif /* _H_cstrnutl */ diff --git a/src/default.c b/src/default.c index 6d74b93..2b78b16 100644 --- a/src/default.c +++ b/src/default.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFAULT ATTRIBUTE MODULE */ /*******************************************************/ @@ -15,12 +15,17 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Support for deftemplate-slot-default-value */ -/* function. */ +/* function. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ /* */ /*************************************************************/ @@ -82,7 +87,7 @@ globle void DeriveDefaultFromConstraints( SetpDOBegin(theDefault,1); SetpDOEnd(theDefault,0); if (garbageMultifield) SetpValue(theDefault,(void *) EnvCreateMultifield(theEnv,0L)); - else SetpValue(theDefault,(void *) CreateMultifield2(theEnv,0L)); + else SetpValue(theDefault,(void *) CreateMultifield2(theEnv,0L)); } else { @@ -112,7 +117,7 @@ globle void DeriveDefaultFromConstraints( else if (constraints->integersAllowed) { theType = INTEGER; - theValue = FindDefaultValue(theEnv,INTEGER,constraints,EnvAddLong(theEnv,0L)); + theValue = FindDefaultValue(theEnv,INTEGER,constraints,EnvAddLong(theEnv,0LL)); } else if (constraints->floatsAllowed) @@ -143,7 +148,7 @@ globle void DeriveDefaultFromConstraints( else if (constraints->externalAddressesAllowed) { theType = EXTERNAL_ADDRESS; - theValue = NULL; + theValue = EnvAddExternalAddress(theEnv,NULL,0); } else @@ -226,11 +231,11 @@ static void *FindDefaultValue( if (theConstraints->minValue->type == INTEGER) { return(theConstraints->minValue->value); } else if (theConstraints->minValue->type == FLOAT) - { return(EnvAddLong(theEnv,(long) ValueToDouble(theConstraints->minValue->value))); } + { return(EnvAddLong(theEnv,(long long) ValueToDouble(theConstraints->minValue->value))); } else if (theConstraints->maxValue->type == INTEGER) { return(theConstraints->maxValue->value); } else if (theConstraints->maxValue->type == FLOAT) - { return(EnvAddLong(theEnv,(long) ValueToDouble(theConstraints->maxValue->value))); } + { return(EnvAddLong(theEnv,(long long) ValueToDouble(theConstraints->maxValue->value))); } } else if (theType == FLOAT) { @@ -259,7 +264,7 @@ static void *FindDefaultValue( /**********************************************/ globle struct expr *ParseDefault( void *theEnv, - char *readSource, + const char *readSource, int multifield, int dynamic, int evalStatic, diff --git a/src/default.h b/src/default.h index 85d21d6..4eaf6d1 100644 --- a/src/default.h +++ b/src/default.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFAULT ATTRIBUTE HEADER FILE */ /*******************************************************/ @@ -19,7 +19,12 @@ /* Revision History: */ /* */ /* 6.24: Support for deftemplate-slot-default-value */ -/* function. */ +/* function. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ /* */ /*************************************************************/ @@ -44,9 +49,9 @@ #endif LOCALE void DeriveDefaultFromConstraints(void *,CONSTRAINT_RECORD *,DATA_OBJECT *,int,int); - LOCALE struct expr *ParseDefault(void *,char *,int,int,int,int *,int *,int *); + LOCALE struct expr *ParseDefault(void *,const char *,int,int,int,int *,int *,int *); -#endif +#endif /* _H_default */ diff --git a/src/defins.c b/src/defins.c index 0255aaa..a14c105 100644 --- a/src/defins.c +++ b/src/defins.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* DEFINSTANCES MODULE */ /*******************************************************/ @@ -11,12 +11,13 @@ /* and routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -31,6 +32,21 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ /* ========================================= @@ -87,12 +103,12 @@ ***************************************** */ #if (! BLOAD_ONLY) && (! RUN_TIME) -static int ParseDefinstances(void *,char *); -static SYMBOL_HN *ParseDefinstancesName(void *,char *,int *); +static int ParseDefinstances(void *,const char *); +static SYMBOL_HN *ParseDefinstancesName(void *,const char *,int *); static void RemoveDefinstances(void *,void *); -static void SaveDefinstances(void *,void *,char *); +static void SaveDefinstances(void *,void *,const char *); static intBool RemoveAllDefinstances(void *); -static void DefinstancesDeleteError(void *,char *); +static void DefinstancesDeleteError(void *,const char *); #if DEFRULE_CONSTRUCT static void CreateInitialDefinstances(void *); @@ -148,7 +164,7 @@ globle void SetupDefinstances( #else NULL, #endif - EnvFindDefinstances); + EnvFindDefinstancesInModule); DefinstancesData(theEnv)->DefinstancesConstruct = AddConstruct(theEnv,"definstances","definstances", @@ -202,7 +218,7 @@ globle void SetupDefinstances( SetupDefinstancesCompiler(theEnv); #endif } - + /*******************************************************/ /* DeallocateDefinstancesData: Deallocates environment */ /* data for the definstances construct. */ @@ -213,13 +229,13 @@ static void DeallocateDefinstancesData( #if ! RUN_TIME struct definstancesModule *theModuleItem; void *theModule; - + #if BLOAD || BLOAD_AND_BSAVE if (Bloaded(theEnv)) return; #endif - - DoForAllConstructs(theEnv,DestroyDefinstancesAction,DefinstancesData(theEnv)->DefinstancesModuleIndex,FALSE,NULL); - + + DoForAllConstructs(theEnv,DestroyDefinstancesAction,DefinstancesData(theEnv)->DefinstancesModuleIndex,FALSE,NULL); + for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; theModule = EnvGetNextDefmodule(theEnv,theModule)) @@ -230,40 +246,37 @@ static void DeallocateDefinstancesData( rtn_struct(theEnv,definstancesModule,theModuleItem); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } -#if ! RUN_TIME +#if ! RUN_TIME /*****************************************************/ /* DestroyDefinstancesAction: Action used to remove */ /* definstances as a result of DestroyEnvironment. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDefinstancesAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif #if (! BLOAD_ONLY) && (! RUN_TIME) struct definstances *theDefinstances = (struct definstances *) theConstruct; - + if (theDefinstances == NULL) return; - + ReturnPackedExpression(theEnv,theDefinstances->mkinstance); - + DestroyConstructHeader(theEnv,&theDefinstances->header); rtn_struct(theEnv,definstances,theDefinstances); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theConstruct,theEnv) #endif #endif @@ -300,9 +313,26 @@ globle void *EnvGetNextDefinstances( ***************************************************/ globle void *EnvFindDefinstances( void *theEnv, - char *name) + const char *name) + { + return(FindNamedConstructInModuleOrImports(theEnv,name,DefinstancesData(theEnv)->DefinstancesConstruct)); + } + +/*************************************************** + NAME : EnvFindDefinstancesInModule + DESCRIPTION : Looks up a definstance construct + by name-string + INPUTS : The symbolic name + RETURNS : The definstance address, or NULL + if not found + SIDE EFFECTS : None + NOTES : None + ***************************************************/ +globle void *EnvFindDefinstancesInModule( + void *theEnv, + const char *name) { - return(FindNamedConstruct(theEnv,name,DefinstancesData(theEnv)->DefinstancesConstruct)); + return(FindNamedConstructInModule(theEnv,name,DefinstancesData(theEnv)->DefinstancesConstruct)); } /*************************************************** @@ -366,7 +396,7 @@ globle intBool EnvUndefinstances( void *vptr) { #if RUN_TIME || BLOAD_ONLY -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,vptr) #endif return(FALSE); @@ -430,7 +460,7 @@ globle void ListDefinstancesCommand( ***************************************************/ globle void EnvListDefinstances( void *theEnv, - char *logicalName, + const char *logicalName, struct defmodule *theModule) { ListConstruct(theEnv,DefinstancesData(theEnv)->DefinstancesConstruct,logicalName,theModule); @@ -500,7 +530,7 @@ globle void EnvGetDefinstancesList( *********************************************************************/ static int ParseDefinstances( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *dname; void *mkinsfcall; @@ -529,7 +559,10 @@ static int ParseDefinstances( dobj->busy = 0; dobj->mkinstance = NULL; #if DEFRULE_CONSTRUCT - mkinsfcall = (void *) FindFunction(theEnv,(char *) (active ? "active-make-instance" : "make-instance")); + if (active) + mkinsfcall = (void *) FindFunction(theEnv,"active-make-instance"); + else + mkinsfcall = (void *) FindFunction(theEnv,"make-instance"); #else mkinsfcall = (void *) FindFunction(theEnv,"make-instance"); #endif @@ -584,13 +617,13 @@ static int ParseDefinstances( PPBackup(theEnv); PPBackup(theEnv); SavePPBuffer(theEnv,")\n"); - SetDefinstancesPPForm((void *) dobj,CopyPPBuffer(theEnv)); + EnvSetDefinstancesPPForm(theEnv,(void *) dobj,CopyPPBuffer(theEnv)); } #endif mkinstance = dobj->mkinstance; dobj->mkinstance = PackExpression(theEnv,mkinstance); ReturnExpression(theEnv,mkinstance); - IncrementSymbolCount(GetDefinstancesNamePointer((void *) dobj)); + IncrementSymbolCount(EnvGetDefinstancesNamePointer(theEnv,(void *) dobj)); ExpressionInstall(theEnv,dobj->mkinstance); } @@ -614,15 +647,15 @@ static int ParseDefinstances( *************************************************************/ static SYMBOL_HN *ParseDefinstancesName( void *theEnv, - char *readSource, + const char *readSource, int *active) { SYMBOL_HN *dname; *active = FALSE; dname = GetConstructNameAndComment(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken,"definstances", - EnvFindDefinstances,EnvUndefinstances,"@", - TRUE,FALSE,TRUE); + EnvFindDefinstancesInModule,EnvUndefinstances,"@", + TRUE,FALSE,TRUE,FALSE); if (dname == NULL) return(NULL); @@ -665,10 +698,10 @@ static void RemoveDefinstances( { DEFINSTANCES *dptr = (DEFINSTANCES *) vdptr; - DecrementSymbolCount(theEnv,GetDefinstancesNamePointer((void *) dptr)); + DecrementSymbolCount(theEnv,EnvGetDefinstancesNamePointer(theEnv,(void *) dptr)); ExpressionDeinstall(theEnv,dptr->mkinstance); ReturnPackedExpression(theEnv,dptr->mkinstance); - SetDefinstancesPPForm((void *) dptr,NULL); + EnvSetDefinstancesPPForm(theEnv,(void *) dptr,NULL); ClearUserDataList(theEnv,dptr->header.usrData); rtn_struct(theEnv,definstances,dptr); } @@ -685,7 +718,7 @@ static void RemoveDefinstances( static void SaveDefinstances( void *theEnv, void *theModule, - char *logName) + const char *logName) { SaveConstruct(theEnv,theModule,logName,DefinstancesData(theEnv)->DefinstancesConstruct); } @@ -741,7 +774,7 @@ static intBool RemoveAllDefinstances( ***************************************************/ static void DefinstancesDeleteError( void *theEnv, - char *dname) + const char *dname) { CantDeleteItemErrorMessage(theEnv,"definstances",dname); } @@ -775,7 +808,7 @@ static void CreateInitialDefinstances( GenConstant(theEnv,DEFCLASS_PTR,(void *) LookupDefclassInScope(theEnv,INITIAL_OBJECT_CLASS_NAME)); theDefinstances->mkinstance = PackExpression(theEnv,tmp); ReturnExpression(theEnv,tmp); - IncrementSymbolCount(GetDefinstancesNamePointer((void *) theDefinstances)); + IncrementSymbolCount(EnvGetDefinstancesNamePointer(theEnv,(void *) theDefinstances)); ExpressionInstall(theEnv,theDefinstances->mkinstance); AddConstructToModule((struct constructHeader *) theDefinstances); } @@ -856,15 +889,12 @@ static intBool ClearDefinstancesReady( if definstances is not busy (assumed to be initialized to 1) ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void CheckDefinstancesBusy( void *theEnv, struct constructHeader *theDefinstances, void *userBuffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -904,15 +934,12 @@ static void ResetDefinstances( SIDE EFFECTS : Instances created NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void ResetDefinstancesAction( void *theEnv, struct constructHeader *vDefinstances, void *userBuffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(userBuffer) #endif DEFINSTANCES *theDefinstances = (DEFINSTANCES *) vDefinstances; @@ -940,6 +967,120 @@ static void ResetDefinstancesAction( RestoreCurrentModule(theEnv); } +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvGetDefinstancesName( + void *theEnv, + void *theDefinstances) + { + return GetConstructNameString((struct constructHeader *) theDefinstances); + } + +globle const char *EnvGetDefinstancesPPForm( + void *theEnv, + void *theDefinstances) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDefinstances); + } + +globle void EnvSetDefinstancesPPForm( + void *theEnv, + void *theDefinstances, + const char *thePPForm) + { + SetConstructPPForm(theEnv,(struct constructHeader *) theDefinstances,thePPForm); + } + +globle const char *EnvDefinstancesModule( + void *theEnv, + void *theDefinstances) + { + return GetConstructModuleName((struct constructHeader *) theDefinstances); + } + +globle SYMBOL_HN *EnvGetDefinstancesNamePointer( + void *theEnv, + void *theDefinstances) + { + return GetConstructNamePointer((struct constructHeader *) theDefinstances); + } + +globle const char *EnvDefinstancesModuleName( + void *theEnv, + void *theDefinstances) + { + return GetConstructModuleName((struct constructHeader *) theDefinstances); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *DefinstancesModule( + void *theDefinstances) + { + return EnvDefinstancesModule(GetCurrentEnvironment(),theDefinstances); + } + +globle void *FindDefinstances( + const char *name) + { + return EnvFindDefinstances(GetCurrentEnvironment(),name); + } + +globle void GetDefinstancesList( + DATA_OBJECT *returnValue, + struct defmodule *theModule) + { + EnvGetDefinstancesList(GetCurrentEnvironment(),returnValue,theModule); + } + +globle const char *GetDefinstancesName( + void *theDefinstances) + { + return EnvGetDefinstancesName(GetCurrentEnvironment(),theDefinstances); + } + +globle const char *GetDefinstancesPPForm( + void *theDefinstances) + { + return EnvGetDefinstancesPPForm(GetCurrentEnvironment(),theDefinstances); + } + +globle void *GetNextDefinstances( + void *ptr) + { + return EnvGetNextDefinstances(GetCurrentEnvironment(),ptr); + } + +globle int IsDefinstancesDeletable( + void *ptr) + { + return EnvIsDefinstancesDeletable(GetCurrentEnvironment(),ptr); + } + +globle intBool Undefinstances( + void *vptr) + { + return EnvUndefinstances(GetCurrentEnvironment(),vptr); + } + +#if DEBUGGING_FUNCTIONS + +globle void ListDefinstances( + const char *logicalName, + struct defmodule *theModule) + { + EnvListDefinstances(GetCurrentEnvironment(),logicalName,theModule); + } +#endif + +#endif + #endif diff --git a/src/defins.h b/src/defins.h index c35f456..435ce65 100644 --- a/src/defins.h +++ b/src/defins.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* */ /*******************************************************/ @@ -10,16 +10,32 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_defins @@ -27,15 +43,6 @@ #if DEFINSTANCES_CONSTRUCT -#define EnvGetDefinstancesName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDefinstancesPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) - -#define GetDefinstancesNamePointer(x) GetConstructNamePointer((struct constructHeader *) x) -#define SetDefinstancesPPForm(d,ppf) SetConstructPPForm(theEnv,(struct constructHeader *) d,ppf) - -#define GetDefinstancesModuleName(x) GetConstructModuleName((struct constructHeader *) x) -#define EnvDefinstancesModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - struct definstances; #ifndef _H_conscomp @@ -69,7 +76,7 @@ typedef struct definstances #define DEFINSTANCES_DATA 22 struct definstancesData - { + { struct construct *DefinstancesConstruct; int DefinstancesModuleIndex; #if CONSTRUCT_COMPILER && (! RUN_TIME) @@ -79,7 +86,6 @@ struct definstancesData #define DefinstancesData(theEnv) ((struct definstancesData *) GetEnvironmentData(theEnv,DEFINSTANCES_DATA)) - #ifdef LOCALE #undef LOCALE #endif @@ -90,49 +96,47 @@ struct definstancesData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DefinstancesModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefinstances(theEnv,a) EnvFindDefinstances(theEnv,a) -#define GetDefinstancesList(theEnv,a,b) EnvGetDefinstancesList(theEnv,a,b) -#define GetDefinstancesName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDefinstancesPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetNextDefinstances(theEnv,a) EnvGetNextDefinstances(theEnv,a) -#define IsDefinstancesDeletable(theEnv,a) EnvIsDefinstancesDeletable(theEnv,a) -#define ListDefinstances(theEnv,a,b) EnvListDefinstances(theEnv,a,b) -#define Undefinstances(theEnv,a) EnvUndefinstances(theEnv,a) -#else -#define DefinstancesModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefinstances(a) EnvFindDefinstances(GetCurrentEnvironment(),a) -#define GetDefinstancesList(a,b) EnvGetDefinstancesList(GetCurrentEnvironment(),a,b) -#define GetDefinstancesName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDefinstancesPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetNextDefinstances(a) EnvGetNextDefinstances(GetCurrentEnvironment(),a) -#define IsDefinstancesDeletable(a) EnvIsDefinstancesDeletable(GetCurrentEnvironment(),a) -#define ListDefinstances(a,b) EnvListDefinstances(GetCurrentEnvironment(),a,b) -#define Undefinstances(a) EnvUndefinstances(GetCurrentEnvironment(),a) + LOCALE const char *EnvDefinstancesModule(void *,void *); + LOCALE const char *EnvDefinstancesModuleName(void *,void *); + LOCALE void *EnvFindDefinstances(void *,const char *); + LOCALE void *EnvFindDefinstancesInModule(void *,const char *); + LOCALE void EnvGetDefinstancesList(void *,DATA_OBJECT *,struct defmodule *); + LOCALE const char *EnvGetDefinstancesName(void *,void *); + LOCALE SYMBOL_HN *EnvGetDefinstancesNamePointer(void *,void *); + LOCALE const char *EnvGetDefinstancesPPForm(void *,void *); + LOCALE void *EnvGetNextDefinstances(void *,void *); + LOCALE int EnvIsDefinstancesDeletable(void *,void *); + LOCALE void EnvSetDefinstancesPPForm(void *,void *,const char *); + LOCALE intBool EnvUndefinstances(void *,void *); + LOCALE void GetDefinstancesListFunction(void *,DATA_OBJECT *); + LOCALE void *GetDefinstancesModuleCommand(void *); + LOCALE void SetupDefinstances(void *); + LOCALE void UndefinstancesCommand(void *); +#if DEBUGGING_FUNCTIONS + LOCALE void PPDefinstancesCommand(void *); + LOCALE void ListDefinstancesCommand(void *); + LOCALE void EnvListDefinstances(void *,const char *,struct defmodule *); #endif -LOCALE void SetupDefinstances(void *); -LOCALE void *EnvGetNextDefinstances(void *,void *); -LOCALE void *EnvFindDefinstances(void *,char *); -LOCALE int EnvIsDefinstancesDeletable(void *,void *); -LOCALE void UndefinstancesCommand(void *); -LOCALE void *GetDefinstancesModuleCommand(void *); -LOCALE intBool EnvUndefinstances(void *,void *); +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE const char *DefinstancesModule(void *); + LOCALE void *FindDefinstances(const char *); + LOCALE void GetDefinstancesList(DATA_OBJECT *,struct defmodule *); + LOCALE const char *GetDefinstancesName(void *); + LOCALE const char *GetDefinstancesPPForm(void *); + LOCALE void *GetNextDefinstances(void *); + LOCALE int IsDefinstancesDeletable(void *); #if DEBUGGING_FUNCTIONS -LOCALE void PPDefinstancesCommand(void *); -LOCALE void ListDefinstancesCommand(void *); -LOCALE void EnvListDefinstances(void *,char *,struct defmodule *); + LOCALE void ListDefinstances(const char *,struct defmodule *); #endif + LOCALE intBool Undefinstances(void *); -LOCALE void GetDefinstancesListFunction(void *,DATA_OBJECT *); -LOCALE void EnvGetDefinstancesList(void *,DATA_OBJECT *,struct defmodule *); - -#endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ -#endif +#endif /* DEFINSTANCES_CONSTRUCT */ +#endif /* _H_defins */ diff --git a/src/developr.c b/src/developr.c index b104cde..9b07582 100644 --- a/src/developr.c +++ b/src/developr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEVELOPER MODULE */ /*******************************************************/ @@ -18,9 +18,23 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Changed garbage collection algorithm. */ +/* Functions enable-gc-heuristics and */ +/* disable-gc-heuristics are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers and type casts to */ +/* remove C++ warnings. */ +/* */ +/* Replaced deprecated WCLIPS logical name with */ +/* WPROMPT. */ +/* */ /*************************************************************/ #define _DEVELOPR_SOURCE_ @@ -70,13 +84,14 @@ globle void DeveloperCommands( #if ! RUN_TIME EnvDefineFunction2(theEnv,"primitives-info",'v', PTIEF PrimitiveTablesInfo,"PrimitiveTablesInfo","00"); EnvDefineFunction2(theEnv,"primitives-usage",'v', PTIEF PrimitiveTablesUsage,"PrimitiveTablesUsage","00"); - EnvDefineFunction2(theEnv,"enable-gc-heuristics",'v', PTIEF EnableGCHeuristics,"EnableGCHeuristics","00"); - EnvDefineFunction2(theEnv,"disable-gc-heuristics",'v', PTIEF DisableGCHeuristics,"DisableGCHeuristics","00"); #if DEFRULE_CONSTRUCT && DEFTEMPLATE_CONSTRUCT + EnvDefineFunction2(theEnv,"validate-fact-integrity", 'b', ValidateFactIntegrity, "ValidateFactIntegrity", "00"); + EnvDefineFunction2(theEnv,"show-fpn",'v', PTIEF ShowFactPatternNetwork,"ShowFactPatternNetwork","11w"); EnvDefineFunction2(theEnv,"show-fht",'v', PTIEF ShowFactHashTable,"ShowFactHashTable","00"); #endif + #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM EnvDefineFunction2(theEnv,"show-opn",'v',PTIEF PrintObjectPatternNetwork, "PrintObjectPatternNetwork","00"); @@ -90,26 +105,6 @@ globle void DeveloperCommands( } /******************************************************/ -/* EnableGCHeuristics: */ -/******************************************************/ -globle void EnableGCHeuristics( - void *theEnv) - { - EnvArgCountCheck(theEnv,"enable-gc-heuristics",EXACTLY,0); - SetGarbageCollectionHeuristics(theEnv,TRUE); - } - -/******************************************************/ -/* DisableGCHeuristics: */ -/******************************************************/ -globle void DisableGCHeuristics( - void *theEnv) - { - EnvArgCountCheck(theEnv,"disable-gc-heuristics",EXACTLY,0); - SetGarbageCollectionHeuristics(theEnv,FALSE); - } - -/******************************************************/ /* PrimitiveTablesInfo: Prints information about the */ /* symbol, float, integer, and bitmap tables. */ /******************************************************/ @@ -175,22 +170,24 @@ globle void PrimitiveTablesInfo( /*========================*/ EnvPrintRouter(theEnv,WDISPLAY,"Symbols: "); - PrintLongInteger(theEnv,WDISPLAY,(long) symbolCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) symbolCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); EnvPrintRouter(theEnv,WDISPLAY,"Integers: "); - PrintLongInteger(theEnv,WDISPLAY,(long) integerCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) integerCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); EnvPrintRouter(theEnv,WDISPLAY,"Floats: "); - PrintLongInteger(theEnv,WDISPLAY,(long) floatCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) floatCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); EnvPrintRouter(theEnv,WDISPLAY,"BitMaps: "); - PrintLongInteger(theEnv,WDISPLAY,(long) bitMapCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) bitMapCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); - //EnvPrintRouter(theEnv,WDISPLAY,"Ephemerals: "); - //PrintLongInteger(theEnv,WDISPLAY,(long) EphemeralSymbolCount()); - //EnvPrintRouter(theEnv,WDISPLAY,"\n"); + /* + EnvPrintRouter(theEnv,WDISPLAY,"Ephemerals: "); + PrintLongInteger(theEnv,WDISPLAY,(long long) EphemeralSymbolCount()); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + */ } - + #define COUNT_SIZE 21 /******************************************************/ @@ -212,9 +209,9 @@ globle void PrimitiveTablesUsage( for (i = 0; i < 21; i++) { symbolCounts[i] = 0; - floatCounts[i] = 0; + floatCounts[i] = 0; } - + /*====================================*/ /* Count entries in the symbol table. */ /*====================================*/ @@ -224,11 +221,11 @@ globle void PrimitiveTablesUsage( { symbolCount = 0; for (symbolPtr = symbolArray[i]; symbolPtr != NULL; symbolPtr = symbolPtr->next) - { + { symbolCount++; totalSymbolCount++; } - + if (symbolCount < (COUNT_SIZE - 1)) { symbolCounts[symbolCount]++; } else @@ -238,17 +235,17 @@ globle void PrimitiveTablesUsage( /*===================================*/ /* Count entries in the float table. */ /*===================================*/ - + floatArray = GetFloatTable(theEnv); for (i = 0; i < FLOAT_HASH_SIZE; i++) { floatCount = 0; for (floatPtr = floatArray[i]; floatPtr != NULL; floatPtr = floatPtr->next) - { + { floatCount++; totalFloatCount++; } - + if (floatCount < (COUNT_SIZE - 1)) { floatCounts[floatCount]++; } else @@ -261,24 +258,24 @@ globle void PrimitiveTablesUsage( /*========================*/ EnvPrintRouter(theEnv,WDISPLAY,"Total Symbols: "); - PrintLongInteger(theEnv,WDISPLAY,(long) totalSymbolCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) totalSymbolCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); for (i = 0; i < COUNT_SIZE; i++) { - PrintLongInteger(theEnv,WDISPLAY,(long) i); + PrintLongInteger(theEnv,WDISPLAY,(long long) i); EnvPrintRouter(theEnv,WDISPLAY," "); - PrintLongInteger(theEnv,WDISPLAY,(long) symbolCounts[i]); + PrintLongInteger(theEnv,WDISPLAY,(long long) symbolCounts[i]); EnvPrintRouter(theEnv,WDISPLAY,"\n"); } EnvPrintRouter(theEnv,WDISPLAY,"\nTotal Floats: "); - PrintLongInteger(theEnv,WDISPLAY,(long) totalFloatCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) totalFloatCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); for (i = 0; i < COUNT_SIZE; i++) { - PrintLongInteger(theEnv,WDISPLAY,(long) i); + PrintLongInteger(theEnv,WDISPLAY,(long long) i); EnvPrintRouter(theEnv,WDISPLAY," "); - PrintLongInteger(theEnv,WDISPLAY,(long) floatCounts[i]); + PrintLongInteger(theEnv,WDISPLAY,(long long) floatCounts[i]); EnvPrintRouter(theEnv,WDISPLAY,"\n"); } @@ -286,6 +283,62 @@ globle void PrimitiveTablesUsage( #if DEFRULE_CONSTRUCT && DEFTEMPLATE_CONSTRUCT +/***********************************************/ +/* ValidateFactIntegrity: Command for checking */ +/* the facts for atom value integrity. */ +/***********************************************/ +globle intBool ValidateFactIntegrity( + void *theEnv) + { + struct fact *theFact; + struct multifield *theSegment; + int i; + SYMBOL_HN *theSymbol; + FLOAT_HN *theFloat; + INTEGER_HN *theInteger; + + if (((struct environmentData *) theEnv)->initialized == FALSE) + { return TRUE; } + + for (theFact = (struct fact *) EnvGetNextFact(theEnv,NULL); + theFact != NULL; + theFact = (struct fact *) EnvGetNextFact(theEnv,theFact)) + { + if (theFact->factHeader.busyCount <= 0) + { return FALSE; } + + theSegment = &theFact->theProposition; + + for (i = 0 ; i < (int) theSegment->multifieldLength ; i++) + { + if ((theSegment->theFields[i].type == SYMBOL) || + (theSegment->theFields[i].type == STRING) || + (theSegment->theFields[i].type == INSTANCE_NAME)) + { + theSymbol = (SYMBOL_HN *) theSegment->theFields[i].value; + if (theSymbol->count <= 0) + { return FALSE; } + } + + if (theSegment->theFields[i].type == INTEGER) + { + theInteger = (INTEGER_HN *) theSegment->theFields[i].value; + if (theInteger->count <= 0) + { return FALSE; } + } + + if (theSegment->theFields[i].type == FLOAT) + { + theFloat = (FLOAT_HN *) theSegment->theFields[i].value; + if (theFloat->count <= 0) + { return FALSE; } + } + } + } + + return TRUE; + } + /*******************************************************/ /* ShowFactPatternNetwork: Command for displaying the */ /* fact pattern network for a specified deftemplate. */ @@ -295,7 +348,7 @@ globle void ShowFactPatternNetwork( { struct factPatternNode *patternPtr; struct deftemplate *theDeftemplate; - char *theName; + const char *theName; int depth = 0, i; theName = GetConstructName(theEnv,"show-fpn","template name"); @@ -314,18 +367,21 @@ globle void ShowFactPatternNetwork( EnvPrintRouter(theEnv,WDISPLAY,"MF"); if (patternPtr->header.endSlot) EnvPrintRouter(theEnv,WDISPLAY,")"); else EnvPrintRouter(theEnv,WDISPLAY,"*"); - PrintLongInteger(theEnv,WDISPLAY,(long) patternPtr->leaveFields); + PrintLongInteger(theEnv,WDISPLAY,(long long) patternPtr->leaveFields); EnvPrintRouter(theEnv,WDISPLAY," "); } EnvPrintRouter(theEnv,WDISPLAY,"Slot: "); - PrintLongInteger(theEnv,WDISPLAY,(long) patternPtr->whichSlot); + PrintLongInteger(theEnv,WDISPLAY,(long long) patternPtr->whichSlot); EnvPrintRouter(theEnv,WDISPLAY," Field: "); - PrintLongInteger(theEnv,WDISPLAY,(long) patternPtr->whichField); + PrintLongInteger(theEnv,WDISPLAY,(long long) patternPtr->whichField); EnvPrintRouter(theEnv,WDISPLAY," Expression: "); if (patternPtr->networkTest == NULL) EnvPrintRouter(theEnv,WDISPLAY,"None"); else PrintExpression(theEnv,WDISPLAY,patternPtr->networkTest); + EnvPrintRouter(theEnv,WDISPLAY," RightHash: "); + if (patternPtr->header.rightHash == NULL) EnvPrintRouter(theEnv,WDISPLAY,"None"); + else PrintExpression(theEnv,WDISPLAY,patternPtr->header.rightHash); EnvPrintRouter(theEnv,WDISPLAY,"\n"); if (patternPtr->nextLevel == NULL) @@ -398,10 +454,10 @@ static void PrintOPNLevel( EnvPrintRouter(theEnv,WDISPLAY,"+"); EnvPrintRouter(theEnv,WDISPLAY,ValueToString(FindIDSlotName(theEnv,pptr->slotNameID))); EnvPrintRouter(theEnv,WDISPLAY," ("); - PrintLongInteger(theEnv,WDISPLAY,(long) pptr->slotNameID); + PrintLongInteger(theEnv,WDISPLAY,(long long) pptr->slotNameID); EnvPrintRouter(theEnv,WDISPLAY,") "); EnvPrintRouter(theEnv,WDISPLAY,pptr->endSlot ? "EPF#" : "PF#"); - PrintLongInteger(theEnv,WDISPLAY,(long) pptr->whichField); + PrintLongInteger(theEnv,WDISPLAY,(long long) pptr->whichField); EnvPrintRouter(theEnv,WDISPLAY," "); EnvPrintRouter(theEnv,WDISPLAY,pptr->multifieldNode ? "$? " : "? "); if (pptr->networkTest != NULL) @@ -436,6 +492,12 @@ static void PrintOPNLevel( } } } + if (alphaPtr->header.rightHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," RH: "); + PrintExpression(theEnv,WDISPLAY,alphaPtr->header.rightHash); + } + EnvPrintRouter(theEnv,WDISPLAY,"\n"); alphaPtr = alphaPtr->nxtInGroup; } @@ -470,7 +532,7 @@ globle void InstanceTableUsage( for (i = 0; i < COUNT_SIZE; i++) { instanceCounts[i] = 0; } - + /*======================================*/ /* Count entries in the instance table. */ /*======================================*/ @@ -479,11 +541,11 @@ globle void InstanceTableUsage( { instanceCount = 0; for (ins = InstanceData(theEnv)->InstanceTable[i]; ins != NULL; ins = ins->nxtHash) - { + { instanceCount++; totalInstanceCount++; } - + if (instanceCount < (COUNT_SIZE - 1)) { instanceCounts[instanceCount]++; } else @@ -495,17 +557,93 @@ globle void InstanceTableUsage( /*========================*/ EnvPrintRouter(theEnv,WDISPLAY,"Total Instances: "); - PrintLongInteger(theEnv,WDISPLAY,(long) totalInstanceCount); + PrintLongInteger(theEnv,WDISPLAY,(long long) totalInstanceCount); EnvPrintRouter(theEnv,WDISPLAY,"\n"); for (i = 0; i < COUNT_SIZE; i++) { - PrintLongInteger(theEnv,WDISPLAY,(long) i); + PrintLongInteger(theEnv,WDISPLAY,(long long) i); EnvPrintRouter(theEnv,WDISPLAY," "); - PrintLongInteger(theEnv,WDISPLAY,(long) instanceCounts[i]); + PrintLongInteger(theEnv,WDISPLAY,(long long) instanceCounts[i]); EnvPrintRouter(theEnv,WDISPLAY,"\n"); } } - + +#endif + +#if DEFRULE_CONSTRUCT + +/******************/ +/* ExamineMemory: */ +/******************/ +static void ExamineMemory( + void *theEnv, + struct joinNode *theJoin, + struct betaMemory *theMemory) + { +#if MAC_XCD +#pragma unused(theJoin) +#endif + if (theMemory->size > 10000) + { + /* Set a break point here */ + } + } + +/*************************/ +/* TraverseBetaMemories: */ +/*************************/ +static void TraverseBetaMemories( + void *theEnv, + struct joinNode *theJoin) + { + if (theJoin == NULL) + { return; } + + if (theJoin->lastLevel != NULL) + { TraverseBetaMemories(theEnv,theJoin->lastLevel); } + + if (theJoin->depth > 2) + { ExamineMemory(theEnv,theJoin,theJoin->leftMemory); } + + if (theJoin->joinFromTheRight) + { TraverseBetaMemories(theEnv,(struct joinNode *) theJoin->rightSideEntryStructure); } + + if ((theJoin->joinFromTheRight) && + (((struct joinNode *) (theJoin->rightSideEntryStructure))->depth > 1)) + { ExamineMemory(theEnv,theJoin,theJoin->rightMemory); } + } + +/***********************************/ +/* ValidateRuleBetaMemoriesAction: */ +/***********************************/ +static void ValidateRuleBetaMemoriesAction( + void *theEnv, + struct constructHeader *theConstruct, + void *buffer) + { +#if MAC_XCD +#pragma unused(buffer) +#endif + struct defrule *rulePtr, *tmpPtr; + + for (rulePtr = (struct defrule *) theConstruct, tmpPtr = rulePtr; + rulePtr != NULL; + rulePtr = rulePtr->disjunct) + { + TraverseBetaMemories(theEnv,rulePtr->lastJoin); + } + } + +/************************/ +/* ValidateBetaMemories */ +/************************/ +globle void ValidateBetaMemories( + void *theEnv) + { + EnvPrintRouter(theEnv,WPROMPT,"ValidateBetaMemories"); + DoForAllConstructs(theEnv,ValidateRuleBetaMemoriesAction,DefruleData(theEnv)->DefruleModuleIndex,FALSE,NULL); + } + #endif #endif diff --git a/src/developr.h b/src/developr.h index d8fc6c7..69b56c0 100644 --- a/src/developr.h +++ b/src/developr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEVELOPER HEADER FILE */ /*******************************************************/ @@ -16,9 +16,17 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Changed garbage collection algorithm. */ +/* Functions enable-gc-heuristics and */ +/* disable-gc-heuristics are no longer supported. */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_developr @@ -37,11 +45,10 @@ LOCALE void DeveloperCommands(void *); LOCALE void PrimitiveTablesInfo(void *); LOCALE void PrimitiveTablesUsage(void *); - LOCALE void EnableGCHeuristics(void *); - LOCALE void DisableGCHeuristics(void *); #if DEFRULE_CONSTRUCT && DEFTEMPLATE_CONSTRUCT LOCALE void ShowFactPatternNetwork(void *); + LOCALE intBool ValidateFactIntegrity(void *); #endif #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM LOCALE void PrintObjectPatternNetwork(void *); @@ -49,7 +56,10 @@ #if OBJECT_SYSTEM LOCALE void InstanceTableUsage(void *); #endif - +#if DEFRULE_CONSTRUCT + LOCALE void ValidateBetaMemories(void *); #endif +#endif /* _H_developr */ + diff --git a/src/dffctbin.c b/src/dffctbin.c index dde2463..87645e9 100644 --- a/src/dffctbin.c +++ b/src/dffctbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -14,10 +14,12 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #define _DFFCTBIN_SOURCE_ @@ -76,7 +78,7 @@ globle void DeffactsBinarySetup( ClearBload); #endif } - + /********************************************************/ /* DeallocateDeffactsBloadData: Deallocates environment */ /* data for the deffacts bsave functionality. */ @@ -84,13 +86,13 @@ globle void DeffactsBinarySetup( static void DeallocateDeffactsBloadData( void *theEnv) { - unsigned long space; + size_t space; space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts); - if (space != 0) genlongfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space); - + if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space); + space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule); - if (space != 0) genlongfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space); } #if BLOAD_AND_BSAVE @@ -211,7 +213,7 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; /*=================================================================*/ /* Only two data structures are saved as part of a deffacts binary */ @@ -221,9 +223,9 @@ static void BsaveStorage( /*=================================================================*/ space = sizeof(long) * 2; - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); - GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffacts,(unsigned long) sizeof(long int),fp); - GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,(unsigned long) sizeof(long int),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffacts,sizeof(long int),fp); + GenWrite(&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,sizeof(long int),fp); } /********************************************/ @@ -234,7 +236,7 @@ static void BsaveBinaryItem( void *theEnv, FILE *fp) { - unsigned long int space; + size_t space; struct deffacts *theDeffacts; struct bsaveDeffacts newDeffacts; struct defmodule *theModule; @@ -248,7 +250,7 @@ static void BsaveBinaryItem( space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct bsaveDeffacts) + (DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct bsaveDeffactsModule)); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*================================================*/ /* Write out each deffacts module data structure. */ @@ -313,16 +315,16 @@ static void BsaveBinaryItem( static void BloadStorage( void *theEnv) { - unsigned long int space; + size_t space; /*=====================================================*/ /* Determine the number of deffacts and deffactsModule */ /* data structures to be read. */ /*=====================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffacts,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffacts,sizeof(long int)); + GenReadBinary(theEnv,&DeffactsBinaryData(theEnv)->NumberOfDeffactsModules,sizeof(long int)); /*===================================*/ /* Allocate the space needed for the */ @@ -337,7 +339,7 @@ static void BloadStorage( } space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule); - DeffactsBinaryData(theEnv)->ModuleArray = (struct deffactsModule *) genlongalloc(theEnv,space); + DeffactsBinaryData(theEnv)->ModuleArray = (struct deffactsModule *) genalloc(theEnv,space); /*===================================*/ /* Allocate the space needed for the */ @@ -350,8 +352,8 @@ static void BloadStorage( return; } - space = (unsigned long) (DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts)); - DeffactsBinaryData(theEnv)->DeffactsArray = (struct deffacts *) genlongalloc(theEnv,space); + space = (DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts)); + DeffactsBinaryData(theEnv)->DeffactsArray = (struct deffacts *) genalloc(theEnv,space); } /*****************************************************/ @@ -361,7 +363,7 @@ static void BloadStorage( static void BloadBinaryItem( void *theEnv) { - unsigned long int space; + size_t space; /*======================================================*/ /* Read in the amount of space used by the binary image */ @@ -369,7 +371,7 @@ static void BloadBinaryItem( /* is not available in the version being run). */ /*======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); /*============================================*/ /* Read in the deffactsModule data structures */ @@ -377,8 +379,7 @@ static void BloadBinaryItem( /*============================================*/ BloadandRefresh(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffactsModules, - (unsigned) sizeof(struct bsaveDeffactsModule), - UpdateDeffactsModule); + sizeof(struct bsaveDeffactsModule),UpdateDeffactsModule); /*======================================*/ /* Read in the deffacts data structures */ @@ -386,8 +387,7 @@ static void BloadBinaryItem( /*======================================*/ BloadandRefresh(theEnv,DeffactsBinaryData(theEnv)->NumberOfDeffacts, - (unsigned) sizeof(struct bsaveDeffacts), - UpdateDeffacts); + sizeof(struct bsaveDeffacts),UpdateDeffacts); } /***************************************************/ @@ -432,7 +432,7 @@ static void ClearBload( void *theEnv) { long i; - unsigned long space; + size_t space; /*=============================================*/ /* Decrement in use counters for atomic values */ @@ -447,15 +447,15 @@ static void ClearBload( /*=============================================================*/ space = DeffactsBinaryData(theEnv)->NumberOfDeffacts * sizeof(struct deffacts); - if (space != 0) genlongfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space); + if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->DeffactsArray,space); DeffactsBinaryData(theEnv)->NumberOfDeffacts = 0; - + /*====================================================================*/ /* Deallocate the space used for the deffacts module data structures. */ /*====================================================================*/ space = DeffactsBinaryData(theEnv)->NumberOfDeffactsModules * sizeof(struct deffactsModule); - if (space != 0) genlongfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DeffactsBinaryData(theEnv)->ModuleArray,space); DeffactsBinaryData(theEnv)->NumberOfDeffactsModules = 0; } diff --git a/src/dffctbin.h b/src/dffctbin.h index 601daba..d7d7464 100644 --- a/src/dffctbin.h +++ b/src/dffctbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS BSAVE/BLOAD HEADER FILE */ /*******************************************************/ @@ -13,13 +13,16 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #if (! RUN_TIME) + #ifndef _H_dffctbin #define _H_dffctbin @@ -40,17 +43,17 @@ struct bsaveDeffactsModule { struct bsaveDefmoduleItemHeader header; }; - + #define DFFCTBIN_DATA 26 struct deffactsBinaryData - { + { struct deffacts *DeffactsArray; long NumberOfDeffacts; struct deffactsModule *ModuleArray; long NumberOfDeffactsModules; }; - + #define DeffactsBinaryData(theEnv) ((struct deffactsBinaryData *) GetEnvironmentData(theEnv,DFFCTBIN_DATA)) #ifdef LOCALE @@ -66,8 +69,9 @@ struct deffactsBinaryData LOCALE void DeffactsBinarySetup(void *); LOCALE void *BloadDeffactsModuleReference(void *,int); -#endif -#endif +#endif /* _H_dffctbin */ + +#endif /* (! RUN_TIME) */ diff --git a/src/dffctbsc.c b/src/dffctbsc.c index e276108..77b6687 100644 --- a/src/dffctbsc.c +++ b/src/dffctbsc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFFACTS BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -15,14 +15,28 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _DFFCTBSC_SOURCE_ @@ -63,7 +77,7 @@ static void ResetDeffacts(void *); static void ClearDeffacts(void *); - static void SaveDeffacts(void *,void *,char *); + static void SaveDeffacts(void *,void *,const char *); static void ResetDeffactsAction(void *,struct constructHeader *,void *); /***************************************************************/ @@ -71,7 +85,7 @@ /***************************************************************/ globle void DeffactsBasicCommands( void *theEnv) - { + { EnvAddResetFunction(theEnv,"deffacts",ResetDeffacts,0); EnvAddClearFunction(theEnv,"deffacts",ClearDeffacts,0); AddSaveFunction(theEnv,"deffacts",SaveDeffacts,10); @@ -104,23 +118,20 @@ globle void DeffactsBasicCommands( /**********************************************************/ static void ResetDeffacts( void *theEnv) - { - DoForAllConstructs(theEnv,ResetDeffactsAction,DeffactsData(theEnv)->DeffactsModuleIndex,TRUE,NULL); + { + DoForAllConstructs(theEnv,ResetDeffactsAction,DeffactsData(theEnv)->DeffactsModuleIndex,TRUE,NULL); } /*****************************************************/ /* ResetDeffactsAction: Action to be applied to each */ /* deffacts construct during a reset command. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void ResetDeffactsAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif DATA_OBJECT result; @@ -150,7 +161,7 @@ static void ClearDeffacts( /*=====================================*/ stub = GenConstant(theEnv,FCALL,FindFunction(theEnv,"assert")); - stub->argList = GenConstant(theEnv,DEFTEMPLATE_PTR,EnvFindDeftemplate(theEnv,"initial-fact")); + stub->argList = GenConstant(theEnv,DEFTEMPLATE_PTR,EnvFindDeftemplateInModule(theEnv,"initial-fact")); ExpressionInstall(theEnv,stub); /*=============================================*/ @@ -175,7 +186,7 @@ static void ClearDeffacts( AddConstructToModule(&newDeffacts->header); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -188,9 +199,9 @@ static void ClearDeffacts( static void SaveDeffacts( void *theEnv, void *theModule, - char *logicalName) - { - SaveConstruct(theEnv,theModule,logicalName,DeffactsData(theEnv)->DeffactsConstruct); + const char *logicalName) + { + SaveConstruct(theEnv,theModule,logicalName,DeffactsData(theEnv)->DeffactsConstruct); } /*******************************************/ @@ -199,8 +210,8 @@ static void SaveDeffacts( /*******************************************/ globle void UndeffactsCommand( void *theEnv) - { - UndefconstructCommand(theEnv,"undeffacts",DeffactsData(theEnv)->DeffactsConstruct); + { + UndefconstructCommand(theEnv,"undeffacts",DeffactsData(theEnv)->DeffactsConstruct); } /***********************************/ @@ -210,8 +221,8 @@ globle void UndeffactsCommand( globle intBool EnvUndeffacts( void *theEnv, void *theDeffacts) - { - return(Undefconstruct(theEnv,theDeffacts,DeffactsData(theEnv)->DeffactsConstruct)); + { + return(Undefconstruct(theEnv,theDeffacts,DeffactsData(theEnv)->DeffactsConstruct)); } /*************************************************/ @@ -221,8 +232,8 @@ globle intBool EnvUndeffacts( globle void GetDeffactsListFunction( void *theEnv, DATA_OBJECT_PTR returnValue) - { - GetConstructListFunction(theEnv,"get-deffacts-list",returnValue,DeffactsData(theEnv)->DeffactsConstruct); + { + GetConstructListFunction(theEnv,"get-deffacts-list",returnValue,DeffactsData(theEnv)->DeffactsConstruct); } /*****************************************/ @@ -233,8 +244,8 @@ globle void EnvGetDeffactsList( void *theEnv, DATA_OBJECT_PTR returnValue, void *theModule) - { - GetConstructList(theEnv,returnValue,DeffactsData(theEnv)->DeffactsConstruct,(struct defmodule *) theModule); + { + GetConstructList(theEnv,returnValue,DeffactsData(theEnv)->DeffactsConstruct,(struct defmodule *) theModule); } /************************************************/ @@ -243,8 +254,8 @@ globle void EnvGetDeffactsList( /************************************************/ globle void *DeffactsModuleFunction( void *theEnv) - { - return(GetConstructModuleCommand(theEnv,"deffacts-module",DeffactsData(theEnv)->DeffactsConstruct)); + { + return(GetConstructModuleCommand(theEnv,"deffacts-module",DeffactsData(theEnv)->DeffactsConstruct)); } #if DEBUGGING_FUNCTIONS @@ -255,8 +266,8 @@ globle void *DeffactsModuleFunction( /*******************************************/ globle void PPDeffactsCommand( void *theEnv) - { - PPConstructCommand(theEnv,"ppdeffacts",DeffactsData(theEnv)->DeffactsConstruct); + { + PPConstructCommand(theEnv,"ppdeffacts",DeffactsData(theEnv)->DeffactsConstruct); } /************************************/ @@ -265,10 +276,10 @@ globle void PPDeffactsCommand( /************************************/ globle int PPDeffacts( void *theEnv, - char *deffactsName, - char *logicalName) - { - return(PPConstruct(theEnv,deffactsName,logicalName,DeffactsData(theEnv)->DeffactsConstruct)); + const char *deffactsName, + const char *logicalName) + { + return(PPConstruct(theEnv,deffactsName,logicalName,DeffactsData(theEnv)->DeffactsConstruct)); } /*********************************************/ @@ -277,8 +288,8 @@ globle int PPDeffacts( /*********************************************/ globle void ListDeffactsCommand( void *theEnv) - { - ListConstructCommand(theEnv,"list-deffacts",DeffactsData(theEnv)->DeffactsConstruct); + { + ListConstructCommand(theEnv,"list-deffacts",DeffactsData(theEnv)->DeffactsConstruct); } /*************************************/ @@ -287,14 +298,46 @@ globle void ListDeffactsCommand( /*************************************/ globle void EnvListDeffacts( void *theEnv, - char *logicalName, + const char *logicalName, void *theModule) - { + { ListConstruct(theEnv,DeffactsData(theEnv)->DeffactsConstruct,logicalName,(struct defmodule *) theModule); } #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void GetDeffactsList( + DATA_OBJECT_PTR returnValue, + void *theModule) + { + EnvGetDeffactsList(GetCurrentEnvironment(),returnValue,theModule); + } + +globle intBool Undeffacts( + void *theDeffacts) + { + return EnvUndeffacts(GetCurrentEnvironment(),theDeffacts); + } + +#if DEBUGGING_FUNCTIONS + +globle void ListDeffacts( + const char *logicalName, + void *theModule) + { + EnvListDeffacts(GetCurrentEnvironment(),logicalName,theModule); + } + +#endif + +#endif + #endif /* DEFFACTS_CONSTRUCT */ diff --git a/src/dffctbsc.h b/src/dffctbsc.h index db3b72d..4638508 100644 --- a/src/dffctbsc.h +++ b/src/dffctbsc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -15,14 +15,24 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_dffctbsc @@ -42,16 +52,6 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetDeffactsList(theEnv,a,b) EnvGetDeffactsList(theEnv,a,b) -#define ListDeffacts(theEnv,a,b) EnvListDeffacts(theEnv,a,b) -#define Undeffacts(theEnv,a) EnvUndeffacts(theEnv,a) -#else -#define GetDeffactsList(a,b) EnvGetDeffactsList(GetCurrentEnvironment(),a,b) -#define ListDeffacts(a,b) EnvListDeffacts(GetCurrentEnvironment(),a,b) -#define Undeffacts(a) EnvUndeffacts(GetCurrentEnvironment(),a) -#endif - LOCALE void DeffactsBasicCommands(void *); LOCALE void UndeffactsCommand(void *); LOCALE intBool EnvUndeffacts(void *,void *); @@ -59,9 +59,19 @@ LOCALE void EnvGetDeffactsList(void *,DATA_OBJECT_PTR,void *); LOCALE void *DeffactsModuleFunction(void *); LOCALE void PPDeffactsCommand(void *); - LOCALE int PPDeffacts(void *,char *,char *); + LOCALE int PPDeffacts(void *,const char *,const char *); LOCALE void ListDeffactsCommand(void *); - LOCALE void EnvListDeffacts(void *,char *,void *); + LOCALE void EnvListDeffacts(void *,const char *,void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE void GetDeffactsList(DATA_OBJECT_PTR,void *); + LOCALE intBool Undeffacts(void *); +#if DEBUGGING_FUNCTIONS + LOCALE void ListDeffacts(const char *,void *); #endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_dffctbsc */ + diff --git a/src/dffctcmp.c b/src/dffctcmp.c index be1100e..cb6afce 100644 --- a/src/dffctcmp.c +++ b/src/dffctcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -14,10 +14,20 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _DFFCTCMP_SOURCE_ @@ -39,7 +49,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int ConstructToCode(void *,char *,int,FILE *,int,int); + static int ConstructToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void DeffactsToCode(void *,FILE *,struct deffacts *, int,int,int); static void DeffactsModuleToCode(void *,FILE *,struct defmodule *,int,int,int); @@ -53,7 +63,7 @@ globle void DeffactsCompilerSetup( void *theEnv) { - DeffactsData(theEnv)->DeffactsCodeItem = + DeffactsData(theEnv)->DeffactsCodeItem = AddCodeGeneratorItem(theEnv,"deffacts",0,BeforeDeffactsToCode, NULL,ConstructToCode,2); } @@ -75,7 +85,9 @@ static void BeforeDeffactsToCode( /**********************************************************/ static int ConstructToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -105,7 +117,7 @@ static int ConstructToCode( { EnvSetCurrentModule(theEnv,(void *) theModule); - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "struct deffactsModule",ModulePrefix(DeffactsData(theEnv)->DeffactsCodeItem), FALSE,NULL); @@ -128,7 +140,7 @@ static int ConstructToCode( theDeffacts != NULL; theDeffacts = (struct deffacts *) EnvGetNextDeffacts(theEnv,theDeffacts)) { - deffactsFile = OpenFileIfNeeded(theEnv,deffactsFile,fileName,fileID,imageID,&fileCount, + deffactsFile = OpenFileIfNeeded(theEnv,deffactsFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, deffactsArrayVersion,headerFP, "struct deffacts",ConstructPrefix(DeffactsData(theEnv)->DeffactsCodeItem), FALSE,NULL); @@ -184,9 +196,6 @@ static void CloseDeffactsFiles( /* DeffactsModuleToCode: Writes the C code representation */ /* of a single deffacts module to the specified file. */ /**********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DeffactsModuleToCode( void *theEnv, FILE *theFile, @@ -195,10 +204,10 @@ static void DeffactsModuleToCode( int maxIndices, int moduleCount) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(moduleCount) #endif - + fprintf(theFile,"{"); ConstructModuleToCode(theEnv,theFile,theModule,imageID,maxIndices, diff --git a/src/dffctcmp.h b/src/dffctcmp.h index 638a328..7408a99 100644 --- a/src/dffctcmp.h +++ b/src/dffctcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,13 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ #ifndef _H_dffctcmp @@ -35,4 +42,4 @@ LOCALE void DeffactsCompilerSetup(void *); LOCALE void DeffactsCModuleReference(void *,FILE *,int,int,int); -#endif +#endif /* _H_dffctcmp */ diff --git a/src/dffctdef.c b/src/dffctdef.c index e7120fe..da63a0c 100644 --- a/src/dffctdef.c +++ b/src/dffctdef.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFFACTS DEFINITION MODULE */ /*******************************************************/ @@ -15,7 +15,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -24,6 +24,19 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _DFFCTDEF_SOURCE_ @@ -67,11 +80,11 @@ /***********************************************************/ /* InitializeDeffacts: Initializes the deffacts construct. */ /***********************************************************/ -globle void InitializeDeffacts( +globle void InitializeDeffacts( void *theEnv) { AllocateEnvironmentData(theEnv,DEFFACTS_DATA,sizeof(struct deffactsData),DeallocateDeffactsData); - + InitializeDeffactsModules(theEnv); DeffactsBasicCommands(theEnv); @@ -82,7 +95,7 @@ globle void InitializeDeffacts( GetConstructModuleItem,EnvGetNextDeffacts,SetNextConstruct, EnvIsDeffactsDeletable,EnvUndeffacts,ReturnDeffacts); } - + /***************************************************/ /* DeallocateDeffactsData: Deallocates environment */ /* data for the deffacts construct. */ @@ -98,7 +111,7 @@ static void DeallocateDeffactsData( if (Bloaded(theEnv)) return; #endif - DoForAllConstructs(theEnv,DestroyDeffactsAction,DeffactsData(theEnv)->DeffactsModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDeffactsAction,DeffactsData(theEnv)->DeffactsModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; @@ -110,40 +123,37 @@ static void DeallocateDeffactsData( rtn_struct(theEnv,deffactsModule,theModuleItem); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } - + #if ! RUN_TIME /*********************************************************/ /* DestroyDeffactsAction: Action used to remove deffacts */ /* as a result of DestroyEnvironment. */ /*********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDeffactsAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif #if (! BLOAD_ONLY) && (! RUN_TIME) struct deffacts *theDeffacts = (struct deffacts *) theConstruct; - + if (theDeffacts == NULL) return; ReturnPackedExpression(theEnv,theDeffacts->assertList); - + DestroyConstructHeader(theEnv,&theDeffacts->header); rtn_struct(theEnv,deffacts,theDeffacts); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,theConstruct) #endif #endif @@ -154,10 +164,10 @@ static void DestroyDeffactsAction( /* InitializeDeffactsModules: Initializes the deffacts */ /* construct for use with the defmodule construct. */ /*******************************************************/ -static void InitializeDeffactsModules( +static void InitializeDeffactsModules( void *theEnv) { - DeffactsData(theEnv)->DeffactsModuleIndex = + DeffactsData(theEnv)->DeffactsModuleIndex = RegisterModuleItem(theEnv,"deffacts", AllocateModule, ReturnModule, @@ -171,7 +181,7 @@ static void InitializeDeffactsModules( #else NULL, #endif - EnvFindDeffacts); + EnvFindDeffactsInModule); } /************************************************/ @@ -180,7 +190,7 @@ static void InitializeDeffactsModules( static void *AllocateModule( void *theEnv) { - return((void *) get_struct(theEnv,deffactsModule)); + return((void *) get_struct(theEnv,deffactsModule)); } /************************************************/ @@ -201,8 +211,8 @@ static void ReturnModule( globle struct deffactsModule *GetDeffactsModuleItem( void *theEnv, struct defmodule *theModule) - { - return((struct deffactsModule *) GetConstructModuleItemByIndex(theEnv,theModule,DeffactsData(theEnv)->DeffactsModuleIndex)); + { + return((struct deffactsModule *) GetConstructModuleItemByIndex(theEnv,theModule,DeffactsData(theEnv)->DeffactsModuleIndex)); } /**************************************************/ @@ -212,9 +222,21 @@ globle struct deffactsModule *GetDeffactsModuleItem( /**************************************************/ globle void *EnvFindDeffacts( void *theEnv, - char *deffactsName) - { - return(FindNamedConstruct(theEnv,deffactsName,DeffactsData(theEnv)->DeffactsConstruct)); + const char *deffactsName) + { + return(FindNamedConstructInModuleOrImports(theEnv,deffactsName,DeffactsData(theEnv)->DeffactsConstruct)); + } + +/**************************************************/ +/* EnvFindDeffactsInModule: Searches for a deffact in the */ +/* list of deffacts. Returns a pointer to the */ +/* deffact if found, otherwise NULL. */ +/**************************************************/ +globle void *EnvFindDeffactsInModule( + void *theEnv, + const char *deffactsName) + { + return(FindNamedConstructInModule(theEnv,deffactsName,DeffactsData(theEnv)->DeffactsConstruct)); } /*********************************************************/ @@ -227,21 +249,18 @@ globle void *EnvGetNextDeffacts( void *theEnv, void *deffactsPtr) { - return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) deffactsPtr,DeffactsData(theEnv)->DeffactsModuleIndex)); + return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) deffactsPtr,DeffactsData(theEnv)->DeffactsModuleIndex)); } /********************************************************/ /* EnvIsDeffactsDeletable: Returns TRUE if a particular */ /* deffacts can be deleted, otherwise returns FALSE. */ /********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvIsDeffactsDeletable( void *theEnv, void *ptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(ptr) #endif if (! ConstructsDeletable(theEnv)) @@ -260,10 +279,6 @@ static void ReturnDeffacts( void *theEnv, void *vTheDeffacts) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vTheDeffacts) -#endif - #if (! BLOAD_ONLY) && (! RUN_TIME) struct deffacts *theDeffacts = (struct deffacts *) vTheDeffacts; @@ -277,7 +292,76 @@ static void ReturnDeffacts( rtn_struct(theEnv,deffacts,theDeffacts); #endif } - + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDeffactsModule( + void *theEnv, + void *theDeffacts) + { + return GetConstructModuleName((struct constructHeader *) theDeffacts); + } + +globle const char *EnvGetDeffactsName( + void *theEnv, + void *theDeffacts) + { + return GetConstructNameString((struct constructHeader *) theDeffacts); + } + +globle const char *EnvGetDeffactsPPForm( + void *theEnv, + void *theDeffacts) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDeffacts); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *FindDeffacts( + const char *deffactsName) + { + return EnvFindDeffacts(GetCurrentEnvironment(),deffactsName); + } + +globle void *GetNextDeffacts( + void *deffactsPtr) + { + return EnvGetNextDeffacts(GetCurrentEnvironment(),deffactsPtr); + } + +globle intBool IsDeffactsDeletable( + void *ptr) + { + return EnvIsDeffactsDeletable(GetCurrentEnvironment(),ptr); + } + +globle const char *DeffactsModule( + void *theDeffacts) + { + return EnvDeffactsModule(GetCurrentEnvironment(),theDeffacts); + } + +globle const char *GetDeffactsName( + void *theDeffacts) + { + return EnvGetDeffactsName(GetCurrentEnvironment(),theDeffacts); + } + +globle const char *GetDeffactsPPForm( + void *theDeffacts) + { + return EnvGetDeffactsPPForm(GetCurrentEnvironment(),theDeffacts); + } + +#endif + #endif /* DEFFACTS_CONSTRUCT */ diff --git a/src/dffctdef.h b/src/dffctdef.h index d2c3b32..97af508 100644 --- a/src/dffctdef.h +++ b/src/dffctdef.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFFACTS HEADER FILE */ /*******************************************************/ @@ -13,12 +13,25 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_dffctdef @@ -49,14 +62,14 @@ #define DEFFACTS_DATA 0 struct deffactsData - { + { struct construct *DeffactsConstruct; - int DeffactsModuleIndex; + int DeffactsModuleIndex; #if CONSTRUCT_COMPILER && (! RUN_TIME) struct CodeGeneratorItem *DeffactsCodeItem; #endif }; - + struct deffacts { struct constructHeader header; @@ -68,9 +81,6 @@ struct deffactsModule struct defmoduleItemHeader header; }; -#define EnvGetDeffactsName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDeffactsPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define EnvDeffactsModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) #define DeffactsData(theEnv) ((struct deffactsData *) GetEnvironmentData(theEnv,DEFFACTS_DATA)) #ifdef LOCALE @@ -83,29 +93,28 @@ struct deffactsModule #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DeffactsModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDeffacts(theEnv,a) EnvFindDeffacts(theEnv,a) -#define GetDeffactsName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDeffactsPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetNextDeffacts(theEnv,a) EnvGetNextDeffacts(theEnv,a) -#define IsDeffactsDeletable(theEnv,a) EnvIsDeffactsDeletable(theEnv,a) -#else -#define DeffactsModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDeffacts(a) EnvFindDeffacts(GetCurrentEnvironment(),a) -#define GetDeffactsName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDeffactsPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetNextDeffacts(a) EnvGetNextDeffacts(GetCurrentEnvironment(),a) -#define IsDeffactsDeletable(a) EnvIsDeffactsDeletable(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeDeffacts(void *); - LOCALE void *EnvFindDeffacts(void *,char *); + LOCALE void *EnvFindDeffacts(void *,const char *); + LOCALE void *EnvFindDeffactsInModule(void *,const char *); LOCALE void *EnvGetNextDeffacts(void *,void *); LOCALE void CreateInitialFactDeffacts(void); LOCALE intBool EnvIsDeffactsDeletable(void *,void *); LOCALE struct deffactsModule *GetDeffactsModuleItem(void *,struct defmodule *); + LOCALE const char *EnvDeffactsModule(void *,void *); + LOCALE const char *EnvGetDeffactsName(void *,void *); + LOCALE const char *EnvGetDeffactsPPForm(void *,void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void *FindDeffacts(const char *); + LOCALE void *GetNextDeffacts(void *); + LOCALE intBool IsDeffactsDeletable(void *); + LOCALE const char *DeffactsModule(void *); + LOCALE const char *GetDeffactsName(void *); + LOCALE const char *GetDeffactsPPForm(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_dffctdef */ diff --git a/src/dffctpsr.c b/src/dffctpsr.c index 6fd40fc..30a6a24 100644 --- a/src/dffctpsr.c +++ b/src/dffctpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFFACTS PARSER MODULE */ /*******************************************************/ @@ -13,10 +13,23 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _DFFCTPSR_SOURCE_ @@ -46,12 +59,8 @@ /************************************************************/ globle int ParseDeffacts( void *theEnv, - char *readSource) + const char *readSource) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,readSource) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) SYMBOL_HN *deffactsName; struct expr *temp; @@ -87,8 +96,8 @@ globle int ParseDeffacts( /*============================*/ deffactsName = GetConstructNameAndComment(theEnv,readSource,&inputToken,"deffacts", - EnvFindDeffacts,EnvUndeffacts,"$",TRUE, - TRUE,TRUE); + EnvFindDeffactsInModule,EnvUndeffacts,"$",TRUE, + TRUE,TRUE,FALSE); if (deffactsName == NULL) { return(TRUE); } /*===============================================*/ diff --git a/src/dffctpsr.h b/src/dffctpsr.h index 10098e3..6d78f0b 100644 --- a/src/dffctpsr.h +++ b/src/dffctpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFFACTS PARSER HEADER FILE */ /*******************************************************/ @@ -13,10 +13,19 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_dffctpsr @@ -32,7 +41,7 @@ #define LOCALE extern #endif - LOCALE int ParseDeffacts(void *,char *); + LOCALE int ParseDeffacts(void *,const char *); -#endif +#endif /* _H_dffctpsr */ diff --git a/src/dffnxbin.c b/src/dffnxbin.c index 4314a32..0031396 100644 --- a/src/dffnxbin.c +++ b/src/dffnxbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Binary Load/Save Functions for Deffunctions */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ /* ========================================= @@ -117,7 +123,7 @@ globle void SetupDeffunctionsBload( ClearDeffunctionBload); #endif } - + /***********************************************************/ /* DeallocateDeffunctionBloadData: Deallocates environment */ /* data for the deffunction bsave functionality. */ @@ -125,14 +131,14 @@ globle void SetupDeffunctionsBload( static void DeallocateDeffunctionBloadData( void *theEnv) { - unsigned long space; + size_t space; #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) space = DeffunctionBinaryData(theEnv)->DeffunctionCount * sizeof(struct deffunctionStruct); - if (space != 0) genlongfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->DeffunctionArray,space); + if (space != 0) genfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->DeffunctionArray,space); space = DeffunctionBinaryData(theEnv)->ModuleCount * sizeof(struct deffunctionModule); - if (space != 0) genlongfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->ModuleArray,space); #endif } @@ -182,7 +188,7 @@ static void BsaveDeffunctionFind( SaveBloadCount(theEnv,DeffunctionBinaryData(theEnv)->DeffunctionCount); DeffunctionBinaryData(theEnv)->DeffunctionCount = 0L; - DeffunctionBinaryData(theEnv)->ModuleCount = + DeffunctionBinaryData(theEnv)->ModuleCount = DoForAllConstructs(theEnv,MarkDeffunctionItems,DeffunctionData(theEnv)->DeffunctionModuleIndex, FALSE,NULL); } @@ -197,15 +203,12 @@ static void BsaveDeffunctionFind( SIDE EFFECTS : Needed items marked NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkDeffunctionItems( void *theEnv, struct constructHeader *theDeffunction, void *userBuffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(userBuffer) #endif @@ -263,12 +266,12 @@ static void BsaveStorageDeffunctions( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; space = sizeof(unsigned long) * 2; - GenWrite((void *) &space,(unsigned long) sizeof(unsigned long),fp); - GenWrite((void *) &DeffunctionBinaryData(theEnv)->ModuleCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DeffunctionBinaryData(theEnv)->DeffunctionCount,(unsigned long) sizeof(long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); + GenWrite((void *) &DeffunctionBinaryData(theEnv)->ModuleCount,sizeof(unsigned long),fp); + GenWrite((void *) &DeffunctionBinaryData(theEnv)->DeffunctionCount,sizeof(unsigned long),fp); } /************************************************************************************* @@ -285,14 +288,14 @@ static void BsaveDeffunctions( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; struct defmodule *theModule; DEFFUNCTION_MODULE *theModuleItem; BSAVE_DEFFUNCTION_MODULE dummy_mitem; - space = (unsigned long) ((sizeof(BSAVE_DEFFUNCTION_MODULE) * DeffunctionBinaryData(theEnv)->ModuleCount) + - (sizeof(BSAVE_DEFFUNCTION) * DeffunctionBinaryData(theEnv)->DeffunctionCount)); - GenWrite((void *) &space,(unsigned long) sizeof(unsigned long),fp); + space = ((sizeof(BSAVE_DEFFUNCTION_MODULE) * DeffunctionBinaryData(theEnv)->ModuleCount) + + (sizeof(BSAVE_DEFFUNCTION) * DeffunctionBinaryData(theEnv)->DeffunctionCount)); + GenWrite((void *) &space,sizeof(size_t),fp); /* ================================= Write out each deffunction module @@ -304,7 +307,7 @@ static void BsaveDeffunctions( theModuleItem = (DEFFUNCTION_MODULE *) GetModuleItem(theEnv,theModule,FindModuleItem(theEnv,"deffunction")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&dummy_mitem.header,&theModuleItem->header); - GenWrite((void *) &dummy_mitem,(unsigned long) sizeof(BSAVE_DEFFUNCTION_MODULE),fp); + GenWrite((void *) &dummy_mitem,sizeof(BSAVE_DEFFUNCTION_MODULE),fp); theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule); } @@ -346,7 +349,7 @@ static void BsaveDeffunction( } else dummy_df.code = -1L; - GenWrite((void *) &dummy_df,(unsigned long) sizeof(BSAVE_DEFFUNCTION),(FILE *) userBuffer); + GenWrite((void *) &dummy_df,sizeof(BSAVE_DEFFUNCTION),(FILE *) userBuffer); } #endif @@ -364,13 +367,13 @@ static void BsaveDeffunction( static void BloadStorageDeffunctions( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) return; - GenReadBinary(theEnv,(void *) &DeffunctionBinaryData(theEnv)->ModuleCount,(unsigned long) sizeof(unsigned long)); - GenReadBinary(theEnv,(void *) &DeffunctionBinaryData(theEnv)->DeffunctionCount,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &DeffunctionBinaryData(theEnv)->ModuleCount,sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &DeffunctionBinaryData(theEnv)->DeffunctionCount,sizeof(unsigned long)); if (DeffunctionBinaryData(theEnv)->ModuleCount == 0L) { DeffunctionBinaryData(theEnv)->ModuleArray = NULL; @@ -378,8 +381,8 @@ static void BloadStorageDeffunctions( return; } - space = (unsigned long) (DeffunctionBinaryData(theEnv)->ModuleCount * sizeof(DEFFUNCTION_MODULE)); - DeffunctionBinaryData(theEnv)->ModuleArray = (DEFFUNCTION_MODULE *) genlongalloc(theEnv,space); + space = (DeffunctionBinaryData(theEnv)->ModuleCount * sizeof(DEFFUNCTION_MODULE)); + DeffunctionBinaryData(theEnv)->ModuleArray = (DEFFUNCTION_MODULE *) genalloc(theEnv,space); if (DeffunctionBinaryData(theEnv)->DeffunctionCount == 0L) { @@ -387,8 +390,8 @@ static void BloadStorageDeffunctions( return; } - space = (unsigned long) (DeffunctionBinaryData(theEnv)->DeffunctionCount * sizeof(DEFFUNCTION)); - DeffunctionBinaryData(theEnv)->DeffunctionArray = (DEFFUNCTION *) genlongalloc(theEnv,space); + space = (DeffunctionBinaryData(theEnv)->DeffunctionCount * sizeof(DEFFUNCTION)); + DeffunctionBinaryData(theEnv)->DeffunctionArray = (DEFFUNCTION *) genalloc(theEnv,space); } /********************************************************************* @@ -405,9 +408,9 @@ static void BloadStorageDeffunctions( static void BloadDeffunctions( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); BloadandRefresh(theEnv,DeffunctionBinaryData(theEnv)->ModuleCount,sizeof(BSAVE_DEFFUNCTION_MODULE),UpdateDeffunctionModule); BloadandRefresh(theEnv,DeffunctionBinaryData(theEnv)->DeffunctionCount,sizeof(BSAVE_DEFFUNCTION),UpdateDeffunction); } @@ -488,21 +491,21 @@ static void ClearDeffunctionBload( void *theEnv) { register long i; - unsigned long space; + size_t space; - space = (unsigned long) (sizeof(DEFFUNCTION_MODULE) * DeffunctionBinaryData(theEnv)->ModuleCount); + space = (sizeof(DEFFUNCTION_MODULE) * DeffunctionBinaryData(theEnv)->ModuleCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->ModuleArray,space); + genfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->ModuleArray,space); DeffunctionBinaryData(theEnv)->ModuleArray = NULL; DeffunctionBinaryData(theEnv)->ModuleCount = 0L; for (i = 0L ; i < DeffunctionBinaryData(theEnv)->DeffunctionCount ; i++) UnmarkConstructHeader(theEnv,&DeffunctionBinaryData(theEnv)->DeffunctionArray[i].header); - space = (unsigned long) (sizeof(DEFFUNCTION) * DeffunctionBinaryData(theEnv)->DeffunctionCount); + space = (sizeof(DEFFUNCTION) * DeffunctionBinaryData(theEnv)->DeffunctionCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->DeffunctionArray,space); + genfree(theEnv,(void *) DeffunctionBinaryData(theEnv)->DeffunctionArray,space); DeffunctionBinaryData(theEnv)->DeffunctionArray = NULL; DeffunctionBinaryData(theEnv)->DeffunctionCount = 0L; } diff --git a/src/dffnxbin.h b/src/dffnxbin.h index c7d8963..8f2cc87 100644 --- a/src/dffnxbin.h +++ b/src/dffnxbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_dffnxbin @@ -35,26 +41,26 @@ #define LOCALE extern #endif -LOCALE void SetupDeffunctionsBload(void *); -LOCALE void *BloadDeffunctionModuleReference(void *,int); + LOCALE void SetupDeffunctionsBload(void *); + LOCALE void *BloadDeffunctionModuleReference(void *,int); #define DFFNXBIN_DATA 24 struct deffunctionBinaryData - { + { DEFFUNCTION *DeffunctionArray; long DeffunctionCount; long ModuleCount; DEFFUNCTION_MODULE *ModuleArray; }; - + #define DeffunctionBinaryData(theEnv) ((struct deffunctionBinaryData *) GetEnvironmentData(theEnv,DFFNXBIN_DATA)) #define DeffunctionPointer(i) (((i) == -1L) ? NULL : (DEFFUNCTION *) &DeffunctionBinaryData(theEnv)->DeffunctionArray[i]) -#endif +#endif /* DEFFUNCTION_CONSTRUCT && (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) */ -#endif +#endif /* _H_dffnxbin */ diff --git a/src/dffnxcmp.c b/src/dffnxcmp.c index d305f99..195fc7d 100644 --- a/src/dffnxcmp.c +++ b/src/dffnxcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Generic Function Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -40,7 +46,7 @@ ***************************************** */ static void ReadyDeffunctionsForCode(void *); -static int DeffunctionsToCode(void *,char *,int,FILE *,int,int); +static int DeffunctionsToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void CloseDeffunctionFiles(void *,FILE *,FILE *,int); static void DeffunctionModuleToCode(void *,FILE *,struct defmodule *,int,int); static void SingleDeffunctionToCode(void *,FILE *,DEFFUNCTION *,int,int,int); @@ -162,7 +168,9 @@ static void ReadyDeffunctionsForCode( *******************************************************/ static int DeffunctionsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -190,7 +198,7 @@ static int DeffunctionsToCode( { EnvSetCurrentModule(theEnv,(void *) theModule); - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "DEFFUNCTION_MODULE",ModulePrefix(DeffunctionData(theEnv)->DeffunctionCodeItem), FALSE,NULL); @@ -209,7 +217,7 @@ static int DeffunctionsToCode( while (theDeffunction != NULL) { - deffunctionFile = OpenFileIfNeeded(theEnv,deffunctionFile,fileName,fileID,imageID,&fileCount, + deffunctionFile = OpenFileIfNeeded(theEnv,deffunctionFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, deffunctionArrayVersion,headerFP, "DEFFUNCTION",ConstructPrefix(DeffunctionData(theEnv)->DeffunctionCodeItem), FALSE,NULL); diff --git a/src/dffnxcmp.h b/src/dffnxcmp.h index 0877842..5c44788 100644 --- a/src/dffnxcmp.h +++ b/src/dffnxcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Deffunction Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_dffnxcmp @@ -40,12 +46,12 @@ #define LOCALE extern #endif -LOCALE void SetupDeffunctionCompiler(void *); -LOCALE void PrintDeffunctionReference(void *,FILE *,DEFFUNCTION *,int,int); -LOCALE void DeffunctionCModuleReference(void *,FILE *,int,int,int); + LOCALE void SetupDeffunctionCompiler(void *); + LOCALE void PrintDeffunctionReference(void *,FILE *,DEFFUNCTION *,int,int); + LOCALE void DeffunctionCModuleReference(void *,FILE *,int,int,int); -#endif +#endif /* DEFFUNCTION_CONSTRUCT && CONSTRUCT_COMPILER && (! RUN_TIME) */ -#endif +#endif /* _H_dffnxcmp */ diff --git a/src/dffnxexe.c b/src/dffnxexe.c index 9526ce6..c4972a4 100644 --- a/src/dffnxexe.c +++ b/src/dffnxexe.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,13 +10,21 @@ /* Purpose: Deffunction Execution Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -33,6 +41,8 @@ #include <stdio.h> #endif +#include <string.h> + #include "constrct.h" #include "envrnmnt.h" #include "prcdrfun.h" @@ -62,7 +72,7 @@ static void UnboundDeffunctionErr(void *); #if DEBUGGING_FUNCTIONS -static void WatchDeffunction(void *,char *); +static void WatchDeffunction(void *,const char *); #endif /* ========================================= @@ -90,6 +100,8 @@ globle void CallDeffunction( { int oldce; DEFFUNCTION *previouslyExecutingDeffunction; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; #endif @@ -99,6 +111,12 @@ globle void CallDeffunction( EvaluationData(theEnv)->EvaluationError = FALSE; if (EvaluationData(theEnv)->HaltExecution) return; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + oldce = ExecutingConstruct(theEnv); SetExecutingConstruct(theEnv,TRUE); previouslyExecutingDeffunction = DeffunctionData(theEnv)->ExecutingDeffunction; @@ -112,7 +130,10 @@ globle void CallDeffunction( dptr->executing--; DeffunctionData(theEnv)->ExecutingDeffunction = previouslyExecutingDeffunction; EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); return; } @@ -146,8 +167,10 @@ globle void CallDeffunction( PopProcParameters(theEnv); DeffunctionData(theEnv)->ExecutingDeffunction = previouslyExecutingDeffunction; EvaluationData(theEnv)->CurrentEvaluationDepth--; - PropagateReturnValue(theEnv,result); - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); } @@ -191,7 +214,7 @@ static void UnboundDeffunctionErr( ***************************************************/ static void WatchDeffunction( void *theEnv, - char *tstring) + const char *tstring) { EnvPrintRouter(theEnv,WTRACE,"DFN "); EnvPrintRouter(theEnv,WTRACE,tstring); @@ -203,7 +226,7 @@ static void WatchDeffunction( } EnvPrintRouter(theEnv,WTRACE,ValueToString(DeffunctionData(theEnv)->ExecutingDeffunction->header.name)); EnvPrintRouter(theEnv,WTRACE," ED:"); - PrintLongInteger(theEnv,WTRACE,(long) EvaluationData(theEnv)->CurrentEvaluationDepth); + PrintLongInteger(theEnv,WTRACE,(long long) EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,WTRACE); } diff --git a/src/dffnxexe.h b/src/dffnxexe.h index 2ed79ef..e08bd51 100644 --- a/src/dffnxexe.h +++ b/src/dffnxexe.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,21 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_dffnxexe @@ -41,11 +50,11 @@ #define LOCALE extern #endif -LOCALE void CallDeffunction(void *,DEFFUNCTION *,EXPRESSION *,DATA_OBJECT *); + LOCALE void CallDeffunction(void *,DEFFUNCTION *,EXPRESSION *,DATA_OBJECT *); -#endif +#endif /* DEFFUNCTION_CONSTRUCT */ -#endif +#endif /* _H_dffnxexe */ diff --git a/src/dffnxfun.c b/src/dffnxfun.c index 7c9c722..8026873 100644 --- a/src/dffnxfun.c +++ b/src/dffnxfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* DEFFUNCTION MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -30,6 +31,27 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added missing initializer for ENTITY_RECORD. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ /* ========================================= @@ -83,7 +105,7 @@ ========================================= ***************************************** */ -static void PrintDeffunctionCall(void *,char *,void *); +static void PrintDeffunctionCall(void *,const char *,void *); static intBool EvaluateDeffunctionCall(void *,void *,DATA_OBJECT *); static void DecrementDeffunctionBusyCount(void *,void *); static void IncrementDeffunctionBusyCount(void *,void *); @@ -98,15 +120,15 @@ static intBool ClearDeffunctionsReady(void *); #if (! BLOAD_ONLY) && (! RUN_TIME) static intBool RemoveAllDeffunctions(void *); -static void DeffunctionDeleteError(void *,char *); -static void SaveDeffunctionHeaders(void *,void *,char *); +static void DeffunctionDeleteError(void *,const char *); +static void SaveDeffunctionHeaders(void *,void *,const char *); static void SaveDeffunctionHeader(void *,struct constructHeader *,void *); -static void SaveDeffunctions(void *,void *,char *); +static void SaveDeffunctions(void *,void *,const char *); #endif #if DEBUGGING_FUNCTIONS static unsigned DeffunctionWatchAccess(void *,int,unsigned,EXPRESSION *); -static unsigned DeffunctionWatchPrint(void *,char *,int,EXPRESSION *); +static unsigned DeffunctionWatchPrint(void *,const char *,int,EXPRESSION *); #endif /* ========================================= @@ -132,10 +154,10 @@ globle void SetupDeffunctions( PrintDeffunctionCall,PrintDeffunctionCall, NULL,EvaluateDeffunctionCall,NULL, DecrementDeffunctionBusyCount,IncrementDeffunctionBusyCount, - NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL }; AllocateEnvironmentData(theEnv,DEFFUNCTION_DATA,sizeof(struct deffunctionData),DeallocateDeffunctionData); - memcpy(&DeffunctionData(theEnv)->DeffunctionEntityRecord,&deffunctionEntityRecord,sizeof(struct entityRecord)); + memcpy(&DeffunctionData(theEnv)->DeffunctionEntityRecord,&deffunctionEntityRecord,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&DeffunctionData(theEnv)->DeffunctionEntityRecord,PCALL); @@ -156,7 +178,7 @@ globle void SetupDeffunctions( #else NULL, #endif - EnvFindDeffunction); + EnvFindDeffunctionInModule); DeffunctionData(theEnv)->DeffunctionConstruct = AddConstruct(theEnv,"deffunction","deffunctions", #if (! BLOAD_ONLY) && (! RUN_TIME) @@ -214,7 +236,7 @@ globle void SetupDeffunctions( #endif } - + /******************************************************/ /* DeallocateDeffunctionData: Deallocates environment */ /* data for the deffunction construct. */ @@ -230,7 +252,7 @@ static void DeallocateDeffunctionData( if (Bloaded(theEnv)) return; #endif - DoForAllConstructs(theEnv,DestroyDeffunctionAction,DeffunctionData(theEnv)->DeffunctionModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDeffunctionAction,DeffunctionData(theEnv)->DeffunctionModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; @@ -242,40 +264,37 @@ static void DeallocateDeffunctionData( rtn_struct(theEnv,deffunctionModule,theModuleItem); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } - + #if ! RUN_TIME /*****************************************************/ /* DestroyDeffunctionAction: Action used to remove */ /* deffunctions as a result of DestroyEnvironment. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDeffunctionAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif #if (! BLOAD_ONLY) && (! RUN_TIME) struct deffunctionStruct *theDeffunction = (struct deffunctionStruct *) theConstruct; - + if (theDeffunction == NULL) return; - + ReturnPackedExpression(theEnv,theDeffunction->code); DestroyConstructHeader(theEnv,&theDeffunction->header); - + rtn_struct(theEnv,deffunctionStruct,theDeffunction); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theConstruct,theEnv) #endif #endif @@ -294,9 +313,26 @@ static void DestroyDeffunctionAction( ***************************************************/ globle void *EnvFindDeffunction( void *theEnv, - char *dfnxModuleAndName) + const char *dfnxModuleAndName) + { + return(FindNamedConstructInModuleOrImports(theEnv,dfnxModuleAndName,DeffunctionData(theEnv)->DeffunctionConstruct)); + } + +/*************************************************** + NAME : EnvFindDeffunctionInModule + DESCRIPTION : Searches for a deffunction + INPUTS : The name of the deffunction + (possibly including a module name) + RETURNS : Pointer to the deffunction if + found, otherwise NULL + SIDE EFFECTS : None + NOTES : None + ***************************************************/ +globle void *EnvFindDeffunctionInModule( + void *theEnv, + const char *dfnxModuleAndName) { - return(FindNamedConstruct(theEnv,dfnxModuleAndName,DeffunctionData(theEnv)->DeffunctionConstruct)); + return(FindNamedConstructInModule(theEnv,dfnxModuleAndName,DeffunctionData(theEnv)->DeffunctionConstruct)); } /*************************************************** @@ -312,7 +348,7 @@ globle void *EnvFindDeffunction( ***************************************************/ globle DEFFUNCTION *LookupDeffunctionByMdlOrScope( void *theEnv, - char *deffunctionName) + const char *deffunctionName) { return((DEFFUNCTION *) LookupConstruct(theEnv,DeffunctionData(theEnv)->DeffunctionConstruct,deffunctionName,TRUE)); } @@ -330,7 +366,7 @@ globle DEFFUNCTION *LookupDeffunctionByMdlOrScope( ***************************************************/ globle DEFFUNCTION *LookupDeffunctionInScope( void *theEnv, - char *deffunctionName) + const char *deffunctionName) { return((DEFFUNCTION *) LookupConstruct(theEnv,DeffunctionData(theEnv)->DeffunctionConstruct,deffunctionName,FALSE)); } @@ -349,10 +385,6 @@ globle intBool EnvUndeffunction( void *theEnv, void *vptr) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vptr) -#endif - #if BLOAD_ONLY || RUN_TIME return(FALSE); #else @@ -431,10 +463,10 @@ globle void RemoveDeffunction( if (dptr == NULL) return; - DecrementSymbolCount(theEnv,GetDeffunctionNamePointer((void *) dptr)); + DecrementSymbolCount(theEnv,EnvGetDeffunctionNamePointer(theEnv,(void *) dptr)); ExpressionDeinstall(theEnv,dptr->code); ReturnPackedExpression(theEnv,dptr->code); - SetDeffunctionPPForm((void *) dptr,NULL); + EnvSetDeffunctionPPForm(theEnv,(void *) dptr,NULL); ClearUserDataList(theEnv,dptr->header.usrData); rtn_struct(theEnv,deffunctionStruct,dptr); } @@ -512,7 +544,7 @@ globle void ListDeffunctionsCommand( ***************************************************/ globle void EnvListDeffunctions( void *theEnv, - char *logicalName, + const char *logicalName, struct defmodule *theModule) { ListConstruct(theEnv,DeffunctionData(theEnv)->DeffunctionConstruct,logicalName,theModule); @@ -612,12 +644,9 @@ globle int CheckDeffunctionCall( SIDE EFFECTS : Call expression printed NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void PrintDeffunctionCall( void *theEnv, - char *logName, + const char *logName, void *value) { #if DEVELOPER @@ -631,7 +660,7 @@ static void PrintDeffunctionCall( } EnvPrintRouter(theEnv,logName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logName) #pragma unused(value) @@ -698,16 +727,17 @@ static void DecrementDeffunctionBusyCount( SIDE EFFECTS : Busy count incremented NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void IncrementDeffunctionBusyCount( void *theEnv, void *value) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif ((DEFFUNCTION *) value)->busy++; } @@ -826,7 +856,7 @@ static intBool RemoveAllDeffunctions( EnvPrintRouter(theEnv,WWARNING,"Deffunction "); EnvPrintRouter(theEnv,WWARNING,EnvGetDeffunctionName(theEnv,(void *) dtmp)); EnvPrintRouter(theEnv,WWARNING," only partially deleted due to usage by other constructs.\n"); - SetDeffunctionPPForm((void *) dtmp,NULL); + EnvSetDeffunctionPPForm(theEnv,(void *) dtmp,NULL); success = FALSE; } else @@ -850,7 +880,7 @@ static intBool RemoveAllDeffunctions( ****************************************************/ static void DeffunctionDeleteError( void *theEnv, - char *dfnxName) + const char *dfnxName) { CantDeleteItemErrorMessage(theEnv,"deffunction",dfnxName); } @@ -870,7 +900,7 @@ static void DeffunctionDeleteError( static void SaveDeffunctionHeaders( void *theEnv, void *theModule, - char *logicalName) + const char *logicalName) { DoForAllConstructsInModule(theEnv,theModule,SaveDeffunctionHeader, DeffunctionData(theEnv)->DeffunctionModuleIndex, @@ -893,20 +923,20 @@ static void SaveDeffunctionHeader( void *userBuffer) { DEFFUNCTION *dfnxPtr = (DEFFUNCTION *) theDeffunction; - char *logicalName = (char *) userBuffer; + const char *logicalName = (const char *) userBuffer; register int i; if (EnvGetDeffunctionPPForm(theEnv,(void *) dfnxPtr) != NULL) { EnvPrintRouter(theEnv,logicalName,"(deffunction "); EnvPrintRouter(theEnv,logicalName,EnvDeffunctionModule(theEnv,(void *) dfnxPtr)); - EnvPrintRouter(theEnv,logicalName,"::"); + EnvPrintRouter(theEnv,logicalName,"::"); EnvPrintRouter(theEnv,logicalName,EnvGetDeffunctionName(theEnv,(void *) dfnxPtr)); EnvPrintRouter(theEnv,logicalName," ("); for (i = 0 ; i < dfnxPtr->minNumberOfParameters ; i++) { EnvPrintRouter(theEnv,logicalName,"?p"); - PrintLongInteger(theEnv,logicalName,(long) i); + PrintLongInteger(theEnv,logicalName,(long long) i); if (i != dfnxPtr->minNumberOfParameters-1) EnvPrintRouter(theEnv,logicalName," "); } @@ -933,7 +963,7 @@ static void SaveDeffunctionHeader( static void SaveDeffunctions( void *theEnv, void *theModule, - char *logicalName) + const char *logicalName) { SaveConstruct(theEnv,theModule,logicalName,DeffunctionData(theEnv)->DeffunctionConstruct); } @@ -955,16 +985,13 @@ static void SaveDeffunctions( SIDE EFFECTS : Watch flags set in specified deffunctions NOTES : Accessory function for AddWatchItem() ******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DeffunctionWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -985,16 +1012,13 @@ static unsigned DeffunctionWatchAccess( SIDE EFFECTS : Watch flags displayed for specified deffunctions NOTES : Accessory function for AddWatchItem() ***********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DeffunctionWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -1013,15 +1037,12 @@ static unsigned DeffunctionWatchPrint( SIDE EFFECTS : Watch flag for the deffunction set NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDeffunctionWatch( void *theEnv, unsigned newState, void *dptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1038,14 +1059,11 @@ globle void EnvSetDeffunctionWatch( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDeffunctionWatch( void *theEnv, void *dptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1054,6 +1072,128 @@ globle unsigned EnvGetDeffunctionWatch( #endif +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDeffunctionModule( + void *theEnv, + void *theDeffunction) + { + return GetConstructModuleName((struct constructHeader *) theDeffunction); + } + +globle const char *EnvGetDeffunctionName( + void *theEnv, + void *theDeffunction) + { + return GetConstructNameString((struct constructHeader *) theDeffunction); + } + +globle const char *EnvGetDeffunctionPPForm( + void *theEnv, + void *theDeffunction) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDeffunction); + } + +globle SYMBOL_HN *EnvGetDeffunctionNamePointer( + void *theEnv, + void *theDeffunction) + { + return GetConstructNamePointer((struct constructHeader *) theDeffunction); + } + +globle void EnvSetDeffunctionPPForm( + void *theEnv, + void *theDeffunction, + const char *thePPForm) + { + SetConstructPPForm(theEnv,(struct constructHeader *) theDeffunction,thePPForm); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *DeffunctionModule( + void *theDeffunction) + { + return EnvDeffunctionModule(GetCurrentEnvironment(),theDeffunction); + } + +globle void *FindDeffunction( + const char *deffunctionName) + { + return EnvFindDeffunction(GetCurrentEnvironment(),deffunctionName); + } + +globle void *GetNextDeffunction( + void *deffunctionPtr) + { + return EnvGetNextDeffunction(GetCurrentEnvironment(),deffunctionPtr); + } + +globle intBool IsDeffunctionDeletable( + void *ptr) + { + return EnvIsDeffunctionDeletable(GetCurrentEnvironment(),ptr); + } + +globle const char *GetDeffunctionName( + void *theDeffunction) + { + return EnvGetDeffunctionName(GetCurrentEnvironment(),theDeffunction); + } + +globle const char *GetDeffunctionPPForm( + void *theDeffunction) + { + return EnvGetDeffunctionPPForm(GetCurrentEnvironment(),theDeffunction); + } + +globle intBool Undeffunction( + void *vptr) + { + return EnvUndeffunction(GetCurrentEnvironment(),vptr); + } + +globle void GetDeffunctionList( + DATA_OBJECT *returnValue, + struct defmodule *theModule) + { + EnvGetDeffunctionList(GetCurrentEnvironment(),returnValue,theModule); + } + +#if DEBUGGING_FUNCTIONS + +globle void ListDeffunctions( + const char *logicalName, + struct defmodule *theModule) + { + EnvListDeffunctions(GetCurrentEnvironment(),logicalName,theModule); + } + +globle unsigned GetDeffunctionWatch( + void *dptr) + { + return EnvGetDeffunctionWatch(GetCurrentEnvironment(),dptr); + } + +globle void SetDeffunctionWatch( + unsigned newState, + void *dptr) + { + EnvSetDeffunctionWatch(GetCurrentEnvironment(),newState,dptr); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + + #endif diff --git a/src/dffnxfun.h b/src/dffnxfun.h index 4cc159a..ce3cbdf 100644 --- a/src/dffnxfun.h +++ b/src/dffnxfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFFUNCTION HEADER FILE */ /*******************************************************/ @@ -10,30 +10,49 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ +/* Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove run-time program */ +/* compiler warning. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added missing initializer for ENTITY_RECORD. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_dffnxfun #define _H_dffnxfun -#define EnvGetDeffunctionName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDeffunctionPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) - -#define GetDeffunctionNamePointer(x) GetConstructNamePointer((struct constructHeader *) x) -#define SetDeffunctionPPForm(d,ppf) SetConstructPPForm(theEnv,(struct constructHeader *) d,ppf) - -#define EnvDeffunctionModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - typedef struct deffunctionStruct DEFFUNCTION; typedef struct deffunctionModule DEFFUNCTION_MODULE; @@ -81,11 +100,11 @@ struct deffunctionStruct maxNumberOfParameters, numberOfLocalVars; }; - + #define DEFFUNCTION_DATA 23 struct deffunctionData - { + { struct construct *DeffunctionConstruct; int DeffunctionModuleIndex; ENTITY_RECORD DeffunctionEntityRecord; @@ -101,61 +120,58 @@ struct deffunctionData #define DeffunctionData(theEnv) ((struct deffunctionData *) GetEnvironmentData(theEnv,DEFFUNCTION_DATA)) -#if ENVIRONMENT_API_ONLY -#define DeffunctionModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDeffunction(theEnv,a) EnvFindDeffunction(theEnv,a) -#define GetDeffunctionList(theEnv,a,b) EnvGetDeffunctionList(theEnv,a,b) -#define GetDeffunctionName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDeffunctionPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetDeffunctionWatch(theEnv,a) EnvGetDeffunctionWatch(theEnv,a) -#define GetNextDeffunction(theEnv,a) EnvGetNextDeffunction(theEnv,a) -#define IsDeffunctionDeletable(theEnv,a) EnvIsDeffunctionDeletable(theEnv,a) -#define ListDeffunctions(theEnv,a,b) EnvListDeffunctions(theEnv,a,b) -#define SetDeffunctionWatch(theEnv,a,b) EnvSetDeffunctionWatch(theEnv,a,b) -#define Undeffunction(theEnv,a) EnvUndeffunction(theEnv,a) -#else -#define DeffunctionModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDeffunction(a) EnvFindDeffunction(GetCurrentEnvironment(),a) -#define GetDeffunctionList(a,b) EnvGetDeffunctionList(GetCurrentEnvironment(),a,b) -#define GetDeffunctionName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDeffunctionPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetDeffunctionWatch(a) EnvGetDeffunctionWatch(GetCurrentEnvironment(),a) -#define GetNextDeffunction(a) EnvGetNextDeffunction(GetCurrentEnvironment(),a) -#define IsDeffunctionDeletable(a) EnvIsDeffunctionDeletable(GetCurrentEnvironment(),a) -#define ListDeffunctions(a,b) EnvListDeffunctions(GetCurrentEnvironment(),a,b) -#define SetDeffunctionWatch(a,b) EnvSetDeffunctionWatch(GetCurrentEnvironment(),a,b) -#define Undeffunction(a) EnvUndeffunction(GetCurrentEnvironment(),a) + LOCALE int CheckDeffunctionCall(void *,void *,int); + LOCALE void DeffunctionGetBind(DATA_OBJECT *); + LOCALE void DFRtnUnknown(DATA_OBJECT *); + LOCALE void DFWildargs(DATA_OBJECT *); + LOCALE const char *EnvDeffunctionModule(void *,void *); + LOCALE void *EnvFindDeffunction(void *,const char *); + LOCALE void *EnvFindDeffunctionInModule(void *,const char *); + LOCALE void EnvGetDeffunctionList(void *,DATA_OBJECT *,struct defmodule *); + LOCALE const char *EnvGetDeffunctionName(void *,void *); + LOCALE SYMBOL_HN *EnvGetDeffunctionNamePointer(void *,void *); + LOCALE const char *EnvGetDeffunctionPPForm(void *,void *); + LOCALE void *EnvGetNextDeffunction(void *,void *); + LOCALE int EnvIsDeffunctionDeletable(void *,void *); + LOCALE void EnvSetDeffunctionPPForm(void *,void *,const char *); + LOCALE intBool EnvUndeffunction(void *,void *); + LOCALE void GetDeffunctionListFunction(void *,DATA_OBJECT *); + LOCALE void *GetDeffunctionModuleCommand(void *); + LOCALE DEFFUNCTION *LookupDeffunctionByMdlOrScope(void *,const char *); + LOCALE DEFFUNCTION *LookupDeffunctionInScope(void *,const char *); +#if (! BLOAD_ONLY) && (! RUN_TIME) + LOCALE void RemoveDeffunction(void *,void *); #endif - -LOCALE void SetupDeffunctions(void *); -LOCALE void *EnvFindDeffunction(void *,char *); -LOCALE DEFFUNCTION *LookupDeffunctionByMdlOrScope(void *,char *); -LOCALE DEFFUNCTION *LookupDeffunctionInScope(void *,char *); -LOCALE intBool EnvUndeffunction(void *,void *); -LOCALE void *EnvGetNextDeffunction(void *,void *); -LOCALE int EnvIsDeffunctionDeletable(void *,void *); -LOCALE void UndeffunctionCommand(void *); -LOCALE void *GetDeffunctionModuleCommand(void *); -LOCALE void DeffunctionGetBind(DATA_OBJECT *); -LOCALE void DFRtnUnknown(DATA_OBJECT *); -LOCALE void DFWildargs(DATA_OBJECT *); -LOCALE int CheckDeffunctionCall(void *,void *,int); + LOCALE void SetupDeffunctions(void *); + LOCALE void UndeffunctionCommand(void *); #if DEBUGGING_FUNCTIONS -LOCALE void PPDeffunctionCommand(void *); -LOCALE void ListDeffunctionsCommand(void *); -LOCALE void EnvListDeffunctions(void *,char *,struct defmodule *); -LOCALE void EnvSetDeffunctionWatch(void *,unsigned,void *); -LOCALE unsigned EnvGetDeffunctionWatch(void *,void *); -#endif -#if (! BLOAD_ONLY) && (! RUN_TIME) -LOCALE void RemoveDeffunction(void *,void *); + LOCALE unsigned EnvGetDeffunctionWatch(void *,void *); + LOCALE void EnvListDeffunctions(void *,const char *,struct defmodule *); + LOCALE void EnvSetDeffunctionWatch(void *,unsigned,void *); + LOCALE void ListDeffunctionsCommand(void *); + LOCALE void PPDeffunctionCommand(void *); #endif -LOCALE void GetDeffunctionListFunction(void *,DATA_OBJECT *); -globle void EnvGetDeffunctionList(void *,DATA_OBJECT *,struct defmodule *); +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE const char *DeffunctionModule(void *); + LOCALE void *FindDeffunction(const char *); + LOCALE void GetDeffunctionList(DATA_OBJECT *,struct defmodule *); + LOCALE const char *GetDeffunctionName(void *); + LOCALE const char *GetDeffunctionPPForm(void *); + LOCALE void *GetNextDeffunction(void *); + LOCALE intBool IsDeffunctionDeletable(void *); + LOCALE intBool Undeffunction(void *); +#if DEBUGGING_FUNCTIONS + LOCALE unsigned GetDeffunctionWatch(void *); + LOCALE void ListDeffunctions(const char *,struct defmodule *); + LOCALE void SetDeffunctionWatch(unsigned,void *); #endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_dffnxfun */ + diff --git a/src/dffnxpsr.c b/src/dffnxpsr.c index 19b3728..8927ce4 100644 --- a/src/dffnxpsr.c +++ b/src/dffnxpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Deffunction Parsing Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -26,6 +26,23 @@ /* Added pragmas to prevent unused variable */ /* warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* ENVIRONMENT_API_ONLY no longer supported. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ /* ========================================= @@ -72,7 +89,7 @@ ========================================= ***************************************** */ -static intBool ValidDeffunctionName(void *,char *); +static intBool ValidDeffunctionName(void *,const char *); static DEFFUNCTION *AddDeffunction(void *,SYMBOL_HN *,EXPRESSION *,int,int,int,int); /* ========================================= @@ -94,7 +111,7 @@ static DEFFUNCTION *AddDeffunction(void *,SYMBOL_HN *,EXPRESSION *,int,int,int,i ***************************************************************************/ globle intBool ParseDeffunction( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *deffunctionName; EXPRESSION *actions; @@ -122,8 +139,8 @@ globle intBool ParseDeffunction( Parse the name and comment fields of the deffunction. ===================================================== */ deffunctionName = GetConstructNameAndComment(theEnv,readSource,&DeffunctionData(theEnv)->DFInputToken,"deffunction", - EnvFindDeffunction,NULL, - "!",TRUE,TRUE,TRUE); + EnvFindDeffunctionInModule,NULL, + "!",TRUE,TRUE,TRUE,FALSE); if (deffunctionName == NULL) return(TRUE); @@ -144,7 +161,7 @@ globle intBool ParseDeffunction( if (ConstructData(theEnv)->CheckSyntaxMode) { - dptr = (DEFFUNCTION *) EnvFindDeffunction(theEnv,ValueToString(deffunctionName)); + dptr = (DEFFUNCTION *) EnvFindDeffunctionInModule(theEnv,ValueToString(deffunctionName)); if (dptr == NULL) { dptr = AddDeffunction(theEnv,deffunctionName,NULL,min,max,0,TRUE); } else @@ -184,7 +201,7 @@ globle intBool ParseDeffunction( (actions != NULL)) { SyntaxErrorMessage(theEnv,"deffunction"); - + ReturnExpression(theEnv,parameterList); ReturnPackedExpression(theEnv,actions); @@ -282,7 +299,7 @@ globle intBool ParseDeffunction( ************************************************************/ static intBool ValidDeffunctionName( void *theEnv, - char *theDeffunctionName) + const char *theDeffunctionName) { struct constructHeader *theDeffunction; #if DEFGENERIC_CONSTRUCT @@ -343,7 +360,7 @@ static intBool ValidDeffunctionName( } #endif - theDeffunction = (struct constructHeader *) EnvFindDeffunction(theEnv,theDeffunctionName); + theDeffunction = (struct constructHeader *) EnvFindDeffunctionInModule(theEnv,theDeffunctionName); if (theDeffunction != NULL) { /* =========================================== @@ -381,9 +398,6 @@ static intBool ValidDeffunctionName( SIDE EFFECTS : Deffunction structures allocated NOTES : Assumes deffunction is not executing ****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static DEFFUNCTION *AddDeffunction( void *theEnv, SYMBOL_HN *name, @@ -398,7 +412,7 @@ static DEFFUNCTION *AddDeffunction( #if DEBUGGING_FUNCTIONS unsigned DFHadWatch = FALSE; #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(headerp) #endif #endif @@ -409,7 +423,7 @@ static DEFFUNCTION *AddDeffunction( /* use the existing structure and remove the pretty print form */ /* and interpretive code. */ /*===============================================================*/ - dfuncPtr = (DEFFUNCTION *) EnvFindDeffunction(theEnv,ValueToString(name)); + dfuncPtr = (DEFFUNCTION *) EnvFindDeffunctionInModule(theEnv,ValueToString(name)); if (dfuncPtr == NULL) { dfuncPtr = get_struct(theEnv,deffunctionStruct); @@ -435,7 +449,7 @@ static DEFFUNCTION *AddDeffunction( dfuncPtr->busy = oldbusy; ReturnPackedExpression(theEnv,dfuncPtr->code); dfuncPtr->code = NULL; - SetDeffunctionPPForm((void *) dfuncPtr,NULL); + EnvSetDeffunctionPPForm(theEnv,(void *) dfuncPtr,NULL); /* ======================================= Remove the deffunction from the list so @@ -470,7 +484,7 @@ static DEFFUNCTION *AddDeffunction( #if DEBUGGING_FUNCTIONS EnvSetDeffunctionWatch(theEnv,DFHadWatch ? TRUE : DeffunctionData(theEnv)->WatchDeffunctions,(void *) dfuncPtr); if ((EnvGetConserveMemory(theEnv) == FALSE) && (headerp == FALSE)) - SetDeffunctionPPForm((void *) dfuncPtr,CopyPPBuffer(theEnv)); + EnvSetDeffunctionPPForm(theEnv,(void *) dfuncPtr,CopyPPBuffer(theEnv)); #endif return(dfuncPtr); } diff --git a/src/dffnxpsr.h b/src/dffnxpsr.h index 0a223bb..23e98c1 100644 --- a/src/dffnxpsr.h +++ b/src/dffnxpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -18,6 +18,15 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_dffnxpsr @@ -35,14 +44,11 @@ #define LOCALE extern #endif -LOCALE intBool ParseDeffunction(void *,char *); + LOCALE intBool ParseDeffunction(void *,const char *); -#ifndef _DFFNXPSR_SOURCE_ -#endif +#endif /* DEFFUNCTION_CONSTRUCT && (! BLOAD_ONLY) && (! RUN_TIME) */ -#endif - -#endif +#endif /* _H_dffnxpsr */ diff --git a/src/dfinsbin.c b/src/dfinsbin.c index 484e314..1fd80b2 100644 --- a/src/dfinsbin.c +++ b/src/dfinsbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Binary Load/Save Functions for Definstances */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ /* ========================================= @@ -113,7 +119,7 @@ globle void SetupDefinstancesBload( ClearDefinstancesBload); #endif } - + /*************************************************************/ /* DeallocateDefinstancesBinaryData: Deallocates environment */ /* data for the definstances binary functionality. */ @@ -121,14 +127,14 @@ globle void SetupDefinstancesBload( static void DeallocateDefinstancesBinaryData( void *theEnv) { - unsigned long space; + size_t space; #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) space = DefinstancesBinaryData(theEnv)->DefinstancesCount * sizeof(struct definstances); - if (space != 0) genlongfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->DefinstancesArray,space); + if (space != 0) genfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->DefinstancesArray,space); space = DefinstancesBinaryData(theEnv)->ModuleCount * sizeof(struct definstancesModule); - if (space != 0) genlongfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->ModuleArray,space); #endif } @@ -178,7 +184,7 @@ static void BsaveDefinstancesFind( SaveBloadCount(theEnv,DefinstancesBinaryData(theEnv)->DefinstancesCount); DefinstancesBinaryData(theEnv)->DefinstancesCount = 0L; - DefinstancesBinaryData(theEnv)->ModuleCount = + DefinstancesBinaryData(theEnv)->ModuleCount = DoForAllConstructs(theEnv,MarkDefinstancesItems,DefinstancesData(theEnv)->DefinstancesModuleIndex, FALSE,NULL); } @@ -194,15 +200,12 @@ static void BsaveDefinstancesFind( SIDE EFFECTS : Needed items marked NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkDefinstancesItems( void *theEnv, struct constructHeader *theDefinstances, void *userBuffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(userBuffer) #endif @@ -260,12 +263,12 @@ static void BsaveStorageDefinstances( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; space = sizeof(unsigned long) * 2; - GenWrite((void *) &space,(unsigned long) sizeof(unsigned long),fp); - GenWrite((void *) &DefinstancesBinaryData(theEnv)->ModuleCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefinstancesBinaryData(theEnv)->DefinstancesCount,(unsigned long) sizeof(long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); + GenWrite((void *) &DefinstancesBinaryData(theEnv)->ModuleCount,sizeof(unsigned long),fp); + GenWrite((void *) &DefinstancesBinaryData(theEnv)->DefinstancesCount,sizeof(unsigned long),fp); } /************************************************************************************* @@ -282,14 +285,14 @@ static void BsaveDefinstancesDriver( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; struct defmodule *theModule; DEFINSTANCES_MODULE *theModuleItem; BSAVE_DEFINSTANCES_MODULE dummy_mitem; - space = (unsigned long) ((sizeof(BSAVE_DEFINSTANCES_MODULE) * DefinstancesBinaryData(theEnv)->ModuleCount) + - (sizeof(BSAVE_DEFINSTANCES) * DefinstancesBinaryData(theEnv)->DefinstancesCount)); - GenWrite((void *) &space,(unsigned long) sizeof(unsigned long),fp); + space = ((sizeof(BSAVE_DEFINSTANCES_MODULE) * DefinstancesBinaryData(theEnv)->ModuleCount) + + (sizeof(BSAVE_DEFINSTANCES) * DefinstancesBinaryData(theEnv)->DefinstancesCount)); + GenWrite((void *) &space,sizeof(size_t),fp); /* ================================= Write out each definstances module @@ -301,7 +304,7 @@ static void BsaveDefinstancesDriver( theModuleItem = (DEFINSTANCES_MODULE *) GetModuleItem(theEnv,theModule,FindModuleItem(theEnv,"definstances")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&dummy_mitem.header,&theModuleItem->header); - GenWrite((void *) &dummy_mitem,(unsigned long) sizeof(BSAVE_DEFINSTANCES_MODULE),fp); + GenWrite((void *) &dummy_mitem,sizeof(BSAVE_DEFINSTANCES_MODULE),fp); theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule); } @@ -358,13 +361,13 @@ static void BsaveDefinstances( static void BloadStorageDefinstances( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) return; - GenReadBinary(theEnv,(void *) &DefinstancesBinaryData(theEnv)->ModuleCount,(unsigned long) sizeof(unsigned long)); - GenReadBinary(theEnv,(void *) &DefinstancesBinaryData(theEnv)->DefinstancesCount,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &DefinstancesBinaryData(theEnv)->ModuleCount,sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &DefinstancesBinaryData(theEnv)->DefinstancesCount,sizeof(unsigned long)); if (DefinstancesBinaryData(theEnv)->ModuleCount == 0L) { DefinstancesBinaryData(theEnv)->ModuleArray = NULL; @@ -372,8 +375,8 @@ static void BloadStorageDefinstances( return; } - space = (unsigned long) (DefinstancesBinaryData(theEnv)->ModuleCount * sizeof(DEFINSTANCES_MODULE)); - DefinstancesBinaryData(theEnv)->ModuleArray = (DEFINSTANCES_MODULE *) genlongalloc(theEnv,space); + space = (DefinstancesBinaryData(theEnv)->ModuleCount * sizeof(DEFINSTANCES_MODULE)); + DefinstancesBinaryData(theEnv)->ModuleArray = (DEFINSTANCES_MODULE *) genalloc(theEnv,space); if (DefinstancesBinaryData(theEnv)->DefinstancesCount == 0L) { @@ -381,8 +384,8 @@ static void BloadStorageDefinstances( return; } - space = (unsigned long) (DefinstancesBinaryData(theEnv)->DefinstancesCount * sizeof(DEFINSTANCES)); - DefinstancesBinaryData(theEnv)->DefinstancesArray = (DEFINSTANCES *) genlongalloc(theEnv,space); + space = (DefinstancesBinaryData(theEnv)->DefinstancesCount * sizeof(DEFINSTANCES)); + DefinstancesBinaryData(theEnv)->DefinstancesArray = (DEFINSTANCES *) genalloc(theEnv,space); } /********************************************************************* @@ -399,9 +402,9 @@ static void BloadStorageDefinstances( static void BloadDefinstances( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); BloadandRefresh(theEnv,DefinstancesBinaryData(theEnv)->ModuleCount,sizeof(BSAVE_DEFINSTANCES_MODULE),UpdateDefinstancesModule); BloadandRefresh(theEnv,DefinstancesBinaryData(theEnv)->DefinstancesCount,sizeof(BSAVE_DEFINSTANCES),UpdateDefinstances); } @@ -474,21 +477,21 @@ static void ClearDefinstancesBload( void *theEnv) { register long i; - unsigned long space; + size_t space; - space = (unsigned long) (sizeof(DEFINSTANCES_MODULE) * DefinstancesBinaryData(theEnv)->ModuleCount); + space = (sizeof(DEFINSTANCES_MODULE) * DefinstancesBinaryData(theEnv)->ModuleCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->ModuleArray,space); + genfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->ModuleArray,space); DefinstancesBinaryData(theEnv)->ModuleArray = NULL; DefinstancesBinaryData(theEnv)->ModuleCount = 0L; for (i = 0L ; i < DefinstancesBinaryData(theEnv)->DefinstancesCount ; i++) UnmarkConstructHeader(theEnv,&DefinstancesBinaryData(theEnv)->DefinstancesArray[i].header); - space = (unsigned long) (sizeof(DEFINSTANCES) * DefinstancesBinaryData(theEnv)->DefinstancesCount); + space = (sizeof(DEFINSTANCES) * DefinstancesBinaryData(theEnv)->DefinstancesCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->DefinstancesArray,space); + genfree(theEnv,(void *) DefinstancesBinaryData(theEnv)->DefinstancesArray,space); DefinstancesBinaryData(theEnv)->DefinstancesArray = NULL; DefinstancesBinaryData(theEnv)->DefinstancesCount = 0L; } diff --git a/src/dfinsbin.h b/src/dfinsbin.h index 7ea1dc2..4376956 100644 --- a/src/dfinsbin.h +++ b/src/dfinsbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,20 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* Revision History: */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_dfinsbin @@ -30,13 +38,13 @@ #define DFINSBIN_DATA 25 struct definstancesBinaryData - { + { DEFINSTANCES *DefinstancesArray; long DefinstancesCount; long ModuleCount; DEFINSTANCES_MODULE *ModuleArray; }; - + #define DefinstancesBinaryData(theEnv) ((struct definstancesBinaryData *) GetEnvironmentData(theEnv,DFINSBIN_DATA)) #ifdef LOCALE @@ -49,15 +57,12 @@ struct definstancesBinaryData #define LOCALE extern #endif -LOCALE void SetupDefinstancesBload(void *); -LOCALE void *BloadDefinstancesModuleRef(void *,int); + LOCALE void SetupDefinstancesBload(void *); + LOCALE void *BloadDefinstancesModuleRef(void *,int); -#ifndef _DFINSBIN_SOURCE_ -#endif - -#endif +#endif /* DEFINSTANCES_CONSTRUCT && (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) */ -#endif +#endif /* _H_dfinsbin */ diff --git a/src/dfinscmp.c b/src/dfinscmp.c index 3b70beb..9b6d2c7 100644 --- a/src/dfinscmp.c +++ b/src/dfinscmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Definstances Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -41,7 +47,7 @@ ***************************************** */ static void ReadyDefinstancesForCode(void *); -static int DefinstancesToCode(void *,char *,int,FILE *,int,int); +static int DefinstancesToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void CloseDefinstancesFiles(void *,FILE *,FILE *,int); static void DefinstancesModuleToCode(void *,FILE *,struct defmodule *,int,int); static void SingleDefinstancesToCode(void *,FILE *,DEFINSTANCES *,int,int,int); @@ -134,7 +140,9 @@ static void ReadyDefinstancesForCode( *******************************************************/ static int DefinstancesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -162,7 +170,7 @@ static int DefinstancesToCode( { EnvSetCurrentModule(theEnv,(void *) theModule); - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "DEFINSTANCES_MODULE",ModulePrefix(DefinstancesData(theEnv)->DefinstancesCodeItem), FALSE,NULL); @@ -181,7 +189,7 @@ static int DefinstancesToCode( while (theDefinstances != NULL) { - definstancesFile = OpenFileIfNeeded(theEnv,definstancesFile,fileName,fileID,imageID,&fileCount, + definstancesFile = OpenFileIfNeeded(theEnv,definstancesFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, definstancesArrayVersion,headerFP, "DEFINSTANCES",ConstructPrefix(DefinstancesData(theEnv)->DefinstancesCodeItem), FALSE,NULL); diff --git a/src/dfinscmp.h b/src/dfinscmp.h index c19f8e2..4e1ee7f 100644 --- a/src/dfinscmp.h +++ b/src/dfinscmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,15 @@ /* Purpose: Definstances Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ /*************************************************************/ #ifndef _H_dfinscmp @@ -38,11 +41,11 @@ #define LOCALE extern #endif -LOCALE void SetupDefinstancesCompiler(void *); -LOCALE void DefinstancesCModuleReference(void *,FILE *,int,int,int); + LOCALE void SetupDefinstancesCompiler(void *); + LOCALE void DefinstancesCModuleReference(void *,FILE *,int,int,int); -#endif +#endif /* DEFINSTANCES_CONSTRUCT && CONSTRUCT_COMPILER && (! RUN_TIME) */ -#endif +#endif /* _H_dfinscmp */ diff --git a/src/drive.c b/src/drive.c index 493f23e..808e963 100644 --- a/src/drive.c +++ b/src/drive.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DRIVE MODULE */ /*******************************************************/ @@ -17,6 +17,7 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed INCREMENTAL_RESET and */ @@ -27,6 +28,13 @@ /* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CE. */ +/* */ /*************************************************************/ #define _DRIVE_SOURCE_ @@ -57,10 +65,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void PPDrive(void *,struct partialMatch *,struct partialMatch *,struct joinNode *); - static void PNRDrive(void *,struct joinNode *,struct partialMatch *, - struct partialMatch *); - static void EmptyDrive(void *,struct joinNode *,struct partialMatch *); + static void EmptyDrive(void *,struct joinNode *,struct partialMatch *,int); static void JoinNetErrorMessage(void *,struct joinNode *); /************************************************/ @@ -70,13 +75,8 @@ globle void NetworkAssert( void *theEnv, struct partialMatch *binds, - struct joinNode *join, - int enterDirection) + struct joinNode *join) { - struct partialMatch *lhsBinds = NULL, *rhsBinds = NULL; - struct partialMatch *comparePMs = NULL, *newBinds; - int exprResult; - /*=========================================================*/ /* If an incremental reset is being performed and the join */ /* is not part of the network to be reset, then return. */ @@ -86,65 +86,81 @@ globle void NetworkAssert( if (EngineData(theEnv)->IncrementalResetInProgress && (join->initialize == FALSE)) return; #endif - /*=========================================================*/ - /* If the associated LHS pattern is a not CE or the join */ - /* is a nand join, then we need an additional field in the */ - /* partial match to keep track of the pseudo fact if one */ - /* is created. The partial match is automatically stored */ - /* in the beta memory and the counterf slot is used to */ - /* determine if it is an actual partial match. If counterf */ - /* is TRUE, there are one or more fact or instances */ - /* keeping the not or nand join from being satisfied. */ - /*=========================================================*/ - - if ((enterDirection == LHS) && - ((join->patternIsNegated) || (join->joinFromTheRight))) - { - newBinds = AddSingleMatch(theEnv,binds,NULL, - (join->ruleToActivate == NULL) ? 0 : 1, - (int) join->logicalJoin); - newBinds->notOriginf = TRUE; - newBinds->counterf = TRUE; - binds = newBinds; - binds->next = join->beta; - join->beta = binds; - } - /*==================================================*/ /* Use a special routine if this is the first join. */ /*==================================================*/ if (join->firstJoin) { - EmptyDrive(theEnv,join,binds); + EmptyDrive(theEnv,join,binds,NETWORK_ASSERT); return; } - /*==================================================*/ - /* Initialize some variables used to indicate which */ - /* side is being compared to the new partial match. */ - /*==================================================*/ + /*================================*/ + /* Enter the join from the right. */ + /*================================*/ - if (enterDirection == LHS) - { - if (join->joinFromTheRight) - { comparePMs = ((struct joinNode *) join->rightSideEntryStructure)->beta;} - else - { comparePMs = ((struct patternNodeHeader *) join->rightSideEntryStructure)->alphaMemory; } - lhsBinds = binds; - } - else if (enterDirection == RHS) + NetworkAssertRight(theEnv,binds,join,NETWORK_ASSERT); + + return; + } + +/*****************************************************/ +/* NetworkAssertRight: Primary routine for filtering */ +/* a partial match through the join network from */ +/* the RHS of a join. */ +/*****************************************************/ +globle void NetworkAssertRight( + void *theEnv, + struct partialMatch *rhsBinds, + struct joinNode *join, + int operation) + { + struct partialMatch *lhsBinds, *nextBind; + int exprResult, restore = FALSE; + struct partialMatch *oldLHSBinds = NULL; + struct partialMatch *oldRHSBinds = NULL; + struct joinNode *oldJoin = NULL; + + /*=========================================================*/ + /* If an incremental reset is being performed and the join */ + /* is not part of the network to be reset, then return. */ + /*=========================================================*/ + +#if (! BLOAD_ONLY) && (! RUN_TIME) + if (EngineData(theEnv)->IncrementalResetInProgress && (join->initialize == FALSE)) return; +#endif + + if (join->firstJoin) { - if (join->patternIsNegated || join->joinFromTheRight) - { comparePMs = join->beta; } - else - { comparePMs = join->lastLevel->beta; } - rhsBinds = binds; + EmptyDrive(theEnv,join,rhsBinds,operation); + return; } - else + + /*=====================================================*/ + /* The partial matches entering from the LHS of a join */ + /* are stored in the left beta memory of the join. */ + /*=====================================================*/ + + lhsBinds = GetLeftBetaMemory(join,rhsBinds->hashValue); + +#if DEVELOPER + if (lhsBinds != NULL) + { EngineData(theEnv)->rightToLeftLoops++; } +#endif + + /*====================================*/ + /* Set up the evaluation environment. */ + /*====================================*/ + + if (lhsBinds != NULL) { - SystemError(theEnv,"DRIVE",1); - EnvExitRouter(theEnv,EXIT_FAILURE); + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalRHSBinds = rhsBinds; + EngineData(theEnv)->GlobalJoin = join; + restore = TRUE; } /*===================================================*/ @@ -154,96 +170,271 @@ globle void NetworkAssert( /* the appropriate action for the logic of the join. */ /*===================================================*/ - while (comparePMs != NULL) + while (lhsBinds != NULL) { + nextBind = lhsBinds->nextInMemory; + join->memoryCompares++; + /*===========================================================*/ /* Initialize some variables pointing to the partial matches */ - /* in the LHS and RHS of the join. In addition, check for */ - /* certain conditions under which the partial match can be */ - /* skipped since it's not a "real" partial match. */ + /* in the LHS and RHS of the join. */ /*===========================================================*/ - if (enterDirection == RHS) + if (lhsBinds->hashValue != rhsBinds->hashValue) { - lhsBinds = comparePMs; - - /*=====================================================*/ - /* The partial matches entering from the LHS of a join */ - /* are stored in the beta memory of the previous join */ - /* (unless the current join is a join from the right */ - /* or is attached to a not CE). If the previous join */ - /* is a join from the right or associated with a not */ - /* CE, then some of its partial matches in its beta */ - /* memory will not be "real" partial matches. That is, */ - /* there may be a partial match in the alpha memory */ - /* that prevents the partial match from satisfying the */ - /* join's conditions. If this is the case, then the */ - /* counterf flag in the partial match will be set to */ - /* TRUE and in this case, we move on to the next */ - /* partial match to be checked. */ - /*=====================================================*/ - - if (lhsBinds->counterf && - (join->patternIsNegated == FALSE) && - (join->joinFromTheRight == FALSE)) +#if DEVELOPER + if (join->leftMemory->size == 1) + { EngineData(theEnv)->betaHashListSkips++; } + else + { EngineData(theEnv)->betaHashHTSkips++; } + + if (lhsBinds->marker != NULL) + { EngineData(theEnv)->unneededMarkerCompare++; } +#endif + lhsBinds = nextBind; + continue; + } + + /*===============================================================*/ + /* If there already is an associated RHS partial match stored in */ + /* the LHS partial match from the beta memory of this join, then */ + /* the exists/nand CE has already been satisfied and we can move */ + /* on to the next partial match found in the beta memory. */ + /*===============================================================*/ + + if (lhsBinds->marker != NULL) + { +#if DEVELOPER + EngineData(theEnv)->unneededMarkerCompare++; +#endif + lhsBinds = nextBind; + continue; + } + + /*===================================================*/ + /* If the join has no expression associated with it, */ + /* then the new partial match derived from the LHS */ + /* and RHS partial matches is valid. */ + /*===================================================*/ + + if (join->networkTest == NULL) + { exprResult = TRUE; } + + /*=========================================================*/ + /* If the join has an expression associated with it, then */ + /* evaluate the expression to determine if the new partial */ + /* match derived from the LHS and RHS partial matches is */ + /* valid (i.e. variable bindings are consistent and */ + /* predicate expressions evaluate to TRUE). */ + /*=========================================================*/ + + else + { +#if DEVELOPER + EngineData(theEnv)->rightToLeftComparisons++; +#endif + EngineData(theEnv)->GlobalLHSBinds = lhsBinds; + exprResult = EvaluateJoinExpression(theEnv,join->networkTest,join); + if (EvaluationData(theEnv)->EvaluationError) { - comparePMs = comparePMs->next; - continue; + if (join->patternIsNegated) exprResult = TRUE; + SetEvaluationError(theEnv,FALSE); } - /*==================================================*/ - /* If the join is associated with a not CE or has a */ - /* join from the right, then the LHS partial match */ - /* currently being checked may already have a */ - /* partial match from the alpha memory preventing */ - /* it from being satisfied. If this is the case, */ - /* then move on to the next partial match in the */ - /* beta memory of the join. */ - /*==================================================*/ - - if ((join->patternIsNegated || join->joinFromTheRight) && - (lhsBinds->counterf)) - { - comparePMs = comparePMs->next; - continue; - } +#if DEVELOPER + if (exprResult) + { EngineData(theEnv)->rightToLeftSucceeds++; } +#endif } - else - { rhsBinds = comparePMs; } - - /*========================================================*/ - /* If the join has no expression associated with it, then */ - /* the new partial match derived from the LHS and RHS */ - /* partial matches is valid. In the event that the join */ - /* is a join from the right, it must also be checked that */ - /* the RHS partial match is the same partial match that */ - /* the LHS partial match was generated from. Each LHS */ - /* partial match in a join from the right corresponds */ - /* uniquely to a partial match from the RHS of the join. */ - /* To determine whether the LHS partial match is the one */ - /* associated with the RHS partial match, we compare the */ - /* the entity addresses found in the partial matches to */ - /* make sure they're equal. */ - /*========================================================*/ - if (join->networkTest == NULL) + if ((join->secondaryNetworkTest != NULL) && exprResult) { - exprResult = TRUE; - if (join->joinFromTheRight) + EngineData(theEnv)->GlobalLHSBinds = lhsBinds; + exprResult = EvaluateJoinExpression(theEnv,join->secondaryNetworkTest,join); + if (EvaluationData(theEnv)->EvaluationError) + { SetEvaluationError(theEnv,FALSE); } + } + + /*====================================================*/ + /* If the join expression evaluated to TRUE (i.e. */ + /* there were no conflicts between variable bindings, */ + /* all tests were satisfied, etc.), then perform the */ + /* appropriate action given the logic of this join. */ + /*====================================================*/ + + if (exprResult != FALSE) + { + if (join->patternIsExists) + { + AddBlockedLink(lhsBinds,rhsBinds); + PPDrive(theEnv,lhsBinds,NULL,join,operation); + } + else if (join->patternIsNegated || join->joinFromTheRight) { - int i; - - for (i = 0; i < (int) (lhsBinds->bcount - 1); i++) - { - if (lhsBinds->binds[i].gm.theMatch != rhsBinds->binds[i].gm.theMatch) - { - exprResult = FALSE; - break; - } - } + AddBlockedLink(lhsBinds,rhsBinds); + if (lhsBinds->children != NULL) + { PosEntryRetractBeta(theEnv,lhsBinds,lhsBinds->children,operation); } + /* + if (lhsBinds->dependents != NULL) + { RemoveLogicalSupport(theEnv,lhsBinds); } + */ } + else + { PPDrive(theEnv,lhsBinds,rhsBinds,join,operation); } + } + + /*====================================*/ + /* Move on to the next partial match. */ + /*====================================*/ + + lhsBinds = nextBind; + } + + /*=========================================*/ + /* Restore the old evaluation environment. */ + /*=========================================*/ + + if (restore) + { + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + } + + return; + } + +/****************************************************/ +/* NetworkAssertLeft: Primary routine for filtering */ +/* a partial match through the join network when */ +/* entering through the left side of a join. */ +/****************************************************/ +globle void NetworkAssertLeft( + void *theEnv, + struct partialMatch *lhsBinds, + struct joinNode *join, + int operation) + { + struct partialMatch *rhsBinds; + int exprResult, restore = FALSE; + unsigned long entryHashValue; + struct partialMatch *oldLHSBinds = NULL; + struct partialMatch *oldRHSBinds = NULL; + struct joinNode *oldJoin = NULL; + + if ((operation == NETWORK_RETRACT) && PartialMatchWillBeDeleted(theEnv,lhsBinds)) + { return; } + + /*=========================================================*/ + /* If an incremental reset is being performed and the join */ + /* is not part of the network to be reset, then return. */ + /*=========================================================*/ + +#if (! BLOAD_ONLY) && (! RUN_TIME) + if (EngineData(theEnv)->IncrementalResetInProgress && (join->initialize == FALSE)) return; +#endif + + /*===================================*/ + /* The only action for the last join */ + /* of a rule is to activate it. */ + /*===================================*/ + + if (join->ruleToActivate != NULL) + { + AddActivation(theEnv,join->ruleToActivate,lhsBinds); + return; + } + + /*=====================================*/ + /* Handle a join handling a test CE at */ + /* the beginning of a not/and group. */ + /*=====================================*/ + + if (join->rightSideEntryStructure == NULL) + { + exprResult = TRUE; + + if (join->networkTest != NULL) + { + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + + EngineData(theEnv)->GlobalLHSBinds = lhsBinds; + EngineData(theEnv)->GlobalRHSBinds = NULL; + EngineData(theEnv)->GlobalJoin = join; + + exprResult = EvaluateJoinExpression(theEnv,join->networkTest,join); + if (EvaluationData(theEnv)->EvaluationError) + { SetEvaluationError(theEnv,FALSE); } + + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + } + + if (exprResult) + { PPDrive(theEnv,lhsBinds,NULL,join,operation); } + + return; + } + + /*==================================================*/ + /* Initialize some variables used to indicate which */ + /* side is being compared to the new partial match. */ + /*==================================================*/ + + entryHashValue = lhsBinds->hashValue; + if (join->joinFromTheRight) + { rhsBinds = GetRightBetaMemory(join,entryHashValue); } + else + { rhsBinds = GetAlphaMemory(theEnv,(struct patternNodeHeader *) join->rightSideEntryStructure,entryHashValue); } + +#if DEVELOPER + if (rhsBinds != NULL) + { EngineData(theEnv)->leftToRightLoops++; } +#endif + + /*====================================*/ + /* Set up the evaluation environment. */ + /*====================================*/ + + if ((rhsBinds != NULL) || (join->secondaryNetworkTest != NULL)) + { + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = lhsBinds; + EngineData(theEnv)->GlobalJoin = join; + restore = TRUE; + } + + /*===================================================*/ + /* Compare each set of binds on the opposite side of */ + /* the join with the set of binds that entered this */ + /* join. If the binds don't mismatch, then perform */ + /* the appropriate action for the logic of the join. */ + /*===================================================*/ + + while (rhsBinds != NULL) + { + if ((operation == NETWORK_RETRACT) && PartialMatchWillBeDeleted(theEnv,rhsBinds)) + { + rhsBinds = rhsBinds->nextInMemory; + continue; } + join->memoryCompares++; + + /*===================================================*/ + /* If the join has no expression associated with it, */ + /* then the new partial match derived from the LHS */ + /* and RHS partial matches is valid. */ + /*===================================================*/ + + if (join->networkTest == NULL) + { exprResult = TRUE; } + /*=========================================================*/ /* If the join has an expression associated with it, then */ /* evaluate the expression to determine if the new partial */ @@ -254,12 +445,32 @@ globle void NetworkAssert( else { - exprResult = EvaluateJoinExpression(theEnv,join->networkTest,lhsBinds,rhsBinds,join); +#if DEVELOPER + EngineData(theEnv)->leftToRightComparisons++; +#endif + EngineData(theEnv)->GlobalRHSBinds = rhsBinds; + + exprResult = EvaluateJoinExpression(theEnv,join->networkTest,join); if (EvaluationData(theEnv)->EvaluationError) { if (join->patternIsNegated) exprResult = TRUE; SetEvaluationError(theEnv,FALSE); } + +#if DEVELOPER + if (exprResult) + { EngineData(theEnv)->leftToRightSucceeds++; } +#endif + } + + // Bug Fix - Need to evaluate secondary network test for exists CE 0881 + + if ((join->secondaryNetworkTest != NULL) && exprResult && join->patternIsExists) + { + EngineData(theEnv)->GlobalRHSBinds = rhsBinds; + exprResult = EvaluateJoinExpression(theEnv,join->secondaryNetworkTest,join); + if (EvaluationData(theEnv)->EvaluationError) + { SetEvaluationError(theEnv,FALSE); } } /*====================================================*/ @@ -278,18 +489,24 @@ globle void NetworkAssert( /*==============================================*/ if ((join->patternIsNegated == FALSE) && + (join->patternIsExists == FALSE) && (join->joinFromTheRight == FALSE)) - { PPDrive(theEnv,lhsBinds,rhsBinds,join); } + { PPDrive(theEnv,lhsBinds,rhsBinds,join,operation); } - /*=====================================================*/ - /* Use the PNRDrive routine when the new partial match */ - /* enters from the RHS of the join and the join either */ - /* is associated with a not CE or has a join from the */ - /* right. */ - /*=====================================================*/ + /*==================================================*/ + /* At most, one partial match will be generated for */ + /* a match from the right memory of an exists CE. */ + /*==================================================*/ - else if (enterDirection == RHS) - { PNRDrive(theEnv,join,comparePMs,rhsBinds); } + else if (join->patternIsExists) + { + AddBlockedLink(lhsBinds,rhsBinds); + PPDrive(theEnv,lhsBinds,NULL,join,operation); + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + return; + } /*===========================================================*/ /* If the new partial match entered from the LHS of the join */ @@ -302,11 +519,10 @@ globle void NetworkAssert( /* the LHS from being satisfied. */ /*===========================================================*/ - else if (enterDirection == LHS) + else { - binds->binds[binds->bcount - 1].gm.theValue = (void *) rhsBinds; - comparePMs = NULL; - continue; + AddBlockedLink(lhsBinds,rhsBinds); + break; } } @@ -314,7 +530,7 @@ globle void NetworkAssert( /* Move on to the next partial match. */ /*====================================*/ - comparePMs = comparePMs->next; + rhsBinds = rhsBinds->nextInMemory; } /*==================================================================*/ @@ -329,9 +545,34 @@ globle void NetworkAssert( /*==================================================================*/ if ((join->patternIsNegated || join->joinFromTheRight) && - (enterDirection == LHS) && - (binds->binds[binds->bcount - 1].gm.theValue == NULL)) - { PNLDrive(theEnv,join,binds); } + (! join->patternIsExists) && + (lhsBinds->marker == NULL)) + { + if (join->secondaryNetworkTest != NULL) + { + EngineData(theEnv)->GlobalRHSBinds = NULL; + + exprResult = EvaluateJoinExpression(theEnv,join->secondaryNetworkTest,join); + if (EvaluationData(theEnv)->EvaluationError) + { SetEvaluationError(theEnv,FALSE); } + + if (exprResult) + { PPDrive(theEnv,lhsBinds,NULL,join,operation); } + } + else + { PPDrive(theEnv,lhsBinds,NULL,join,operation); } + } + + /*=========================================*/ + /* Restore the old evaluation environment. */ + /*=========================================*/ + + if (restore) + { + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + } return; } @@ -344,15 +585,10 @@ globle void NetworkAssert( globle intBool EvaluateJoinExpression( void *theEnv, struct expr *joinExpr, - struct partialMatch *lbinds, - struct partialMatch *rbinds, struct joinNode *joinPtr) { DATA_OBJECT theResult; int andLogic, result = TRUE; - struct partialMatch *oldLHSBinds; - struct partialMatch *oldRHSBinds; - struct joinNode *oldJoin; /*======================================*/ /* A NULL expression evaluates to TRUE. */ @@ -360,29 +596,6 @@ globle intBool EvaluateJoinExpression( if (joinExpr == NULL) return(TRUE); - /*=========================================*/ - /* Initialize some of the global variables */ - /* used when evaluating expressions. */ - /*=========================================*/ - - oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; - oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; - oldJoin = EngineData(theEnv)->GlobalJoin; - EngineData(theEnv)->GlobalLHSBinds = lbinds; - EngineData(theEnv)->GlobalRHSBinds = rbinds; - EngineData(theEnv)->GlobalJoin = joinPtr; - - /*=====================================================*/ - /* Partial matches stored in joins that are associated */ - /* with a not CE contain an additional slot shouldn't */ - /* be considered when evaluating expressions. Since */ - /* joins that have joins from the right don't have any */ - /* expression, we don't have to do this for partial */ - /* matches contained in these joins. */ - /*=====================================================*/ - - if (joinPtr->patternIsNegated) lbinds->bcount--; - /*====================================================*/ /* Initialize some variables which allow this routine */ /* to avoid calling the "and" and "or" functions if */ @@ -435,26 +648,14 @@ globle intBool EvaluateJoinExpression( else if (joinExpr->value == ExpressionData(theEnv)->PTR_OR) { result = FALSE; - if (EvaluateJoinExpression(theEnv,joinExpr,lbinds,rbinds,joinPtr) == TRUE) + if (EvaluateJoinExpression(theEnv,joinExpr,joinPtr) == TRUE) { if (EvaluationData(theEnv)->EvaluationError) - { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(FALSE); - } + { return(FALSE); } result = TRUE; } else if (EvaluationData(theEnv)->EvaluationError) - { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(FALSE); - } + { return(FALSE); } } /*==============================*/ @@ -464,26 +665,14 @@ globle intBool EvaluateJoinExpression( else if (joinExpr->value == ExpressionData(theEnv)->PTR_AND) { result = TRUE; - if (EvaluateJoinExpression(theEnv,joinExpr,lbinds,rbinds,joinPtr) == FALSE) + if (EvaluateJoinExpression(theEnv,joinExpr,joinPtr) == FALSE) { if (EvaluationData(theEnv)->EvaluationError) - { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(FALSE); - } + { return(FALSE); } result = FALSE; } else if (EvaluationData(theEnv)->EvaluationError) - { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(FALSE); - } + { return(FALSE); } } /*==========================================================*/ @@ -497,10 +686,6 @@ globle intBool EvaluateJoinExpression( if (EvaluationData(theEnv)->EvaluationError) { JoinNetErrorMessage(theEnv,joinPtr); - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; return(FALSE); } @@ -516,28 +701,169 @@ globle intBool EvaluateJoinExpression( /*====================================*/ if ((andLogic == TRUE) && (result == FALSE)) + { return(FALSE); } + else if ((andLogic == FALSE) && (result == TRUE)) + { return(TRUE); } + + /*==============================================*/ + /* Move to the next expression to be evaluated. */ + /*==============================================*/ + + joinExpr = joinExpr->nextArg; + } + + /*=================================================*/ + /* Return the result of evaluating the expression. */ + /*=================================================*/ + + return(result); + } + +/*******************************************************/ +/* EvaluateSecondaryNetworkTest: */ +/*******************************************************/ +globle intBool EvaluateSecondaryNetworkTest( + void *theEnv, + struct partialMatch *leftMatch, + struct joinNode *joinPtr) + { + int joinExpr; + struct partialMatch *oldLHSBinds; + struct partialMatch *oldRHSBinds; + struct joinNode *oldJoin; + + if (joinPtr->secondaryNetworkTest == NULL) + { return(TRUE); } + +#if DEVELOPER + EngineData(theEnv)->rightToLeftComparisons++; +#endif + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = leftMatch; + EngineData(theEnv)->GlobalRHSBinds = NULL; + EngineData(theEnv)->GlobalJoin = joinPtr; + + joinExpr = EvaluateJoinExpression(theEnv,joinPtr->secondaryNetworkTest,joinPtr); + EvaluationData(theEnv)->EvaluationError = FALSE; + + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + + return(joinExpr); + } + +/*******************************************************/ +/* BetaMemoryHashValue: */ +/*******************************************************/ +globle unsigned long BetaMemoryHashValue( + void *theEnv, + struct expr *hashExpr, + struct partialMatch *lbinds, + struct partialMatch *rbinds, + struct joinNode *joinPtr) + { + DATA_OBJECT theResult; + struct partialMatch *oldLHSBinds; + struct partialMatch *oldRHSBinds; + struct joinNode *oldJoin; + unsigned long hashValue = 0; + unsigned long multiplier = 1; + union + { + void *vv; + unsigned long liv; + } fis; + + /*======================================*/ + /* A NULL expression evaluates to zero. */ + /*======================================*/ + + if (hashExpr == NULL) return(0); + + /*=========================================*/ + /* Initialize some of the global variables */ + /* used when evaluating expressions. */ + /*=========================================*/ + + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = lbinds; + EngineData(theEnv)->GlobalRHSBinds = rbinds; + EngineData(theEnv)->GlobalJoin = joinPtr; + + /*=========================================*/ + /* Evaluate each of the expressions linked */ + /* together in the join expression. */ + /*=========================================*/ + + while (hashExpr != NULL) + { + /*================================*/ + /* Evaluate a primitive function. */ + /*================================*/ + + if ((EvaluationData(theEnv)->PrimitivesArray[hashExpr->type] == NULL) ? + FALSE : + EvaluationData(theEnv)->PrimitivesArray[hashExpr->type]->evaluateFunction != NULL) { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(FALSE); + struct expr *oldArgument; + + oldArgument = EvaluationData(theEnv)->CurrentExpression; + EvaluationData(theEnv)->CurrentExpression = hashExpr; + (*EvaluationData(theEnv)->PrimitivesArray[hashExpr->type]->evaluateFunction)(theEnv,hashExpr->value,&theResult); + EvaluationData(theEnv)->CurrentExpression = oldArgument; } - else if ((andLogic == FALSE) && (result == TRUE)) + + /*==========================================================*/ + /* Evaluate all other expressions using EvaluateExpression. */ + /*==========================================================*/ + + else + { EvaluateExpression(theEnv,hashExpr,&theResult); } + + switch (theResult.type) { - if (joinPtr->patternIsNegated) lbinds->bcount++; - EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; - EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; - EngineData(theEnv)->GlobalJoin = oldJoin; - return(TRUE); + case STRING: + case SYMBOL: + case INSTANCE_NAME: + hashValue += (((SYMBOL_HN *) theResult.value)->bucket * multiplier); + break; + + case INTEGER: + hashValue += (((INTEGER_HN *) theResult.value)->bucket * multiplier); + break; + + case FLOAT: + hashValue += (((FLOAT_HN *) theResult.value)->bucket * multiplier); + break; + + case FACT_ADDRESS: +#if OBJECT_SYSTEM + case INSTANCE_ADDRESS: +#endif + fis.liv = 0; + fis.vv = theResult.value; + hashValue += (unsigned long) (fis.liv * multiplier); + break; + + case EXTERNAL_ADDRESS: + fis.liv = 0; + fis.vv = ValueToExternalAddress(theResult.value); + hashValue += (unsigned long) (fis.liv * multiplier); + break; } /*==============================================*/ /* Move to the next expression to be evaluated. */ /*==============================================*/ - joinExpr = joinExpr->nextArg; - } + hashExpr = hashExpr->nextArg; + multiplier = multiplier * 509; + } /*=======================================*/ /* Restore some of the global variables. */ @@ -547,18 +873,11 @@ globle intBool EvaluateJoinExpression( EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; EngineData(theEnv)->GlobalJoin = oldJoin; - /*=====================================*/ - /* Restore the count value for the LHS */ - /* binds if it had to be modified. */ - /*=====================================*/ - - if (joinPtr->patternIsNegated) lbinds->bcount++; - /*=================================================*/ /* Return the result of evaluating the expression. */ /*=================================================*/ - return(result); + return(hashValue); } /*******************************************************************/ @@ -570,205 +889,104 @@ globle intBool EvaluateJoinExpression( /* partial match is sent to each child join of the join from */ /* which the merge took place. */ /*******************************************************************/ -static void PPDrive( +globle void PPDrive( void *theEnv, struct partialMatch *lhsBinds, struct partialMatch *rhsBinds, - struct joinNode *join) + struct joinNode *join, + int operation) { struct partialMatch *linker; - struct joinNode *listOfJoins; - - /*==================================================*/ - /* Merge the alpha and beta memory partial matches. */ - /*==================================================*/ - - linker = MergePartialMatches(theEnv,lhsBinds,rhsBinds, - (join->ruleToActivate == NULL) ? 0 : 1, - (int) join->logicalJoin); - - /*=======================================================*/ - /* Add the partial match to the beta memory of the join. */ - /*=======================================================*/ - - linker->next = join->beta; - join->beta = linker; - - /*====================================================*/ - /* Activate the rule satisfied by this partial match. */ - /*====================================================*/ - - if (join->ruleToActivate != NULL) AddActivation(theEnv,join->ruleToActivate,linker); + struct joinLink *listOfJoins; + unsigned long hashValue; /*================================================*/ /* Send the new partial match to all child joins. */ /*================================================*/ - listOfJoins = join->nextLevel; - if (listOfJoins != NULL) - { - if (((struct joinNode *) (listOfJoins->rightSideEntryStructure)) == join) - { NetworkAssert(theEnv,linker,listOfJoins,RHS); } - else while (listOfJoins != NULL) - { - NetworkAssert(theEnv,linker,listOfJoins,LHS); - listOfJoins = listOfJoins->rightDriveNode; - } - } - - return; - } + listOfJoins = join->nextLinks; + if (listOfJoins == NULL) return; -/**********************************************************************/ -/* PNRDrive: Handles the entry of a partial match from the RHS of a */ -/* join that has positive LHS entry and negative RHS entry (meaning */ -/* the conditional element associated with this join is a not */ -/* conditional element). Entry of the alpha memory partial match */ -/* will cause the counterf value of the associated beta memory */ -/* partial match to be set. This in turn may cause partial matches */ -/* associated with the beta memory partial match to be removed from */ -/* the network. */ -/**********************************************************************/ -static void PNRDrive( - void *theEnv, - struct joinNode *join, - struct partialMatch *lhsBinds, - struct partialMatch *rhsBinds) - { - struct joinNode *listOfJoins; + /*===============================================================*/ + /* In the current implementation, all children of this join must */ + /* be entered from the same side (either all left or all right). */ + /*===============================================================*/ - /*==================================================*/ - /* If the partial match already has a partial match */ - /* in the alpha memory which prevents it from being */ - /* satisfied, then don't do anything. */ - /*==================================================*/ - - if (lhsBinds->counterf == TRUE) return; - - /*=================================================*/ - /* Set the counterf flag to indicate that an alpha */ - /* memory partial match is preventing the beta */ - /* memory partial match from being satisfied. */ - /*=================================================*/ - - lhsBinds->counterf = TRUE; - - /*===================================================================*/ - /* If the partial match caused an activation, remove the activation. */ - /*===================================================================*/ + while (listOfJoins != NULL) + { + /*==================================================*/ + /* Merge the alpha and beta memory partial matches. */ + /*==================================================*/ - if ((lhsBinds->activationf) ? - (lhsBinds->binds[lhsBinds->bcount].gm.theValue != NULL) : FALSE) - { RemoveActivation(theEnv,(struct activation *) lhsBinds->binds[lhsBinds->bcount].gm.theValue,TRUE,TRUE); } + linker = MergePartialMatches(theEnv,lhsBinds,rhsBinds); - /*===========================================================*/ - /* The counterf flag was FALSE. This means that a pointer to */ - /* the pseudo-fact matching the not CE is stored directly in */ - /* the partial match. Determine the ID of this pseudo-fact */ - /* and remove all partial matches from descendent joins that */ - /* contain the ID. */ - /*===========================================================*/ + /*================================================*/ + /* Determine the hash value of the partial match. */ + /*================================================*/ - if (join->joinFromTheRight) /* GDR 111599 #834 Begin */ - { - RetractCheckDriveRetractions(theEnv,lhsBinds->binds[lhsBinds->bcount - 1].gm.theMatch, - (int) join->depth-1); - } /* GDR 111599 #834 End */ - - listOfJoins = join->nextLevel; - if (listOfJoins != NULL) - { - if (((struct joinNode *) (listOfJoins->rightSideEntryStructure)) == join) - { NegEntryRetract(theEnv,listOfJoins,lhsBinds,NULL); } - else while (listOfJoins != NULL) + if (listOfJoins->enterDirection == LHS) { - - PosEntryRetract(theEnv,listOfJoins, - lhsBinds->binds[lhsBinds->bcount - 1].gm.theMatch, - lhsBinds,(int) join->depth-1,NULL); - listOfJoins = listOfJoins->rightDriveNode; + if (listOfJoins->join->leftHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,listOfJoins->join->leftHash,linker,NULL,listOfJoins->join); } + else + { hashValue = 0; } + } + else + { + if (listOfJoins->join->rightHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,listOfJoins->join->rightHash,linker,NULL,listOfJoins->join); } + else + { hashValue = 0; } } - } - - /*=========================================================================*/ - /* Remove any logical dependency links associated with this partial match. */ - /*=========================================================================*/ - if (lhsBinds->dependentsf) RemoveLogicalSupport(theEnv,lhsBinds); + /*=======================================================*/ + /* Add the partial match to the beta memory of the join. */ + /*=======================================================*/ - /*========================================*/ - /* Put the pseudo-fact on a garbage list. */ - /*========================================*/ + UpdateBetaPMLinks(theEnv,linker,lhsBinds,rhsBinds,listOfJoins->join,hashValue,listOfJoins->enterDirection); - lhsBinds->binds[lhsBinds->bcount - 1].gm.theMatch->next = EngineData(theEnv)->GarbageAlphaMatches; - EngineData(theEnv)->GarbageAlphaMatches = lhsBinds->binds[lhsBinds->bcount - 1].gm.theMatch; + if (listOfJoins->enterDirection == LHS) + { NetworkAssertLeft(theEnv,linker,listOfJoins->join,operation); } + else + { NetworkAssertRight(theEnv,linker,listOfJoins->join,operation); } - /*========================================================*/ - /* Store the partial match from the alpha memory that is */ - /* preventing the LHS partial match from being satisfied. */ - /*========================================================*/ + listOfJoins = listOfJoins->next; + } - lhsBinds->binds[lhsBinds->bcount - 1].gm.theValue = (void *) rhsBinds; + return; } -/********************************************************************/ -/* PNLDrive: Handles the entry of a partial match from the LHS of a */ -/* join that has positive LHS entry and negative RHS entry */ -/* (meaning the conditional element associated with this join is */ -/* a not conditional element). An new partial match is created by */ -/* combining the match from the beta memory with a "pseudo" */ -/* partial match corresponding to the facts which didn't match */ -/* the not CE. Once merged, the new partial match is sent to each */ -/* child join of the join from which the merge took place. */ -/********************************************************************/ -globle void PNLDrive( +/***********************************************************************/ +/* EPMDrive: Drives an empty partial match to the next level of joins. */ +/* An empty partial match is usually associated with a negated CE */ +/* that is the first CE of a rule. */ +/***********************************************************************/ +globle void EPMDrive( void *theEnv, + struct partialMatch *parent, struct joinNode *join, - struct partialMatch *binds) + int operation) { - struct joinNode *listOfJoins; - struct alphaMatch *tempAlpha; - - /*=======================================================*/ - /* Create a pseudo-fact representing the facts which did */ - /* not match the not CE associated with this join. */ - /*=======================================================*/ + struct partialMatch *linker; + struct joinLink *listOfJoins; - tempAlpha = get_struct(theEnv,alphaMatch); - tempAlpha->next = NULL; - tempAlpha->matchingItem = NULL; - tempAlpha->markers = NULL; + listOfJoins = join->nextLinks; + if (listOfJoins == NULL) return; - /*===============================================*/ - /* Store the pointer to the pseudo-fact directly */ - /* in the beta memory partial match. */ - /*===============================================*/ + while (listOfJoins != NULL) + { + linker = CreateEmptyPartialMatch(theEnv); - binds->counterf = FALSE; - binds->binds[binds->bcount - 1].gm.theMatch = tempAlpha; + UpdateBetaPMLinks(theEnv,linker,parent,NULL,listOfJoins->join,0,listOfJoins->enterDirection); - /*====================================================*/ - /* Activate the rule satisfied by this partial match. */ - /*====================================================*/ + if (listOfJoins->enterDirection == LHS) + { NetworkAssertLeft(theEnv,linker,listOfJoins->join,operation); } + else + { NetworkAssertRight(theEnv,linker,listOfJoins->join,operation); } - if (join->ruleToActivate != NULL) AddActivation(theEnv,join->ruleToActivate,binds); - - /*========================================================*/ - /* Send the merged partial match to all descendent joins. */ - /*========================================================*/ - - listOfJoins = join->nextLevel; - if (listOfJoins != NULL) - { - if (((struct joinNode *) (listOfJoins->rightSideEntryStructure)) == join) - { NetworkAssert(theEnv,binds,listOfJoins,RHS); } - else while (listOfJoins != NULL) - { - NetworkAssert(theEnv,binds,listOfJoins,LHS); - listOfJoins = listOfJoins->rightDriveNode; - } - } - } + listOfJoins = listOfJoins->next; + } + } /***************************************************************/ /* EmptyDrive: Handles the entry of a alpha memory partial */ @@ -778,11 +996,16 @@ globle void PNLDrive( static void EmptyDrive( void *theEnv, struct joinNode *join, - struct partialMatch *rhsBinds) + struct partialMatch *rhsBinds, + int operation) { - struct partialMatch *linker; - struct joinNode *listOfJoins; + struct partialMatch *linker, *existsParent = NULL, *notParent; + struct joinLink *listOfJoins; int joinExpr; + unsigned long hashValue; + struct partialMatch *oldLHSBinds; + struct partialMatch *oldRHSBinds; + struct joinNode *oldJoin; /*======================================================*/ /* Determine if the alpha memory partial match satifies */ @@ -792,53 +1015,150 @@ static void EmptyDrive( if (join->networkTest != NULL) { - joinExpr = EvaluateJoinExpression(theEnv,join->networkTest,NULL,rhsBinds,join); + +#if DEVELOPER + EngineData(theEnv)->rightToLeftComparisons++; +#endif + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = NULL; + EngineData(theEnv)->GlobalRHSBinds = rhsBinds; + EngineData(theEnv)->GlobalJoin = join; + + joinExpr = EvaluateJoinExpression(theEnv,join->networkTest,join); EvaluationData(theEnv)->EvaluationError = FALSE; + + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + if (joinExpr == FALSE) return; } - /*===========================================================*/ - /* The first join of a rule cannot be connected to a NOT CE. */ - /*===========================================================*/ - - if (join->patternIsNegated == TRUE) + if (join->secondaryNetworkTest != NULL) { - SystemError(theEnv,"DRIVE",2); - EnvExitRouter(theEnv,EXIT_FAILURE); +#if DEVELOPER + EngineData(theEnv)->rightToLeftComparisons++; +#endif + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = NULL; + EngineData(theEnv)->GlobalRHSBinds = rhsBinds; + EngineData(theEnv)->GlobalJoin = join; + + joinExpr = EvaluateJoinExpression(theEnv,join->secondaryNetworkTest,join); + EvaluationData(theEnv)->EvaluationError = FALSE; + + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + + if (joinExpr == FALSE) return; } - /*=========================================================*/ - /* If the join's RHS entry is associated with a pattern CE */ - /* (positive entry), then copy the alpha memory partial */ - /* match and send it to all child joins. */ - /*=========================================================*/ + /*========================================================*/ + /* Handle a negated first pattern or join from the right. */ + /*========================================================*/ - linker = CopyPartialMatch(theEnv,rhsBinds, - (join->ruleToActivate == NULL) ? 0 : 1, - (int) join->logicalJoin); + if (join->patternIsNegated || (join->joinFromTheRight && (! join->patternIsExists))) /* reorder to remove patternIsExists test */ + { + notParent = join->leftMemory->beta[0]; + if (notParent->marker != NULL) + { return; } - /*=======================================================*/ - /* Add the partial match to the beta memory of the join. */ - /*=======================================================*/ + AddBlockedLink(notParent,rhsBinds); - linker->next = join->beta; - join->beta = linker; + if (notParent->children != NULL) + { PosEntryRetractBeta(theEnv,notParent,notParent->children,operation); } + /* + if (notParent->dependents != NULL) + { RemoveLogicalSupport(theEnv,notParent); } + */ - /*====================================================*/ - /* Activate the rule satisfied by this partial match. */ - /*====================================================*/ + return; + } - if (join->ruleToActivate != NULL) AddActivation(theEnv,join->ruleToActivate,linker); + /*=====================================================*/ + /* For exists CEs used as the first pattern of a rule, */ + /* a special partial match in the left memory of the */ + /* join is used to track the RHS partial match */ + /* satisfying the CE. */ + /*=====================================================*/ + /* TBD reorder */ + if (join->patternIsExists) + { + existsParent = join->leftMemory->beta[0]; + if (existsParent->marker != NULL) + { return; } + AddBlockedLink(existsParent,rhsBinds); + } /*============================================*/ /* Send the partial match to all child joins. */ /*============================================*/ - listOfJoins = join->nextLevel; + listOfJoins = join->nextLinks; + if (listOfJoins == NULL) return; + while (listOfJoins != NULL) { - NetworkAssert(theEnv,linker,listOfJoins,LHS); - listOfJoins = listOfJoins->rightDriveNode; + /*===================================================================*/ + /* An exists CE as the first pattern of a rule can generate at most */ + /* one partial match, so if there's already a partial match in the */ + /* beta memory nothing further needs to be done. Since there are no */ + /* variable bindings which child joins can use for indexing, the */ + /* partial matches will always be stored in the bucket with index 0. */ + /* Although an exists is associated with a specific fact/instance */ + /* (through its rightParent link) that allows it to be satisfied, */ + /* the bindings in the partial match will be empty for this CE. */ + /*===================================================================*/ + + if (join->patternIsExists) + { linker = CreateEmptyPartialMatch(theEnv); } + + /*=============================================================*/ + /* Othewise just copy the partial match from the alpha memory. */ + /*=============================================================*/ + + else + { linker = CopyPartialMatch(theEnv,rhsBinds); } + + /*================================================*/ + /* Determine the hash value of the partial match. */ + /*================================================*/ + + if (listOfJoins->enterDirection == LHS) + { + if (listOfJoins->join->leftHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,listOfJoins->join->leftHash,linker,NULL,listOfJoins->join); } + else + { hashValue = 0; } + } + else + { + if (listOfJoins->join->rightHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,listOfJoins->join->rightHash,linker,NULL,listOfJoins->join); } + else + { hashValue = 0; } + } + + /*=======================================================*/ + /* Add the partial match to the beta memory of the join. */ + /*=======================================================*/ + + if (join->patternIsExists) + { UpdateBetaPMLinks(theEnv,linker,existsParent,NULL,listOfJoins->join,hashValue,listOfJoins->enterDirection); } + else + { UpdateBetaPMLinks(theEnv,linker,NULL,rhsBinds,listOfJoins->join,hashValue,listOfJoins->enterDirection); } + + if (listOfJoins->enterDirection == LHS) + { NetworkAssertLeft(theEnv,linker,listOfJoins->join,operation); } + else + { NetworkAssertRight(theEnv,linker,listOfJoins->join,operation); } + + listOfJoins = listOfJoins->next; } } @@ -851,14 +1171,14 @@ static void JoinNetErrorMessage( void *theEnv, struct joinNode *joinPtr) { - char buffer[60]; - PrintErrorID(theEnv,"DRIVE",1,TRUE); EnvPrintRouter(theEnv,WERROR,"This error occurred in the join network\n"); + EnvPrintRouter(theEnv,WERROR," Problem resides in associated join\n"); /* TBD generate test case for join with JFTR */ +/* sprintf(buffer," Problem resides in join #%d in rule(s):\n",joinPtr->depth); EnvPrintRouter(theEnv,WERROR,buffer); - +*/ TraceErrorToRule(theEnv,joinPtr," "); EnvPrintRouter(theEnv,WERROR,"\n"); } diff --git a/src/drive.h b/src/drive.h index 0a4c458..089dfe2 100644 --- a/src/drive.h +++ b/src/drive.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 12/04/07 */ /* */ /* DRIVE HEADER FILE */ /*******************************************************/ @@ -20,6 +20,13 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CE. */ +/* */ /*************************************************************/ #ifndef _H_drive @@ -46,11 +53,16 @@ #define LOCALE extern #endif - void NetworkAssert(void *,struct partialMatch *,struct joinNode *,int); - void PNLDrive(void *,struct joinNode *,struct partialMatch *); - intBool EvaluateJoinExpression(void *,struct expr *,struct partialMatch *,struct partialMatch *,struct joinNode *); + void NetworkAssert(void *,struct partialMatch *,struct joinNode *); + intBool EvaluateJoinExpression(void *,struct expr *,struct joinNode *); + void NetworkAssertLeft(void *,struct partialMatch *,struct joinNode *,int); + void NetworkAssertRight(void *,struct partialMatch *,struct joinNode *,int); + void PPDrive(void *,struct partialMatch *,struct partialMatch *,struct joinNode *,int); + unsigned long BetaMemoryHashValue(void *,struct expr *,struct partialMatch *,struct partialMatch *,struct joinNode *); + intBool EvaluateSecondaryNetworkTest(void *,struct partialMatch *,struct joinNode *); + void EPMDrive(void *,struct partialMatch *,struct joinNode *,int); -#endif +#endif /* _H_drive */ diff --git a/src/edbasic.c b/src/edbasic.c index df643d1..6b7f404 100644 --- a/src/edbasic.c +++ b/src/edbasic.c @@ -100,7 +100,7 @@ globle int backchar( return (forwchar(theEnv,f, -n)); while (n--) { - if (curwp->w_doto == 0) + if (curwp->w_doto == 0) { if ((lp=lback(curwp->w_dotp)) == curbp->b_linep) { return (FALSE); } @@ -379,7 +379,7 @@ globle int swapmark( register LINE *odotp; register int odoto; - if (curwp->w_markp == NULL) + if (curwp->w_markp == NULL) { mlwrite("No mark in this window"); return (FALSE); @@ -1744,7 +1744,7 @@ globle int parse_esc_seq() { } break; default : return BADKEY; - } + } return(TRUE); } #endif diff --git a/src/edmain.c b/src/edmain.c index b5ac314..d050dda 100644 --- a/src/edmain.c +++ b/src/edmain.c @@ -5,7 +5,7 @@ /* */ /* */ /*******************************************************/ - + /*************************************************************/ /* Purpose: */ /* */ @@ -546,7 +546,7 @@ globle int ctlxlp( int f, int n) { - if (kbdmip!=NULL || kbdmop!=NULL) + if (kbdmip!=NULL || kbdmop!=NULL) { mlwrite("Not now"); return (FALSE); @@ -739,11 +739,11 @@ globle void EditCommand( void (*redrawScreenFunction)(void *); void (*pauseEnvFunction)(void *); void (*continueEnvFunction)(void *,int); - + redrawScreenFunction = GetRedrawFunction(theEnv); pauseEnvFunction = GetPauseEnvFunction(theEnv); continueEnvFunction = GetContinueEnvFunction(theEnv); - + if (pauseEnvFunction != NULL) (*pauseEnvFunction)(theEnv) ; PerformEditCommand(theEnv); if (continueEnvFunction != NULL) (*continueEnvFunction)(theEnv,0) ; @@ -772,7 +772,7 @@ globle void EditCommand( globle void EditorFunctionDefinition( void *theEnv) - { + { } #endif diff --git a/src/edmisc.c b/src/edmisc.c index aabe6bf..b407aeb 100644 --- a/src/edmisc.c +++ b/src/edmisc.c @@ -5,7 +5,7 @@ /* */ /* */ /*******************************************************/ - + /*************************************************************/ /* Purpose: */ /* */ @@ -195,7 +195,7 @@ globle int get_compile( CompileLineIndex = 0; CompileLine[0] = '\0'; - EnvActivateRouter(theEnv,str1); + EnvActivateRouter(theEnv,str1); EnvActivateRouter(theEnv,"cmp_router"); SetPrintWhileLoading(theEnv,TRUE); LoadConstructsFromLogicalName(theEnv,str2); @@ -203,7 +203,7 @@ globle int get_compile( /* Flush last diagnostic line (if any) to buffer */ if (CompileLineIndex != 0) addline(theEnv,CompileBufferp,CompileLine); - EnvDeactivateRouter(theEnv,str1); + EnvDeactivateRouter(theEnv,str1); EnvDeactivateRouter(theEnv,"cmp_router"); SetPrintWhileLoading(theEnv,FALSE); EnvDeleteRouter(theEnv,str1); @@ -237,7 +237,7 @@ globle int get_compile( return(CompileSuccess); #else return(0); -#endif +#endif } /**************************************************************** @@ -394,7 +394,7 @@ globle int query_cmp( globle int print_cmp( void *theEnv, - char *logName, + char *logName, char *str) { register int i; @@ -1889,7 +1889,7 @@ globle int spawncli( #if UNIX_7 || UNIX_V || IBM_MSC || IBM_TBC || IBM_ZTC || IBM_ICB || IBM_SC || IBM_GCC register char *cp; #endif - + #if VAX_VMS movecursor(term.t_nrow, 0); /* In last line. */ mlputs("[Starting DCL]\r\n"); diff --git a/src/edterm.c b/src/edterm.c index 23cc4e2..6adbe1c 100644 --- a/src/edterm.c +++ b/src/edterm.c @@ -5,7 +5,7 @@ /* */ /* */ /*******************************************************/ - + /*************************************************************/ /* Purpose: */ /* */ @@ -515,11 +515,11 @@ static void pc_eeol() /* wait for vertical retrace to be off */ while ((inp(0x3da) & 8)) ; - + /* and to be back on */ while ((inp(0x3da) & 8) == 0) ; - } + } #if IBM_ZTC disp_move(crow,ccol); @@ -645,7 +645,7 @@ static void tcapopen() } static void tcapmove( - int row, + int row, int col) { putpad(tgoto(CM, col, row)); diff --git a/src/emathfun.c b/src/emathfun.c index 9b4569c..abdbeae 100644 --- a/src/emathfun.c +++ b/src/emathfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXTENDED MATH FUNCTIONS MODULE */ /*******************************************************/ @@ -15,13 +15,25 @@ /* deg-grad, grad-deg, **, and round. */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Renamed EX_MATH compiler flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #include "setup.h" @@ -32,7 +44,7 @@ #include "emathfun.h" -#if EX_MATH +#if EXTENDED_MATH_FUNCTIONS #include <math.h> @@ -55,11 +67,11 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int SingleNumberCheck(void *,char *,double *); + static int SingleNumberCheck(void *,const char *,double *); static int TestProximity(double,double); - static void DomainErrorMessage(void *,char *); - static void ArgumentOverflowErrorMessage(void *,char *); - static void SingularityErrorMessage(void *,char *); + static void DomainErrorMessage(void *,const char *); + static void ArgumentOverflowErrorMessage(void *,const char *); + static void SingularityErrorMessage(void *,const char *); static double genacosh(double); static double genasinh(double); static double genatanh(double); @@ -111,9 +123,9 @@ globle void ExtendedMathFunctionDefinitions( EnvDefineFunction2(theEnv,"deg-grad", 'd', PTIEF DegGradFunction, "DegGradFunction", "11n"); EnvDefineFunction2(theEnv,"grad-deg", 'd', PTIEF GradDegFunction, "GradDegFunction", "11n"); EnvDefineFunction2(theEnv,"**", 'd', PTIEF PowFunction, "PowFunction", "22n"); - EnvDefineFunction2(theEnv,"round", 'l', PTIEF RoundFunction, "RoundFunction", "11n"); + EnvDefineFunction2(theEnv,"round", 'g', PTIEF RoundFunction, "RoundFunction", "11n"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -126,7 +138,7 @@ globle void ExtendedMathFunctionDefinitions( /************************************************************/ static int SingleNumberCheck( void *theEnv, - char *functionName, + const char *functionName, double *theNumber) { DATA_OBJECT theValue; @@ -157,7 +169,7 @@ static int TestProximity( /********************************************************/ static void DomainErrorMessage( void *theEnv, - char *functionName) + const char *functionName) { PrintErrorID(theEnv,"EMATHFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Domain error for "); @@ -174,7 +186,7 @@ static void DomainErrorMessage( /************************************************************/ static void ArgumentOverflowErrorMessage( void *theEnv, - char *functionName) + const char *functionName) { PrintErrorID(theEnv,"EMATHFUN",2,FALSE); EnvPrintRouter(theEnv,WERROR,"Argument overflow for "); @@ -191,7 +203,7 @@ static void ArgumentOverflowErrorMessage( /************************************************************/ static void SingularityErrorMessage( void *theEnv, - char *functionName) + const char *functionName) { PrintErrorID(theEnv,"EMATHFUN",3,FALSE); EnvPrintRouter(theEnv,WERROR,"Singularity at asymptote in "); @@ -729,7 +741,7 @@ globle void ModFunction( { DATA_OBJECT item1, item2; double fnum1, fnum2; - long lnum1, lnum2; + long long lnum1, lnum2; if (EnvArgCountCheck(theEnv,"mod",EXACTLY,2) == -1) { @@ -846,25 +858,25 @@ globle double GradDegFunction( /* RoundFunction: H/L access routine */ /* for the round function. */ /***************************************/ -globle long int RoundFunction( +globle long long RoundFunction( void *theEnv) { DATA_OBJECT result; if (EnvArgCountCheck(theEnv,"round",EXACTLY,1) == -1) - { return(0L); } + { return(0LL); } if (EnvArgTypeCheck(theEnv,"round",1,INTEGER_OR_FLOAT,&result) == FALSE) - { return(0L); } + { return(0LL); } if (result.type == INTEGER) { return(ValueToLong(result.value)); } else - { return((long) ceil(ValueToDouble(result.value) - 0.5)); } + { return((long long) ceil(ValueToDouble(result.value) - 0.5)); } } /*******************************************/ -/* genacsch: Generic routine for computing */ +/* genacosh: Generic routine for computing */ /* the hyperbolic arccosine. */ /*******************************************/ static double genacosh( @@ -874,7 +886,7 @@ static double genacosh( } /*******************************************/ -/* genacsch: Generic routine for computing */ +/* genasinh: Generic routine for computing */ /* the hyperbolic arcsine. */ /*******************************************/ static double genasinh( @@ -894,7 +906,7 @@ static double genatanh( } /*******************************************/ -/* genacsch: Generic routine for computing */ +/* genasech: Generic routine for computing */ /* the hyperbolic arcsecant. */ /*******************************************/ static double genasech( diff --git a/src/emathfun.h b/src/emathfun.h index d282ce3..79f4104 100644 --- a/src/emathfun.h +++ b/src/emathfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 12/27/07 */ /* */ /* EXTENDED MATH FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -21,6 +21,18 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Renamed EX_MATH compiler flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_emathfun @@ -38,7 +50,7 @@ #endif LOCALE void ExtendedMathFunctionDefinitions(void *theEnv); -#if EX_MATH +#if EXTENDED_MATH_FUNCTIONS LOCALE double CosFunction(void *); LOCALE double SinFunction(void *); LOCALE double TanFunction(void *); @@ -63,7 +75,7 @@ LOCALE double AsechFunction(void *); LOCALE double AcschFunction(void *); LOCALE double AcothFunction(void *); - LOCALE long RoundFunction(void *); + LOCALE long long RoundFunction(void *); LOCALE void ModFunction(void *,DATA_OBJECT_PTR); LOCALE double ExpFunction(void *); LOCALE double LogFunction(void *); @@ -77,7 +89,7 @@ LOCALE double PowFunction(void *); #endif -#endif +#endif /* _H_emathfun */ diff --git a/src/engine.c b/src/engine.c index 3b96131..35be086 100644 --- a/src/engine.c +++ b/src/engine.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* ENGINE MODULE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* */ /* Contributing Programmer(s): */ /* Bebe Ly */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -33,6 +34,31 @@ /* Added EnvGetNextFocus, EnvGetFocusChanged, and */ /* EnvSetFocusChanged functions. */ /* */ +/* 6.30: Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ +/* Added context information for run functions. */ +/* */ +/* Added before rule firing callback function. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added EnvHalt function. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _ENGINE_SOURCE_ @@ -70,7 +96,6 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct activation *NextActivationToFire(void *); static struct defmodule *RemoveFocus(void *,struct defmodule *); static void DeallocateEngineData(void *); @@ -79,17 +104,17 @@ /*****************************************************************************/ globle void InitializeEngine( void *theEnv) - { + { AllocateEnvironmentData(theEnv,ENGINE_DATA,sizeof(struct engineData),DeallocateEngineData); EngineData(theEnv)->IncrementalResetFlag = TRUE; - + #if DEBUGGING_FUNCTIONS AddWatchItem(theEnv,"statistics",0,&EngineData(theEnv)->WatchStatistics,20,NULL,NULL); AddWatchItem(theEnv,"focus",0,&EngineData(theEnv)->WatchFocus,0,NULL,NULL); #endif } - + /*************************************************/ /* DeallocateEngineData: Deallocates environment */ /* data for engine functionality. */ @@ -98,8 +123,9 @@ static void DeallocateEngineData( void *theEnv) { struct focus *tmpPtr, *nextPtr; - + DeallocateCallList(theEnv,EngineData(theEnv)->ListOfRunFunctions); + DeallocateCallListWithArg(theEnv,EngineData(theEnv)->ListOfBeforeRunFunctions); tmpPtr = EngineData(theEnv)->CurrentFocus; while (tmpPtr != NULL) @@ -113,12 +139,13 @@ static void DeallocateEngineData( /*************************************************/ /* EnvRun: C access routine for the run command. */ /*************************************************/ -globle long int EnvRun( +globle long long EnvRun( void *theEnv, - long int runLimit) + long long runLimit) { - long int rulesFired = 0; + long long rulesFired = 0; DATA_OBJECT result; + struct callFunctionItemWithArg *theBeforeRunFunction; struct callFunctionItem *theRunFunction; #if DEBUGGING_FUNCTIONS unsigned long maxActivations = 0, sumActivations = 0; @@ -128,17 +155,19 @@ globle long int EnvRun( #if OBJECT_SYSTEM unsigned long maxInstances = 0, sumInstances = 0; #endif -// double endTime, startTime = 0.0; + double endTime, startTime = 0.0; unsigned long tempValue; #endif - unsigned int i; + unsigned short i; struct patternEntity *theMatchingItem; struct partialMatch *theBasis; ACTIVATION *theActivation; - char *ruleFiring; + const char *ruleFiring; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; #endif + struct trackedMemory *theTM; + struct garbageFrame newGarbageFrame, *oldGarbageFrame; /*=====================================================*/ /* Make sure the run command is not already executing. */ @@ -147,6 +176,15 @@ globle long int EnvRun( if (EngineData(theEnv)->AlreadyRunning) return(0); EngineData(theEnv)->AlreadyRunning = TRUE; + /*========================================*/ + /* Set up the frame for tracking garbage. */ + /*========================================*/ + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + /*================================*/ /* Set up statistics information. */ /*================================*/ @@ -164,7 +202,7 @@ globle long int EnvRun( #endif maxActivations = GetNumberOfActivations(theEnv); sumActivations = maxActivations; -// startTime = gentime(); + startTime = gentime(); } #endif @@ -172,9 +210,22 @@ globle long int EnvRun( /* Set up execution variables. */ /*=============================*/ - if (EvaluationData(theEnv)->CurrentEvaluationDepth == 0) SetHaltExecution(theEnv,FALSE); + if (UtilityData(theEnv)->CurrentGarbageFrame->topLevel) SetHaltExecution(theEnv,FALSE); EngineData(theEnv)->HaltRules = FALSE; +#if DEVELOPER + EngineData(theEnv)->leftToRightComparisons = 0; + EngineData(theEnv)->rightToLeftComparisons = 0; + EngineData(theEnv)->leftToRightSucceeds = 0; + EngineData(theEnv)->rightToLeftSucceeds = 0; + EngineData(theEnv)->leftToRightLoops = 0; + EngineData(theEnv)->rightToLeftLoops = 0; + EngineData(theEnv)->findNextConflictingComparisons = 0; + EngineData(theEnv)->betaHashListSkips = 0; + EngineData(theEnv)->betaHashHTSkips = 0; + EngineData(theEnv)->unneededMarkerCompare = 0; +#endif + /*=====================================================*/ /* Fire rules until the agenda is empty, the run limit */ /* has been reached, or a rule execution error occurs. */ @@ -186,15 +237,32 @@ globle long int EnvRun( (EvaluationData(theEnv)->HaltExecution == FALSE) && (EngineData(theEnv)->HaltRules == FALSE)) { + /*========================================*/ + /* Execute the list of functions that are */ + /* to be called before each rule firing. */ + /*========================================*/ + + for (theBeforeRunFunction = EngineData(theEnv)->ListOfBeforeRunFunctions; + theBeforeRunFunction != NULL; + theBeforeRunFunction = theBeforeRunFunction->next) + { + SetEnvironmentCallbackContext(theEnv,theBeforeRunFunction->context); + if (theBeforeRunFunction->environmentAware) + { (*theBeforeRunFunction->func)(theEnv,theActivation); } + else + { ((void (*)(void *))(*theBeforeRunFunction->func))(theActivation); } + } + /*===========================================*/ /* Detach the activation from the agenda and */ /* determine which rule is firing. */ /*===========================================*/ DetachActivation(theEnv,theActivation); + theTM = AddTrackedMemory(theEnv,theActivation,sizeof(struct activation)); ruleFiring = EnvGetActivationName(theEnv,theActivation); - theBasis = (struct partialMatch *) GetActivationBasis(theActivation); - EngineData(theEnv)->ExecutingRule = (struct defrule *) GetActivationRule(theActivation); + theBasis = (struct partialMatch *) EnvGetActivationBasis(theEnv,theActivation); + EngineData(theEnv)->ExecutingRule = (struct defrule *) EnvGetActivationRule(theEnv,theActivation); /*=============================================*/ /* Update the number of rules that have fired. */ @@ -213,7 +281,7 @@ globle long int EnvRun( { char printSpace[60]; - sprintf(printSpace,"FIRE %4ld ",rulesFired); + gensprintf(printSpace,"FIRE %4lld ",rulesFired); EnvPrintRouter(theEnv,WTRACE,printSpace); EnvPrintRouter(theEnv,WTRACE,ruleFiring); EnvPrintRouter(theEnv,WTRACE,": "); @@ -232,7 +300,7 @@ globle long int EnvRun( /* routines which do variable extractions. */ /*=================================================*/ - theBasis->binds[theBasis->bcount].gm.theValue = NULL; + theBasis->marker = NULL; theBasis->busy = TRUE; EngineData(theEnv)->GlobalLHSBinds = theBasis; @@ -246,19 +314,32 @@ globle long int EnvRun( for (i = 0; i < theBasis->bcount; i++) { + if (theBasis->binds[i].gm.theMatch == NULL) continue; theMatchingItem = theBasis->binds[i].gm.theMatch->matchingItem; if (theMatchingItem != NULL) { (*theMatchingItem->theInfo->incrementBasisCount)(theEnv,theMatchingItem); } } /*====================================================*/ - /* Execute the rule's right hand side actions. If the */ - /* rule has logical CEs, set up the pointer to the */ - /* rules logical join so the assert command will */ + /* If the rule has logical CEs, set up the pointer to */ + /* the rules logical join so the assert command will */ /* attach the appropriate dependencies to the facts. */ /*====================================================*/ EngineData(theEnv)->TheLogicalJoin = EngineData(theEnv)->ExecutingRule->logicalJoin; + + if (EngineData(theEnv)->TheLogicalJoin != NULL) + { + EngineData(theEnv)->TheLogicalBind = FindLogicalBind(EngineData(theEnv)->TheLogicalJoin,EngineData(theEnv)->GlobalLHSBinds); + EngineData(theEnv)->TheLogicalBind->busy = TRUE; + } + else + { EngineData(theEnv)->TheLogicalBind = NULL; } + + /*=============================================*/ + /* Execute the rule's right hand side actions. */ + /*=============================================*/ + EvaluationData(theEnv)->CurrentEvaluationDepth++; SetEvaluationError(theEnv,FALSE); EngineData(theEnv)->ExecutingRule->executing = TRUE; @@ -280,8 +361,19 @@ globle long int EnvRun( EngineData(theEnv)->ExecutingRule->executing = FALSE; SetEvaluationError(theEnv,FALSE); EvaluationData(theEnv)->CurrentEvaluationDepth--; + + /*=====================================*/ + /* Remove information for logical CEs. */ + /*=====================================*/ + EngineData(theEnv)->TheLogicalJoin = NULL; + if (EngineData(theEnv)->TheLogicalBind != NULL) + { + EngineData(theEnv)->TheLogicalBind->busy = FALSE; + EngineData(theEnv)->TheLogicalBind = NULL; + } + /*=====================================================*/ /* If rule execution was halted, then print a message. */ /*=====================================================*/ @@ -299,25 +391,16 @@ globle long int EnvRun( EnvPrintRouter(theEnv,WERROR,".\n"); } - /*===================================================================*/ - /* Decrement the count for each of the facts/objects associated with */ - /* the rule activation. If the last match for the activation */ - /* is from a not CE, then we need to make sure that the last */ - /* match is an actual match for the CE and not a counter. */ - /*===================================================================*/ + /*===================================================*/ + /* Decrement the count for each of the facts/objects */ + /* associated with the rule activation. */ + /*===================================================*/ theBasis->busy = FALSE; - for (i = 0; i < (theBasis->bcount - 1); i++) - { - theMatchingItem = theBasis->binds[i].gm.theMatch->matchingItem; - if (theMatchingItem != NULL) - { (*theMatchingItem->theInfo->decrementBasisCount)(theEnv,theMatchingItem); } - } - - i = (unsigned) (theBasis->bcount - 1); - if (theBasis->counterf == FALSE) + for (i = 0; i < (theBasis->bcount); i++) { + if (theBasis->binds[i].gm.theMatch == NULL) continue; theMatchingItem = theBasis->binds[i].gm.theMatch->matchingItem; if (theMatchingItem != NULL) { (*theMatchingItem->theInfo->decrementBasisCount)(theEnv,theMatchingItem); } @@ -327,6 +410,7 @@ globle long int EnvRun( /* Return the agenda node to free memory. */ /*========================================*/ + RemoveTrackedMemory(theEnv,theTM); RemoveActivation(theEnv,theActivation,FALSE,FALSE); /*======================================*/ @@ -341,7 +425,8 @@ globle long int EnvRun( /* while executing the rule's RHS. */ /*==================================*/ - PeriodicCleanup(theEnv,FALSE,TRUE); + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); /*==========================*/ /* Keep up with statistics. */ @@ -380,10 +465,11 @@ globle long int EnvRun( for (theRunFunction = EngineData(theEnv)->ListOfRunFunctions; theRunFunction != NULL; theRunFunction = theRunFunction->next) - { + { + SetEnvironmentCallbackContext(theEnv,theRunFunction->context); if (theRunFunction->environmentAware) { (*theRunFunction->func)(theEnv); } - else + else { ((void (*)(void))(*theRunFunction->func))(); } } @@ -409,7 +495,7 @@ globle long int EnvRun( if (theActivation != NULL) { - if (((struct defrule *) GetActivationRule(theActivation))->afterBreakpoint) + if (((struct defrule *) EnvGetActivationRule(theEnv,theActivation))->afterBreakpoint) { EngineData(theEnv)->HaltRules = TRUE; EnvPrintRouter(theEnv,WDIALOG,"Breaking on rule "); @@ -428,10 +514,10 @@ globle long int EnvRun( for (theRunFunction = EngineData(theEnv)->ListOfRunFunctions; theRunFunction != NULL; theRunFunction = theRunFunction->next) - { + { if (theRunFunction->environmentAware) { (*theRunFunction->func)(theEnv); } - else + else { ((void (*)(void))(*theRunFunction->func))(); } } } @@ -460,13 +546,13 @@ globle long int EnvRun( { char printSpace[60]; -// endTime = gentime(); + endTime = gentime(); PrintLongInteger(theEnv,WDIALOG,rulesFired); EnvPrintRouter(theEnv,WDIALOG," rules fired"); #if (! GENERIC) -/* if (startTime != endTime) + if (startTime != endTime) { EnvPrintRouter(theEnv,WDIALOG," Run time is "); PrintFloat(theEnv,WDIALOG,endTime - startTime); @@ -475,27 +561,72 @@ globle long int EnvRun( EnvPrintRouter(theEnv,WDIALOG," rules per second.\n"); } else - { EnvPrintRouter(theEnv,WDIALOG,"\n"); } */ + { EnvPrintRouter(theEnv,WDIALOG,"\n"); } +#else + EnvPrintRouter(theEnv,WDIALOG,"\n"); #endif #if DEFTEMPLATE_CONSTRUCT - sprintf(printSpace,"%ld mean number of facts (%ld maximum).\n", + gensprintf(printSpace,"%ld mean number of facts (%ld maximum).\n", (long) (((double) sumFacts / (rulesFired + 1)) + 0.5), maxFacts); EnvPrintRouter(theEnv,WDIALOG,printSpace); #endif #if OBJECT_SYSTEM - sprintf(printSpace,"%ld mean number of instances (%ld maximum).\n", + gensprintf(printSpace,"%ld mean number of instances (%ld maximum).\n", (long) (((double) sumInstances / (rulesFired + 1)) + 0.5), maxInstances); EnvPrintRouter(theEnv,WDIALOG,printSpace); #endif - sprintf(printSpace,"%ld mean number of activations (%ld maximum).\n", + gensprintf(printSpace,"%ld mean number of activations (%ld maximum).\n", (long) (((double) sumActivations / (rulesFired + 1)) + 0.5), maxActivations); EnvPrintRouter(theEnv,WDIALOG,printSpace); + +#if DEVELOPER + gensprintf(printSpace,"%9ld left to right comparisons.\n", + EngineData(theEnv)->leftToRightComparisons); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld left to right succeeds.\n", + EngineData(theEnv)->leftToRightSucceeds); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld left to right loops.\n", + EngineData(theEnv)->leftToRightLoops); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld right to left comparisons.\n", + EngineData(theEnv)->rightToLeftComparisons); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld right to left succeeds.\n", + EngineData(theEnv)->rightToLeftSucceeds); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld right to left loops.\n", + EngineData(theEnv)->rightToLeftLoops); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld find next conflicting comparisons.\n", + EngineData(theEnv)->findNextConflictingComparisons); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld beta hash list skips.\n", + EngineData(theEnv)->betaHashListSkips); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld beta hash hash table skips.\n", + EngineData(theEnv)->betaHashHTSkips); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + + gensprintf(printSpace,"%9ld unneeded marker compare.\n", + EngineData(theEnv)->unneededMarkerCompare); + EnvPrintRouter(theEnv,WDIALOG,printSpace); + +#endif } #endif @@ -510,6 +641,13 @@ globle long int EnvRun( { EnvSetCurrentModule(theEnv,(void *) EngineData(theEnv)->CurrentFocus->theModule); } } + /*================================*/ + /* Restore the old garbage frame. */ + /*================================*/ + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame, oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + /*===================================*/ /* Return the number of rules fired. */ /*===================================*/ @@ -522,7 +660,7 @@ globle long int EnvRun( /* NextActivationToFire: Returns the next activation which */ /* should be executed based on the current focus. */ /***********************************************************/ -static struct activation *NextActivationToFire( +globle struct activation *NextActivationToFire( void *theEnv) { struct activation *theActivation; @@ -764,34 +902,13 @@ globle void EnvClearFocusStack( EngineData(theEnv)->FocusChanged = TRUE; } -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -/***********************************/ -/* AddRunFunction: Adds a function */ -/* to the ListOfRunFunctions. */ -/***********************************/ -globle intBool AddRunFunction( - char *name, - void (*functionPtr)(void), - int priority) - { - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - EngineData(theEnv)->ListOfRunFunctions = - AddFunctionToCallList(theEnv,name,priority,(void (*)(void *)) functionPtr, - EngineData(theEnv)->ListOfRunFunctions,TRUE); - return(1); - } -#endif - /**************************************/ /* EnvAddRunFunction: Adds a function */ /* to the ListOfRunFunctions. */ /**************************************/ globle intBool EnvAddRunFunction( void *theEnv, - char *name, + const char *name, void (*functionPtr)(void *), int priority) { @@ -802,16 +919,68 @@ globle intBool EnvAddRunFunction( } /********************************************/ +/* EnvAddBeforeRunFunction: Adds a function */ +/* to the ListOfBeforeRunFunctions. */ +/********************************************/ +globle intBool EnvAddBeforeRunFunction( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority) + { + EngineData(theEnv)->ListOfBeforeRunFunctions = AddFunctionToCallListWithArg(theEnv,name,priority, + functionPtr, + EngineData(theEnv)->ListOfBeforeRunFunctions,TRUE); + return(1); + } + +/*****************************************/ +/* EnvAddRunFunctionWithContext: Adds a */ +/* function to the ListOfRunFunctions. */ +/*****************************************/ +globle intBool EnvAddRunFunctionWithContext( + void *theEnv, + const char *name, + void (*functionPtr)(void *), + int priority, + void *context) + { + EngineData(theEnv)->ListOfRunFunctions = + AddFunctionToCallListWithContext(theEnv,name,priority,functionPtr, + EngineData(theEnv)->ListOfRunFunctions, + TRUE,context); + return(1); + } + +/***********************************************/ +/* EnvAddBeforeRunFunctionWithContext: Adds a */ +/* function to the ListOfBeforeRunFunctions. */ +/***********************************************/ +globle intBool EnvAddBeforeRunFunctionWithContext( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority, + void *context) + { + EngineData(theEnv)->ListOfBeforeRunFunctions = + AddFunctionToCallListWithArgWithContext(theEnv,name,priority,functionPtr, + EngineData(theEnv)->ListOfBeforeRunFunctions, + TRUE,context); + return(1); + } + +/********************************************/ /* EnvRemoveRunFunction: Removes a function */ /* from the ListOfRunFunctions. */ /********************************************/ globle intBool EnvRemoveRunFunction( void *theEnv, - char *name) + const char *name) { int found; - EngineData(theEnv)->ListOfRunFunctions = + EngineData(theEnv)->ListOfRunFunctions = RemoveFunctionFromCallList(theEnv,name,EngineData(theEnv)->ListOfRunFunctions,&found); if (found) return(TRUE); @@ -819,6 +988,24 @@ globle intBool EnvRemoveRunFunction( return(FALSE); } +/**************************************************/ +/* EnvRemoveBeforeRunFunction: Removes a function */ +/* from the ListOfBeforeRunFunctions. */ +/**************************************************/ +globle intBool EnvRemoveBeforeRunFunction( + void *theEnv, + const char *name) + { + int found; + + EngineData(theEnv)->ListOfBeforeRunFunctions = + RemoveFunctionFromCallListWithArg(theEnv,name,EngineData(theEnv)->ListOfBeforeRunFunctions,&found); + + if (found) return(TRUE); + + return(FALSE); + } + /*********************************************************/ /* RunCommand: H/L access routine for the run command. */ /*********************************************************/ @@ -826,13 +1013,13 @@ globle void RunCommand( void *theEnv) { int numArgs; - long int runLimit = -1; + long long runLimit = -1LL; DATA_OBJECT argPtr; if ((numArgs = EnvArgCountCheck(theEnv,"run",NO_MORE_THAN,1)) == -1) return; if (numArgs == 0) - { runLimit = -1; } + { runLimit = -1LL; } else if (numArgs == 1) { if (EnvArgTypeCheck(theEnv,"run",1,INTEGER,&argPtr) == FALSE) return; @@ -851,6 +1038,16 @@ globle void HaltCommand( void *theEnv) { EnvArgCountCheck(theEnv,"halt",EXACTLY,0); + EnvHalt(theEnv); + } + +/*****************************/ +/* EnvHalt: C access routine */ +/* for the halt command. */ +/*****************************/ +globle void EnvHalt( + void *theEnv) + { EngineData(theEnv)->HaltRules = TRUE; } @@ -860,14 +1057,11 @@ globle void HaltCommand( /* EnvSetBreak: C access routine */ /* for the set-break command. */ /*********************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetBreak( void *theEnv, void *theRule) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif struct defrule *thePtr; @@ -882,14 +1076,11 @@ globle void EnvSetBreak( /* EnvRemoveBreak: C access routine */ /* for the remove-break command. */ /************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvRemoveBreak( void *theEnv, void *theRule) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif struct defrule *thePtr; @@ -932,12 +1123,12 @@ globle void RemoveAllBreakpoints( /***********************************/ globle void EnvShowBreaks( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheModule) { ListItemsDriver(theEnv,logicalName,(struct defmodule *) vTheModule, NULL,NULL, - EnvGetNextDefrule,(char *(*)(void *)) GetConstructNameString, + EnvGetNextDefrule,(const char *(*)(void *)) GetConstructNameString, NULL,EnvDefruleHasBreakpoint); } @@ -945,14 +1136,11 @@ globle void EnvShowBreaks( /* EnvDefruleHasBreakpoint: Indicates whether */ /* the specified rule has a breakpoint set. */ /**********************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool EnvDefruleHasBreakpoint( void *theEnv, void *theRule) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -967,7 +1155,7 @@ globle void SetBreakCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; void *defrulePtr; if (EnvArgCountCheck(theEnv,"set-break",EXACTLY,1) == -1) return; @@ -993,7 +1181,7 @@ globle void RemoveBreakCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; int nargs; void *defrulePtr; @@ -1065,7 +1253,7 @@ globle void ListFocusStackCommand( /***************************************/ globle void EnvListFocusStack( void *theEnv, - char *logicalName) + const char *logicalName) { struct focus *theFocus; @@ -1078,7 +1266,7 @@ globle void EnvListFocusStack( } } -#endif +#endif /* DEBUGGING_FUNCTIONS */ /***********************************************/ /* GetFocusStackFunction: H/L access routine */ @@ -1201,7 +1389,7 @@ globle int FocusCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; struct defmodule *theModule; int argCount, i; @@ -1265,8 +1453,8 @@ globle void EnvSetFocusChanged( globle void EnvSetHaltRules( void *theEnv, intBool value) - { - EngineData(theEnv)->HaltRules = value; + { + EngineData(theEnv)->HaltRules = value; } /****************************************************/ @@ -1278,5 +1466,139 @@ globle intBool EnvGetHaltRules( return(EngineData(theEnv)->HaltRules); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool AddBeforeRunFunction( + const char *name, + void (*functionPtr)(void *), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + EngineData(theEnv)->ListOfBeforeRunFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority,(void (*)(void *,void *)) functionPtr, + EngineData(theEnv)->ListOfBeforeRunFunctions,TRUE); + return(1); + } + +globle intBool AddRunFunction( + const char *name, + void (*functionPtr)(void), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + EngineData(theEnv)->ListOfRunFunctions = + AddFunctionToCallList(theEnv,name,priority,(void (*)(void *)) functionPtr, + EngineData(theEnv)->ListOfRunFunctions,TRUE); + return(1); + } + +globle void ClearFocusStack() + { + EnvClearFocusStack(GetCurrentEnvironment()); + } + +globle void Focus( + void *vTheModule) + { + EnvFocus(GetCurrentEnvironment(),vTheModule); + } + +globle void GetFocusStack( + DATA_OBJECT_PTR returnValue) + { + EnvGetFocusStack(GetCurrentEnvironment(),returnValue); + } + +globle void *GetFocus() + { + return EnvGetFocus(GetCurrentEnvironment()); + } + +globle int GetFocusChanged() + { + return EnvGetFocusChanged(GetCurrentEnvironment()); + } + +globle void *GetNextFocus( + void *theFocus) + { + return EnvGetNextFocus(GetCurrentEnvironment(),theFocus); + } + +globle void Halt() + { + EnvHalt(GetCurrentEnvironment()); + } + +globle void *PopFocus() + { + return EnvPopFocus(GetCurrentEnvironment()); + } + +globle intBool RemoveRunFunction( + const char *name) + { + return EnvRemoveRunFunction(GetCurrentEnvironment(),name); + } + +globle long long Run( + long long runLimit) + { + return EnvRun(GetCurrentEnvironment(),runLimit); + } + +globle void SetFocusChanged( + int value) + { + EnvSetFocusChanged(GetCurrentEnvironment(),value); + } + +#if DEBUGGING_FUNCTIONS + +globle void ListFocusStack( + const char *logicalName) + { + EnvListFocusStack(GetCurrentEnvironment(),logicalName); + } + +globle intBool DefruleHasBreakpoint( + void *theRule) + { + return EnvDefruleHasBreakpoint(GetCurrentEnvironment(),theRule); + } + +globle intBool RemoveBreak( + void *theRule) + { + return EnvRemoveBreak(GetCurrentEnvironment(),theRule); + } + +globle void SetBreak( + void *theRule) + { + EnvSetBreak(GetCurrentEnvironment(),theRule); + } + +globle void ShowBreaks( + const char *logicalName, + void *vTheModule) + { + EnvShowBreaks(GetCurrentEnvironment(),logicalName,vTheModule); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFRULE_CONSTRUCT */ diff --git a/src/engine.h b/src/engine.h index 5427b5f..d687455 100644 --- a/src/engine.h +++ b/src/engine.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* ENGINE HEADER FILE */ /*******************************************************/ @@ -16,11 +16,14 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ -/* 6.24: Removed INCREMENTAL_RESET and */ -/* LOGICAL_DEPENDENCIES compilation flag. */ +/* 6.24: Removed DYNAMIC_SALIENCE, INCREMENTAL_RESET, */ +/* and LOGICAL_DEPENDENCIES compilation flags. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ @@ -29,6 +32,31 @@ /* Added EnvGetNextFocus, EnvGetFocusChanged, and */ /* EnvSetFocusChanged functions. */ /* */ +/* 6.30: Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ +/* Added context information for run functions. */ +/* */ +/* Added before rule firing callback function. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added EnvHalt function. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_engine @@ -57,17 +85,19 @@ struct focus struct defruleModule *theDefruleModule; struct focus *next; }; - + #define ENGINE_DATA 18 struct engineData - { + { struct defrule *ExecutingRule; intBool HaltRules; struct joinNode *TheLogicalJoin; + struct partialMatch *TheLogicalBind; struct dependency *UnsupportedDataEntities; int alreadyEntered; struct callFunctionItem *ListOfRunFunctions; + struct callFunctionItemWithArg *ListOfBeforeRunFunctions; struct focus *CurrentFocus; int FocusChanged; #if DEBUGGING_FUNCTIONS @@ -80,14 +110,27 @@ struct engineData struct partialMatch *GlobalLHSBinds; struct partialMatch *GlobalRHSBinds; struct joinNode *GlobalJoin; - struct rdriveinfo *DriveRetractionList; struct partialMatch *GarbagePartialMatches; struct alphaMatch *GarbageAlphaMatches; int AlreadyRunning; +#if DEVELOPER + long leftToRightComparisons; + long rightToLeftComparisons; + long leftToRightSucceeds; + long rightToLeftSucceeds; + long leftToRightLoops; + long rightToLeftLoops; + long findNextConflictingComparisons; + long betaHashHTSkips; + long betaHashListSkips; + long unneededMarkerCompare; +#endif }; #define EngineData(theEnv) ((struct engineData *) GetEnvironmentData(theEnv,ENGINE_DATA)) +#define MAX_PATTERNS_CHECKED 64 + #ifdef LOCALE #undef LOCALE #endif @@ -98,61 +141,23 @@ struct engineData #define LOCALE extern #endif -/**************************************************************/ -/* The GetFocus function is remapped under certain conditions */ -/* because it conflicts with a Windows 3.1 function. */ -/**************************************************************/ -/* -#if ! ((GENERIC || IBM) && WINDOW_INTERFACE) -#define WRGetFocus GetFocus -#endif -*/ -#define MAX_PATTERNS_CHECKED 64 - -#if ENVIRONMENT_API_ONLY -#define ClearFocusStack(theEnv) EnvClearFocusStack(theEnv) -#define DefruleHasBreakpoint(theEnv,a) EnvDefruleHasBreakpoint(theEnv,a) -#define Focus(theEnv,a) EnvFocus(theEnv,a) -#define GetFocus(theEnv) EnvGetFocus(theEnv) -#define GetFocusChanged(theEnv) EnvGetFocusChanged(theEnv) -#define GetFocusStack(theEnv,a) EnvGetFocusStack(theEnv,a) -#define GetNextFocus(theEnv,a) EnvGetNextFocus(theEnv,a) -#define ListFocusStack(theEnv,a) EnvListFocusStack(theEnv,a) -#define PopFocus(theEnv) EnvPopFocus(theEnv) -#define RemoveBreak(theEnv,a) EnvRemoveBreak(theEnv,a) -#define RemoveRunFunction(theEnv,a) EnvRemoveRunFunction(theEnv,a) -#define Run(theEnv,a) EnvRun(theEnv,a) -#define SetBreak(theEnv,a) EnvSetBreak(theEnv,a) -#define SetFocusChanged(theEnv,a) EnvSetFocusChanged(theEnv,a) -#define ShowBreaks(theEnv,a,b) EnvShowBreaks(theEnv,a,b) -#else -#define ClearFocusStack() EnvClearFocusStack(GetCurrentEnvironment()) -#define DefruleHasBreakpoint(a) EnvDefruleHasBreakpoint(GetCurrentEnvironment(),a) -#define Focus(a) EnvFocus(GetCurrentEnvironment(),a) -#define GetFocus() EnvGetFocus(GetCurrentEnvironment()) -#define GetFocusChanged() EnvGetFocusChanged(GetCurrentEnvironment()) -#define GetFocusStack(a) EnvGetFocusStack(GetCurrentEnvironment(),a) -#define GetNextFocus(a) EnvGetNextFocus(GetCurrentEnvironment(),a) -#define ListFocusStack(a) EnvListFocusStack(GetCurrentEnvironment(),a) -#define PopFocus() EnvPopFocus(GetCurrentEnvironment()) -#define RemoveBreak(a) EnvRemoveBreak(GetCurrentEnvironment(),a) -#define RemoveRunFunction(a) EnvRemoveRunFunction(GetCurrentEnvironment(),a) -#define Run(a) EnvRun(GetCurrentEnvironment(),a) -#define SetBreak(a) EnvSetBreak(GetCurrentEnvironment(),a) -#define SetFocusChanged(a) EnvSetFocusChanged(GetCurrentEnvironment(),a) -#define ShowBreaks(a,b) EnvShowBreaks(GetCurrentEnvironment(),a,b) -#endif - - LOCALE intBool EnvAddRunFunction(void *,char *, + LOCALE long long EnvRun(void *,long long); + LOCALE intBool EnvAddRunFunction(void *,const char *, void (*)(void *),int); - LOCALE intBool AddRunFunction(char *,void (*)(void),int); - LOCALE long EnvRun(void *,long); - LOCALE intBool EnvRemoveRunFunction(void *,char *); + LOCALE intBool EnvAddRunFunctionWithContext(void *,const char *, + void (*)(void *),int,void *); + LOCALE intBool EnvRemoveRunFunction(void *,const char *); + LOCALE intBool EnvAddBeforeRunFunction(void *,const char *, + void (*)(void *,void *),int); + LOCALE intBool EnvAddBeforeRunFunctionWithContext(void *,const char *, + void (*)(void *, void *),int,void *); + LOCALE intBool EnvRemoveBeforeRunFunction(void *,const char *); LOCALE void InitializeEngine(void *); LOCALE void EnvSetBreak(void *,void *); + LOCALE void EnvHalt(void *); LOCALE intBool EnvRemoveBreak(void *,void *); LOCALE void RemoveAllBreakpoints(void *); - LOCALE void EnvShowBreaks(void *,char *,void *); + LOCALE void EnvShowBreaks(void *,const char *,void *); LOCALE intBool EnvDefruleHasBreakpoint(void *,void *); LOCALE void RunCommand(void *); LOCALE void SetBreakCommand(void *); @@ -167,7 +172,7 @@ struct engineData LOCALE int EnvGetFocusChanged(void *); LOCALE void EnvSetFocusChanged(void *,int); LOCALE void ListFocusStackCommand(void *); - LOCALE void EnvListFocusStack(void *,char *); + LOCALE void EnvListFocusStack(void *,const char *); LOCALE void GetFocusStackFunction(void *,DATA_OBJECT_PTR); LOCALE void EnvGetFocusStack(void *,DATA_OBJECT_PTR); LOCALE void *PopFocusFunction(void *); @@ -176,9 +181,35 @@ struct engineData LOCALE void *EnvGetFocus(void *); LOCALE intBool EnvGetHaltRules(void *); LOCALE void EnvSetHaltRules(void *,intBool); - + LOCALE struct activation *NextActivationToFire(void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool AddBeforeRunFunction(const char *,void (*)(void *),int); + LOCALE intBool AddRunFunction(const char *,void (*)(void),int); + LOCALE void ClearFocusStack(void); + LOCALE void Focus(void *); + LOCALE void GetFocusStack(DATA_OBJECT_PTR); + LOCALE void *GetFocus(void); + LOCALE int GetFocusChanged(void); + LOCALE void *GetNextFocus(void *); + LOCALE void Halt(void); + LOCALE void *PopFocus(void); + LOCALE intBool RemoveRunFunction(const char *); + LOCALE long long Run(long long); + LOCALE void SetFocusChanged(int); +#if DEBUGGING_FUNCTIONS + LOCALE intBool DefruleHasBreakpoint(void *); + LOCALE void ListFocusStack(const char *); + LOCALE intBool RemoveBreak(void *); + LOCALE void SetBreak(void *); + LOCALE void ShowBreaks(const char *,void *); #endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_engine */ + diff --git a/src/envrnmnt.c b/src/envrnmnt.c index 2b91818..33ef591 100644 --- a/src/envrnmnt.c +++ b/src/envrnmnt.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* ENVIRONMENT MODULE */ /*******************************************************/ @@ -29,6 +29,21 @@ /* environment is created (i.e a pointer from the */ /* CLIPS environment to its parent environment). */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions and callback */ +/* functions. */ +/* */ +/* Support for hashing EXTERNAL_ADDRESS data */ +/* type. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Removed deallocating message parameter from */ +/* EnvReleaseMem. */ +/* */ +/* Removed support for BLOCK_MEMORY. */ +/* */ /*************************************************************/ #define _ENVRNMNT_SOURCE_ @@ -62,7 +77,8 @@ #endif static void RemoveEnvironmentCleanupFunctions(struct environmentData *); static void *CreateEnvironmentDriver(struct symbolHashNode **,struct floatHashNode **, - struct integerHashNode **,struct bitMapHashNode **); + struct integerHashNode **,struct bitMapHashNode **, + struct externalAddressHashNode **); /***************************************/ /* LOCAL INTERNAL VARIABLE DEFINITIONS */ @@ -83,62 +99,62 @@ globle intBool AllocateEnvironmentData( unsigned int position, unsigned long size, void (*cleanupFunction)(void *)) - { + { struct environmentData *theEnvironment = (struct environmentData *) vtheEnvironment; /*===========================================*/ /* Environment data can't be of length zero. */ /*===========================================*/ - + if (size <= 0) { - printf("\n[ENVRNMNT1] Environment data position %d allocated with size of 0 or less.\n",position); + printf("\n[ENVRNMNT1] Environment data position %d allocated with size of 0 or less.\n",position); return(FALSE); } - + /*================================================================*/ /* Check to see if the data position exceeds the maximum allowed. */ /*================================================================*/ - + if (position >= MAXIMUM_ENVIRONMENT_POSITIONS) { - printf("\n[ENVRNMNT2] Environment data position %d exceeds the maximum allowed.\n",position); + printf("\n[ENVRNMNT2] Environment data position %d exceeds the maximum allowed.\n",position); return(FALSE); } - + /*============================================================*/ /* Check if the environment data has already been registered. */ /*============================================================*/ - + if (theEnvironment->theData[position] != NULL) { - printf("\n[ENVRNMNT3] Environment data position %d already allocated.\n",position); + printf("\n[ENVRNMNT3] Environment data position %d already allocated.\n",position); return(FALSE); } - + /*====================*/ /* Allocate the data. */ /*====================*/ - + theEnvironment->theData[position] = malloc(size); if (theEnvironment->theData[position] == NULL) { - printf("\n[ENVRNMNT4] Environment data position %d could not be allocated.\n",position); + printf("\n[ENVRNMNT4] Environment data position %d could not be allocated.\n",position); return(FALSE); } - + memset(theEnvironment->theData[position],0,size); - + /*=============================*/ /* Store the cleanup function. */ /*=============================*/ - + theEnvironment->cleanupFunctions[position] = cleanupFunction; - + /*===============================*/ /* Data successfully registered. */ /*===============================*/ - + return(TRUE); } @@ -152,7 +168,7 @@ globle intBool DeallocateEnvironmentData() #if ALLOW_ENVIRONMENT_GLOBALS struct environmentData *theEnvironment, *nextEnvironment; int i, rv = TRUE; - + for (i = 0; i < SIZE_ENVIRONMENT_HASH; i++) { for (theEnvironment = EnvironmentHashTable[i]; @@ -160,16 +176,16 @@ globle intBool DeallocateEnvironmentData() ) { nextEnvironment = theEnvironment->next; - + if (! DestroyEnvironment(theEnvironment)) { rv = FALSE; } - + theEnvironment = nextEnvironment; } } free(EnvironmentHashTable); - + return(rv); #else return(FALSE); @@ -184,7 +200,7 @@ globle intBool DeallocateEnvironmentData() static void InitializeEnvironmentHashTable() { int i; - + if (EnvironmentHashTable != NULL) { return; } @@ -193,7 +209,7 @@ static void InitializeEnvironmentHashTable() if (EnvironmentHashTable == NULL) { - printf("\n[ENVRNMNT4] Unable to initialize environment hash table.\n"); + printf("\n[ENVRNMNT4] Unable to initialize environment hash table.\n"); return; } @@ -209,17 +225,17 @@ static void AddHashedEnvironment( { struct environmentData *temp; unsigned long hashValue; - + if (EnvironmentHashTable == NULL) { InitializeEnvironmentHashTable(); } - + hashValue = theEnvironment->environmentIndex % SIZE_ENVIRONMENT_HASH; temp = EnvironmentHashTable[hashValue]; EnvironmentHashTable[hashValue] = theEnvironment; theEnvironment->next = temp; } - + /***************************************************/ /* RemoveHashedEnvironment: Removes an environment */ /* entry from the environment hash table. */ @@ -264,9 +280,9 @@ static struct environmentData *FindEnvironment( { struct environmentData *theEnvironment; unsigned long hashValue; - + hashValue = environmentIndex % SIZE_ENVIRONMENT_HASH; - + for (theEnvironment = EnvironmentHashTable[hashValue]; theEnvironment != NULL; theEnvironment = theEnvironment->next) @@ -285,7 +301,7 @@ static struct environmentData *FindEnvironment( /************************************************************/ globle void *CreateEnvironment() { - return CreateEnvironmentDriver(NULL,NULL,NULL,NULL); + return CreateEnvironmentDriver(NULL,NULL,NULL,NULL,NULL); } /**********************************************************/ @@ -298,9 +314,9 @@ globle void *CreateRuntimeEnvironment( struct integerHashNode **integerTable, struct bitMapHashNode **bitmapTable) { - return CreateEnvironmentDriver(symbolTable,floatTable,integerTable,bitmapTable); + return CreateEnvironmentDriver(symbolTable,floatTable,integerTable,bitmapTable,NULL); } - + /*********************************************************/ /* CreateEnvironmentDriver: Creates an environment data */ /* structure and initializes its content to zero/null. */ @@ -309,13 +325,14 @@ globle void *CreateEnvironmentDriver( struct symbolHashNode **symbolTable, struct floatHashNode **floatTable, struct integerHashNode **integerTable, - struct bitMapHashNode **bitmapTable) + struct bitMapHashNode **bitmapTable, + struct externalAddressHashNode **externalAddressTable) { struct environmentData *theEnvironment; void *theData; - + theEnvironment = (struct environmentData *) malloc(sizeof(struct environmentData)); - + if (theEnvironment == NULL) { printf("\n[ENVRNMNT5] Unable to create new environment.\n"); @@ -323,7 +340,7 @@ globle void *CreateEnvironmentDriver( } theData = malloc(sizeof(void *) * MAXIMUM_ENVIRONMENT_POSITIONS); - + if (theData == NULL) { free(theEnvironment); @@ -344,13 +361,15 @@ globle void *CreateEnvironmentDriver( #endif theEnvironment->context = NULL; theEnvironment->routerContext = NULL; + theEnvironment->functionContext = NULL; + theEnvironment->callbackContext = NULL; /*=============================================*/ /* Allocate storage for the cleanup functions. */ /*=============================================*/ theData = malloc(sizeof(void (*)(struct environmentData *)) * MAXIMUM_ENVIRONMENT_POSITIONS); - + if (theData == NULL) { free(theEnvironment->theData); @@ -367,7 +386,7 @@ globle void *CreateEnvironmentDriver( CurrentEnvironment = theEnvironment; #endif - EnvInitializeEnvironment(theEnvironment,symbolTable,floatTable,integerTable,bitmapTable); + EnvInitializeEnvironment(theEnvironment,symbolTable,floatTable,integerTable,bitmapTable,externalAddressTable); return(theEnvironment); } @@ -382,7 +401,7 @@ globle void SetCurrentEnvironment( { CurrentEnvironment = (struct environmentData *) theEnvironment; } - + /**************************************************/ /* SetCurrentEnvironmentByIndex: Sets the current */ /* environment to the one having the specified */ @@ -394,15 +413,15 @@ globle intBool SetCurrentEnvironmentByIndex( struct environmentData *theEnvironment; theEnvironment = FindEnvironment(environmentIndex); - + if (theEnvironment == NULL) { return(FALSE); } - + SetCurrentEnvironment(theEnvironment); - + return(TRUE); - } - + } + /**************************************************/ /* GetEnvironmentByIndex: Returns the environment */ /* having the specified environment index. */ @@ -413,10 +432,10 @@ globle void *GetEnvironmentByIndex( struct environmentData *theEnvironment; theEnvironment = FindEnvironment(environmentIndex); - + return(theEnvironment); - } - + } + /********************************************/ /* GetCurrentEnvironment: Returns a pointer */ /* to the current environment. */ @@ -424,8 +443,8 @@ globle void *GetEnvironmentByIndex( globle void *GetCurrentEnvironment() { return(CurrentEnvironment); - } - + } + /******************************************/ /* GetEnvironmentIndex: Returns the index */ /* of the specified environment. */ @@ -434,8 +453,8 @@ globle unsigned long GetEnvironmentIndex( void *theEnvironment) { return(((struct environmentData *) theEnvironment)->environmentIndex); - } - + } + #endif /**********************************************/ @@ -446,7 +465,7 @@ globle void *GetEnvironmentContext( void *theEnvironment) { return(((struct environmentData *) theEnvironment)->context); - } + } /*******************************************/ /* SetEnvironmentContext: Sets the context */ @@ -457,13 +476,13 @@ globle void *SetEnvironmentContext( void *theContext) { void *oldContext; - + oldContext = ((struct environmentData *) theEnvironment)->context; - + ((struct environmentData *) theEnvironment)->context = theContext; - + return oldContext; - } + } /***************************************************/ /* GetEnvironmentRouterContext: Returns the router */ @@ -473,7 +492,7 @@ globle void *GetEnvironmentRouterContext( void *theEnvironment) { return(((struct environmentData *) theEnvironment)->routerContext); - } + } /************************************************/ /* SetEnvironmentRouterContext: Sets the router */ @@ -484,13 +503,67 @@ globle void *SetEnvironmentRouterContext( void *theRouterContext) { void *oldRouterContext; - + oldRouterContext = ((struct environmentData *) theEnvironment)->routerContext; - + ((struct environmentData *) theEnvironment)->routerContext = theRouterContext; - + return oldRouterContext; - } + } + +/*******************************************************/ +/* GetEnvironmentFunctionContext: Returns the function */ +/* context of the specified environment. */ +/*******************************************************/ +globle void *GetEnvironmentFunctionContext( + void *theEnvironment) + { + return(((struct environmentData *) theEnvironment)->functionContext); + } + +/**************************************************/ +/* SetEnvironmentFunctionContext: Sets the router */ +/* context of the specified environment. */ +/**************************************************/ +globle void *SetEnvironmentFunctionContext( + void *theEnvironment, + void *theFunctionContext) + { + void *oldFunctionContext; + + oldFunctionContext = ((struct environmentData *) theEnvironment)->functionContext; + + ((struct environmentData *) theEnvironment)->functionContext = theFunctionContext; + + return oldFunctionContext; + } + +/*******************************************************/ +/* GetEnvironmentCallbackContext: Returns the callback */ +/* context of the specified environment. */ +/*******************************************************/ +globle void *GetEnvironmentCallbackContext( + void *theEnvironment) + { + return(((struct environmentData *) theEnvironment)->callbackContext); + } + +/****************************************************/ +/* SetEnvironmentCallbackContext: Sets the callback */ +/* context of the specified environment. */ +/****************************************************/ +globle void *SetEnvironmentCallbackContext( + void *theEnvironment, + void *theCallbackContext) + { + void *oldCallbackContext; + + oldCallbackContext = ((struct environmentData *) theEnvironment)->callbackContext; + + ((struct environmentData *) theEnvironment)->callbackContext = theCallbackContext; + + return oldCallbackContext; + } /**********************************************/ /* DestroyEnvironment: Destroys the specified */ @@ -498,58 +571,58 @@ globle void *SetEnvironmentRouterContext( /**********************************************/ globle intBool DestroyEnvironment( void *vtheEnvironment) - { + { struct environmentCleanupFunction *cleanupPtr; int i; struct memoryData *theMemData; intBool rv = TRUE; struct environmentData *theEnvironment = (struct environmentData *) vtheEnvironment; - + /* if (EvaluationData(theEnvironment)->CurrentExpression != NULL) { return(FALSE); } - + #if DEFRULE_CONSTRUCT if (EngineData(theEnvironment)->ExecutingRule != NULL) { return(FALSE); } #endif - +*/ theMemData = MemoryData(theEnvironment); - EnvReleaseMem(theEnvironment,-1,FALSE); + EnvReleaseMem(theEnvironment,-1); for (i = 0; i < MAXIMUM_ENVIRONMENT_POSITIONS; i++) { if (theEnvironment->cleanupFunctions[i] != NULL) { (*theEnvironment->cleanupFunctions[i])(theEnvironment); } } - + free(theEnvironment->cleanupFunctions); - + for (cleanupPtr = theEnvironment->listOfCleanupEnvironmentFunctions; cleanupPtr != NULL; cleanupPtr = cleanupPtr->next) { (*cleanupPtr->func)(theEnvironment); } RemoveEnvironmentCleanupFunctions(theEnvironment); - - EnvReleaseMem(theEnvironment,-1,FALSE); + + EnvReleaseMem(theEnvironment,-1); #if ALLOW_ENVIRONMENT_GLOBALS RemoveHashedEnvironment(theEnvironment); #endif - + if ((theMemData->MemoryAmount != 0) || (theMemData->MemoryCalls != 0)) { - printf("\n[ENVRNMNT8] Environment data not fully deallocated.\n"); - rv = FALSE; + printf("\n[ENVRNMNT8] Environment data not fully deallocated.\n"); + printf("\n[ENVRNMNT8] MemoryAmount = %ld.\n",(long) theMemData->MemoryAmount); + printf("\n[ENVRNMNT8] MemoryCalls = %ld.\n",(long) theMemData->MemoryCalls); + rv = FALSE; } - - free(theMemData->MemoryTable); -#if BLOCK_MEMORY - ReturnAllBlocks(theEnvironment); +#if (MEM_TABLE_SIZE > 0) + free(theMemData->MemoryTable); #endif - + for (i = 0; i < MAXIMUM_ENVIRONMENT_POSITIONS; i++) { if (theEnvironment->theData[i] != NULL) @@ -558,32 +631,32 @@ globle intBool DestroyEnvironment( theEnvironment->theData[i] = NULL; } } - + free(theEnvironment->theData); - + #if ALLOW_ENVIRONMENT_GLOBALS if (CurrentEnvironment == theEnvironment) { CurrentEnvironment = NULL; } #endif free(theEnvironment); - + return(rv); - } - + } + /**************************************************/ /* AddEnvironmentCleanupFunction: Adds a function */ /* to the ListOfCleanupEnvironmentFunctions. */ /**************************************************/ globle intBool AddEnvironmentCleanupFunction( void *vtheEnv, - char *name, + const char *name, void (*functionPtr)(void *), int priority) { struct environmentCleanupFunction *newPtr, *currentPtr, *lastPtr = NULL; struct environmentData *theEnv = (struct environmentData *) vtheEnv; - + newPtr = (struct environmentCleanupFunction *) malloc(sizeof(struct environmentCleanupFunction)); if (newPtr == NULL) { return(FALSE); } @@ -616,7 +689,7 @@ globle intBool AddEnvironmentCleanupFunction( newPtr->next = currentPtr; lastPtr->next = newPtr; } - + return(TRUE); } @@ -626,13 +699,13 @@ globle intBool AddEnvironmentCleanupFunction( /**************************************************/ static void RemoveEnvironmentCleanupFunctions( struct environmentData *theEnv) - { + { struct environmentCleanupFunction *nextPtr; - + while (theEnv->listOfCleanupEnvironmentFunctions != NULL) - { + { nextPtr = theEnv->listOfCleanupEnvironmentFunctions->next; free(theEnv->listOfCleanupEnvironmentFunctions); theEnv->listOfCleanupEnvironmentFunctions = nextPtr; } - } + } diff --git a/src/envrnmnt.h b/src/envrnmnt.h index 37d9bfb..03dc402 100644 --- a/src/envrnmnt.h +++ b/src/envrnmnt.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* ENVRNMNT HEADER FILE */ /*******************************************************/ @@ -14,7 +14,14 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Added code to CreateEnvironment to free */ +/* already allocated data if one of the malloc */ +/* calls fail. */ +/* */ +/* Modified AllocateEnvironmentData to print a */ +/* message if it was unable to allocate memory. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ /* */ /* Added CreateRuntimeEnvironment function. */ /* */ @@ -22,6 +29,16 @@ /* environment is created (i.e a pointer from the */ /* CLIPS environment to its parent environment). */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions and callback */ +/* functions. */ +/* */ +/* Support for hashing EXTERNAL_ADDRESS data */ +/* type. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_envrnmnt @@ -46,18 +63,20 @@ struct environmentCleanupFunction { - char *name; + const char *name; void (*func)(void *); int priority; struct environmentCleanupFunction *next; }; struct environmentData - { + { unsigned int initialized : 1; unsigned long environmentIndex; void *context; void *routerContext; + void *functionContext; + void *callbackContext; void **theData; void (**cleanupFunctions)(void *); struct environmentCleanupFunction *listOfCleanupEnvironmentFunctions; @@ -83,11 +102,15 @@ typedef struct environmentData * ENVIRONMENT_DATA_PTR; LOCALE void *CreateRuntimeEnvironment(struct symbolHashNode **,struct floatHashNode **, struct integerHashNode **,struct bitMapHashNode **); LOCALE intBool DestroyEnvironment(void *); - LOCALE intBool AddEnvironmentCleanupFunction(void *,char *,void (*)(void *),int); + LOCALE intBool AddEnvironmentCleanupFunction(void *,const char *,void (*)(void *),int); LOCALE void *GetEnvironmentContext(void *); LOCALE void *SetEnvironmentContext(void *,void *); LOCALE void *GetEnvironmentRouterContext(void *); LOCALE void *SetEnvironmentRouterContext(void *,void *); + LOCALE void *GetEnvironmentFunctionContext(void *); + LOCALE void *SetEnvironmentFunctionContext(void *,void *); + LOCALE void *GetEnvironmentCallbackContext(void *); + LOCALE void *SetEnvironmentCallbackContext(void *,void *); -#endif +#endif /* _H_envrnmnt */ diff --git a/src/evaluatn.c b/src/evaluatn.c index 3f205f5..9643ca2 100644 --- a/src/evaluatn.c +++ b/src/evaluatn.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* EVALUATION MODULE */ /*******************************************************/ @@ -13,15 +13,35 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ /* Added EvaluateAndStoreInDataObject function. */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions. */ +/* */ +/* Added support for external address hash table */ +/* and subtyping. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Support for DATA_OBJECT_ARRAY primitive. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _EVALUATN_SOURCE_ @@ -34,6 +54,7 @@ #include "setup.h" +#include "argacces.h" #include "commline.h" #include "constant.h" #include "envrnmnt.h" @@ -59,6 +80,7 @@ #if OBJECT_SYSTEM #include "object.h" +#include "inscom.h" #endif #include "evaluatn.h" @@ -67,7 +89,12 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void PropagateReturnAtom(void *,int,void *); + static void DeallocateEvaluationData(void *); + static void PrintCAddress(void *,const char *,void *); + static void NewCAddress(void *,DATA_OBJECT *); + /* + static intBool DiscardCAddress(void *,void *); + */ /**************************************************/ /* InitializeEvaluationData: Allocates environment */ @@ -76,7 +103,24 @@ globle void InitializeEvaluationData( void *theEnv) { - AllocateEnvironmentData(theEnv,EVALUATION_DATA,sizeof(struct evaluationData),NULL); + struct externalAddressType cPointer = { "C", PrintCAddress, PrintCAddress, NULL, NewCAddress, NULL }; + + AllocateEnvironmentData(theEnv,EVALUATION_DATA,sizeof(struct evaluationData),DeallocateEvaluationData); + + InstallExternalAddressType(theEnv,&cPointer); + } + +/*****************************************************/ +/* DeallocateEvaluationData: Deallocates environment */ +/* data for evaluation data. */ +/*****************************************************/ +static void DeallocateEvaluationData( + void *theEnv) + { + int i; + + for (i = 0; i < EvaluationData(theEnv)->numberOfAddressTypes; i++) + { rtn_struct(theEnv,externalAddressType,EvaluationData(theEnv)->ExternalAddressTypes[i]); } } /**************************************************************/ @@ -89,6 +133,7 @@ globle int EvaluateExpression( DATA_OBJECT_PTR returnValue) { struct expr *oldArgument; + void *oldContext; struct FunctionDefinition *fptr; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; @@ -116,9 +161,15 @@ globle int EvaluateExpression( returnValue->value = problem->value; break; + case DATA_OBJECT_ARRAY: /* TBD Remove with AddPrimitive */ + returnValue->type = problem->type; + returnValue->value = problem->value; + break; + case FCALL: { fptr = (struct FunctionDefinition *) problem->value; + oldContext = SetEnvironmentFunctionContext(theEnv,fptr->context); #if PROFILING_FUNCTIONS StartProfile(theEnv,&profileFrame, @@ -169,17 +220,30 @@ globle int EvaluateExpression( (* (void *(*)(void)) fptr->functionPointer)(); } break; + case 'g' : + returnValue->type = INTEGER; + if (fptr->environmentAware) + { + returnValue->value = (void *) + EnvAddLong(theEnv,(* (long long (*)(void *)) fptr->functionPointer)(theEnv)); + } + else + { + returnValue->value = (void *) + EnvAddLong(theEnv,(* (long long (*)(void)) fptr->functionPointer)()); + } + break; case 'i' : returnValue->type = INTEGER; if (fptr->environmentAware) { returnValue->value = (void *) - EnvAddLong(theEnv,(long) (* (int (*)(void *)) fptr->functionPointer)(theEnv)); + EnvAddLong(theEnv,(long long) (* (int (*)(void *)) fptr->functionPointer)(theEnv)); } else { returnValue->value = (void *) - EnvAddLong(theEnv,(long) (* (int (*)(void)) fptr->functionPointer)()); + EnvAddLong(theEnv,(long long) (* (int (*)(void)) fptr->functionPointer)()); } break; case 'l' : @@ -187,12 +251,12 @@ globle int EvaluateExpression( if (fptr->environmentAware) { returnValue->value = (void *) - EnvAddLong(theEnv,(* (long int (*)(void *)) fptr->functionPointer)(theEnv)); + EnvAddLong(theEnv,(long long) (* (long int (*)(void *)) fptr->functionPointer)(theEnv)); } else { returnValue->value = (void *) - EnvAddLong(theEnv,(* (long int (*)(void)) fptr->functionPointer)()); + EnvAddLong(theEnv,(long long) (* (long int (*)(void)) fptr->functionPointer)()); } break; case 'f' : @@ -260,6 +324,9 @@ globle int EvaluateExpression( returnValue->value = (* (void *(*)(void)) fptr->functionPointer)(); } + if (returnValue->value == NULL) + { returnValue->value = (void *) &InstanceData(theEnv)->DummyInstance; } + break; case 'o' : returnValue->type = INSTANCE_NAME; @@ -275,6 +342,26 @@ globle int EvaluateExpression( } break; #endif + +#if DEFTEMPLATE_CONSTRUCT + case 'y' : + returnValue->type = FACT_ADDRESS; + if (fptr->environmentAware) + { + returnValue->value = + (* (void *(*)(void *)) fptr->functionPointer)(theEnv); + } + else + { + returnValue->value = + (* (void *(*)(void)) fptr->functionPointer)(); + } + if (returnValue->value == NULL) + { returnValue->value = (void *) &FactData(theEnv)->DummyFact; } + + break; +#endif + case 'c' : { char cbuff[2]; @@ -317,6 +404,7 @@ globle int EvaluateExpression( EndProfile(theEnv,&profileFrame); #endif + SetEnvironmentFunctionContext(theEnv,oldContext); EvaluationData(theEnv)->CurrentExpression = oldArgument; break; } @@ -381,7 +469,6 @@ globle int EvaluateExpression( break; } - PropagateReturnValue(theEnv,returnValue); return(EvaluationData(theEnv)->EvaluationError); } @@ -404,6 +491,31 @@ globle void InstallPrimitive( } /******************************************************/ +/* InstallExternalAddressType: Installs an external */ +/* address type in the external address type array. */ +/******************************************************/ +globle int InstallExternalAddressType( + void *theEnv, + struct externalAddressType *theAddressType) + { + struct externalAddressType *copyEAT; + + int rv = EvaluationData(theEnv)->numberOfAddressTypes; + + if (EvaluationData(theEnv)->numberOfAddressTypes == MAXIMUM_EXTERNAL_ADDRESS_TYPES) + { + SystemError(theEnv,"EVALUATN",6); + EnvExitRouter(theEnv,EXIT_FAILURE); + } + + copyEAT = (struct externalAddressType *) genalloc(theEnv,sizeof(struct externalAddressType)); + memcpy(copyEAT,theAddressType,sizeof(struct externalAddressType)); + EvaluationData(theEnv)->ExternalAddressTypes[EvaluationData(theEnv)->numberOfAddressTypes++] = copyEAT; + + return rv; + } + +/******************************************************/ /* SetEvaluationError: Sets the EvaluationError flag. */ /******************************************************/ globle void SetEvaluationError( @@ -449,7 +561,8 @@ globle int GetHaltExecution( /******************************************************/ globle void ReturnValues( void *theEnv, - DATA_OBJECT_PTR garbagePtr) + DATA_OBJECT_PTR garbagePtr, + intBool decrementSupplementalInfo) { DATA_OBJECT_PTR nextPtr; @@ -457,6 +570,8 @@ globle void ReturnValues( { nextPtr = garbagePtr->next; ValueDeinstall(theEnv,garbagePtr); + if ((garbagePtr->supplementalInfo != NULL) && decrementSupplementalInfo) + { DecrementSymbolCount(theEnv,(struct symbolHashNode *) garbagePtr->supplementalInfo); } rtn_struct(theEnv,dataObject,garbagePtr); garbagePtr = nextPtr; } @@ -468,7 +583,7 @@ globle void ReturnValues( /***************************************************/ globle void PrintDataObject( void *theEnv, - char *fileid, + const char *fileid, DATA_OBJECT_PTR argPtr) { switch(argPtr->type) @@ -479,6 +594,7 @@ globle void PrintDataObject( case INTEGER: case FLOAT: case EXTERNAL_ADDRESS: + case DATA_OBJECT_ARRAY: // TBD Remove with AddPrimitive case FACT_ADDRESS: #if OBJECT_SYSTEM case INSTANCE_NAME: @@ -486,6 +602,7 @@ globle void PrintDataObject( #endif PrintAtom(theEnv,fileid,argPtr->type,argPtr->value); break; + case MULTIFIELD: PrintMultifield(theEnv,fileid,(struct multifield *) argPtr->value, argPtr->begin,argPtr->end,TRUE); @@ -583,6 +700,10 @@ globle void AtomInstall( IncrementIntegerCount(vPtr); break; + case EXTERNAL_ADDRESS: + IncrementExternalAddressCount(vPtr); + break; + case MULTIFIELD: MultifieldInstall(theEnv,(struct multifield *) vPtr); break; @@ -629,6 +750,10 @@ globle void AtomDeinstall( DecrementIntegerCount(theEnv,(INTEGER_HN *) vPtr); break; + case EXTERNAL_ADDRESS: + DecrementExternalAddressCount(theEnv,(EXTERNAL_ADDRESS_HN *) vPtr); + break; + case MULTIFIELD: MultifieldDeinstall(theEnv,(struct multifield *) vPtr); break; @@ -644,77 +769,6 @@ globle void AtomDeinstall( } } -/*********************************************************************/ -/* PropagateReturnValue: Decrements the associated depth for a value */ -/* stored in a DATA_OBJECT structure. In effect, the values */ -/* returned by certain evaluations (such as a deffunction call) */ -/* are passed up to the previous depth of evaluation. The return */ -/* value's depth is decremented so that it will not be garbage */ -/* collected along with other items that are no longer needed from */ -/* the evaluation that generated the return value. */ -/*********************************************************************/ -globle void PropagateReturnValue( - void *theEnv, - DATA_OBJECT *vPtr) - { - unsigned long i; /* 6.04 Bug Fix */ - struct multifield *theSegment; - struct field *theMultifield; - - if (vPtr->type != MULTIFIELD) - { PropagateReturnAtom(theEnv,vPtr->type,vPtr->value); } - else - { - theSegment = (struct multifield *) vPtr->value; - - if (theSegment->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) - theSegment->depth = (short) EvaluationData(theEnv)->CurrentEvaluationDepth; - - theMultifield = theSegment->theFields; - - for (i = 0; i < theSegment->multifieldLength; i++) - { PropagateReturnAtom(theEnv,theMultifield[i].type,theMultifield[i].value); } - } - } - -/*****************************************/ -/* PropagateReturnAtom: Support function */ -/* for PropagateReturnValue. */ -/*****************************************/ -static void PropagateReturnAtom( - void *theEnv, - int type, - void *value) - { - switch (type) - { - case INTEGER : - case FLOAT : - case SYMBOL : - case STRING : -#if OBJECT_SYSTEM - case INSTANCE_NAME : -#endif - if (((SYMBOL_HN *) value)->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) - { ((SYMBOL_HN *) value)->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; } - break; - -#if OBJECT_SYSTEM - case INSTANCE_ADDRESS : - if (((INSTANCE_TYPE *) value)->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) - { ((INSTANCE_TYPE *) value)->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; } - break; -#endif - case FACT_ADDRESS : - if (((int) ((struct fact *) value)->depth) > EvaluationData(theEnv)->CurrentEvaluationDepth) - { ((struct fact *) value)->depth = (unsigned) EvaluationData(theEnv)->CurrentEvaluationDepth; } - break; - - default: - break; - } - } - #if DEFFUNCTION_CONSTRUCT || DEFGENERIC_CONSTRUCT /********************************************/ @@ -724,8 +778,8 @@ static void PropagateReturnAtom( /********************************************/ globle int EnvFunctionCall( void *theEnv, - char *name, - char *args, + const char *name, + const char *args, DATA_OBJECT *result) { FUNCTION_REFERENCE theReference; @@ -758,7 +812,7 @@ globle int EnvFunctionCall( globle int FunctionCall2( void *theEnv, FUNCTION_REFERENCE *theReference, - char *args, + const char *args, DATA_OBJECT *result) { EXPRESSION *argexps; @@ -769,15 +823,18 @@ globle int FunctionCall2( /* was executed from an embedded application. */ /*=============================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*========================*/ /* Reset the error state. */ /*========================*/ - if (EvaluationData(theEnv)->CurrentEvaluationDepth == 0) SetHaltExecution(theEnv,FALSE); + if (UtilityData(theEnv)->CurrentGarbageFrame->topLevel) SetHaltExecution(theEnv,FALSE); EvaluationData(theEnv)->EvaluationError = FALSE; /*======================================*/ @@ -892,35 +949,44 @@ globle struct expr *ConvertValueToExpression( /* GetAtomicHashValue: Returns the hash */ /* value for an atomic data type. */ /****************************************/ -unsigned int GetAtomicHashValue( +unsigned long GetAtomicHashValue( unsigned short type, void *value, int position) { - unsigned int tvalue; + unsigned long tvalue; union { double fv; - unsigned int liv; + void *vv; + unsigned long liv; } fis; switch (type) { case FLOAT: + fis.liv = 0; fis.fv = ValueToDouble(value); tvalue = fis.liv; break; case INTEGER: - tvalue = (unsigned int) ValueToLong(value); + tvalue = (unsigned long) ValueToLong(value); break; + case EXTERNAL_ADDRESS: + fis.liv = 0; + fis.vv = ValueToExternalAddress(value); + tvalue = (unsigned long) fis.liv; + break; + case FACT_ADDRESS: #if OBJECT_SYSTEM case INSTANCE_ADDRESS: #endif - case EXTERNAL_ADDRESS: - tvalue = (unsigned int) value; + fis.liv = 0; + fis.vv = value; + tvalue = (unsigned long) fis.liv; break; case STRING: @@ -937,7 +1003,7 @@ unsigned int GetAtomicHashValue( if (position < 0) return(tvalue); - return((unsigned int) (tvalue * (position + 29))); + return((unsigned long) (tvalue * (((unsigned long) position) + 29))); } /***********************************************************/ @@ -948,7 +1014,7 @@ unsigned int GetAtomicHashValue( /***********************************************************/ globle struct expr *FunctionReferenceExpression( void *theEnv, - char *name) + const char *name) { #if DEFGENERIC_CONSTRUCT void *gfunc; @@ -1000,7 +1066,7 @@ globle struct expr *FunctionReferenceExpression( /******************************************************************/ globle intBool GetFunctionReference( void *theEnv, - char *name, + const char *name, FUNCTION_REFERENCE *theReference) { #if DEFGENERIC_CONSTRUCT @@ -1125,3 +1191,79 @@ globle int EvaluateAndStoreInDataObject( return(EvaluationData(theEnv)->EvaluationError ? FALSE : TRUE); } +/*******************************************************/ +/* PrintCAddress: */ +/*******************************************************/ +static void PrintCAddress( + void *theEnv, + const char *logicalName, + void *theValue) + { + char buffer[20]; + + EnvPrintRouter(theEnv,logicalName,"<Pointer-C-"); + + gensprintf(buffer,"%p",ValueToExternalAddress(theValue)); + EnvPrintRouter(theEnv,logicalName,buffer); + EnvPrintRouter(theEnv,logicalName,">"); + } + +/****************/ +/* NewCAddress: */ +/****************/ +static void NewCAddress( + void *theEnv, + DATA_OBJECT *rv) + { + int numberOfArguments; + + numberOfArguments = EnvRtnArgCount(theEnv); + + if (numberOfArguments != 1) + { + PrintErrorID(theEnv,"NEW",1,FALSE); + EnvPrintRouter(theEnv,WERROR,"Function new expected no additional arguments for the C external language type.\n"); + SetEvaluationError(theEnv,TRUE); + return; + } + + SetpType(rv,EXTERNAL_ADDRESS); + SetpValue(rv,EnvAddExternalAddress(theEnv,NULL,0)); + } + +/*******************************************************/ +/* DiscardCAddress: TBD Remove */ +/*******************************************************/ +/* +static intBool DiscardCAddress( + void *theEnv, + void *theValue) + { + EnvPrintRouter(theEnv,WDISPLAY,"Discarding C Address\n"); + + return TRUE; + } +*/ + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void SetMultifieldErrorValue( + DATA_OBJECT_PTR returnValue) + { + EnvSetMultifieldErrorValue(GetCurrentEnvironment(),returnValue); + } + +globle int FunctionCall( + const char *name, + const char *args, + DATA_OBJECT *result) + { + return EnvFunctionCall(GetCurrentEnvironment(),name,args,result); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + diff --git a/src/evaluatn.h b/src/evaluatn.h index eaac89b..4694611 100644 --- a/src/evaluatn.h +++ b/src/evaluatn.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* EVALUATION HEADER FILE */ /*******************************************************/ @@ -16,10 +16,31 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ /* Added EvaluateAndStoreInDataObject function. */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions. */ +/* */ +/* Added support for external address hash table */ +/* and subtyping. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Support for DATA_OBJECT_ARRAY primitive. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_evaluatn @@ -56,17 +77,19 @@ typedef struct expr FUNCTION_REFERENCE; #define DATA_OBJECT_PTR_ARG DATA_OBJECT_PTR +#define C_POINTER_EXTERNAL_ADDRESS 0 + #include "userdata.h" struct entityRecord { - char *name; + const char *name; unsigned int type : 13; unsigned int copyToEvaluate : 1; unsigned int bitMap : 1; unsigned int addsToRuleComplexity : 1; - void (*shortPrintFunction)(void *,char *,void *); - void (*longPrintFunction)(void *,char *,void *); + void (*shortPrintFunction)(void *,const char *,void *); + void (*longPrintFunction)(void *,const char *,void *); intBool (*deleteFunction)(void *,void *); intBool (*evaluateFunction)(void *,void *,DATA_OBJECT *); void *(*getNextFunction)(void *,void *); @@ -79,6 +102,16 @@ struct entityRecord struct userData *usrData; }; +struct externalAddressType + { + const char *name; + void (*shortPrintFunction)(void *,const char *,void *); + void (*longPrintFunction)(void *,const char *,void *); + intBool (*discardFunction)(void *,void *); + void (*newFunction)(void *,DATA_OBJECT *); + intBool (*callFunction)(void *,DATA_OBJECT *,DATA_OBJECT *); + }; + typedef struct entityRecord ENTITY_RECORD; typedef struct entityRecord * ENTITY_RECORD_PTR; @@ -110,6 +143,7 @@ typedef struct entityRecord * ENTITY_RECORD_PTR; #define DOPToLong(target) (((struct integerHashNode *) ((target)->value))->contents) #define DOPToInteger(target) ((int) (((struct integerHashNode *) ((target)->value))->contents)) #define DOPToPointer(target) ((target)->value) +#define DOPToExternalAddress(target) (((struct externalAddressHashNode *) ((target)->value))->externalAddress) #define EnvDOPToString(theEnv,target) (((struct symbolHashNode *) ((target)->value))->contents) #define EnvDOPToDouble(theEnv,target) (((struct floatHashNode *) ((target)->value))->contents) @@ -117,20 +151,23 @@ typedef struct entityRecord * ENTITY_RECORD_PTR; #define EnvDOPToLong(theEnv,target) (((struct integerHashNode *) ((target)->value))->contents) #define EnvDOPToInteger(theEnv,target) ((int) (((struct integerHashNode *) ((target)->value))->contents)) #define EnvDOPToPointer(theEnv,target) ((target)->value) +#define EnvDOPToExternalAddress(target) (((struct externalAddressHashNode *) ((target)->value))->externalAddress) -#define DOToString(target) (((struct symbolHashNode *) (target.value))->contents) -#define DOToDouble(target) (((struct floatHashNode *) (target.value))->contents) -#define DOToFloat(target) ((float) (((struct floatHashNode *) (target.value))->contents)) -#define DOToLong(target) (((struct integerHashNode *) (target.value))->contents) -#define DOToInteger(target) ((int) (((struct integerHashNode *) (target.value))->contents)) +#define DOToString(target) (((struct symbolHashNode *) ((target).value))->contents) +#define DOToDouble(target) (((struct floatHashNode *) ((target).value))->contents) +#define DOToFloat(target) ((float) (((struct floatHashNode *) ((target).value))->contents)) +#define DOToLong(target) (((struct integerHashNode *) ((target).value))->contents) +#define DOToInteger(target) ((int) (((struct integerHashNode *) ((target).value))->contents)) #define DOToPointer(target) ((target).value) +#define DOToExternalAddress(target) (((struct externalAddressHashNode *) ((target).value))->externalAddress) -#define EnvDOToString(theEnv,target) (((struct symbolHashNode *) (target.value))->contents) -#define EnvDOToDouble(theEnv,target) (((struct floatHashNode *) (target.value))->contents) -#define EnvDOToFloat(theEnv,target) ((float) (((struct floatHashNode *) (target.value))->contents)) -#define EnvDOToLong(theEnv,target) (((struct integerHashNode *) (target.value))->contents) -#define EnvDOToInteger(theEnv,target) ((int) (((struct integerHashNode *) (target.value))->contents)) +#define EnvDOToString(theEnv,target) (((struct symbolHashNode *) ((target).value))->contents) +#define EnvDOToDouble(theEnv,target) (((struct floatHashNode *) ((target).value))->contents) +#define EnvDOToFloat(theEnv,target) ((float) (((struct floatHashNode *) ((target).value))->contents)) +#define EnvDOToLong(theEnv,target) (((struct integerHashNode *) ((target).value))->contents) +#define EnvDOToInteger(theEnv,target) ((int) (((struct integerHashNode *) ((target).value))->contents)) #define EnvDOToPointer(theEnv,target) ((target).value) +#define EnvDOToExternalAddress(target) (((struct externalAddressHashNode *) ((target).value))->externalAddress) #define CoerceToLongInteger(t,v) ((t == INTEGER) ? ValueToLong(v) : (long int) ValueToDouble(v)) #define CoerceToInteger(t,v) ((t == INTEGER) ? (int) ValueToLong(v) : (int) ValueToDouble(v)) @@ -140,6 +177,7 @@ typedef struct entityRecord * ENTITY_RECORD_PTR; #define GetNextArgument(ep) (ep->nextArg) #define MAXIMUM_PRIMITIVES 150 +#define MAXIMUM_EXTERNAL_ADDRESS_TYPES 10 #define BITS_PER_BYTE 8 @@ -154,12 +192,14 @@ typedef struct entityRecord * ENTITY_RECORD_PTR; #define EVALUATION_DATA 44 struct evaluationData - { + { struct expr *CurrentExpression; int EvaluationError; int HaltExecution; int CurrentEvaluationDepth; + int numberOfAddressTypes; struct entityRecord *PrimitivesArray[MAXIMUM_PRIMITIVES]; + struct externalAddressType *ExternalAddressTypes[MAXIMUM_EXTERNAL_ADDRESS_TYPES]; }; #define EvaluationData(theEnv) ((struct evaluationData *) GetEnvironmentData(theEnv,EVALUATION_DATA)) @@ -174,46 +214,39 @@ struct evaluationData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define SetMultifieldErrorValue(theEnv,a) EnvSetMultifieldErrorValue(theEnv,a) -#define FunctionCall(theEnv,a,b,c) EnvFunctionCall(theEnv,a,b,c) -#else -#define SetMultifieldErrorValue(a) EnvSetMultifieldErrorValue(GetCurrentEnvironment(),a) -#define FunctionCall(a,b,c) EnvFunctionCall(GetCurrentEnvironment(),a,b,c) -#endif - LOCALE void InitializeEvaluationData(void *); LOCALE int EvaluateExpression(void *,struct expr *,struct dataObject *); LOCALE void SetEvaluationError(void *,intBool); LOCALE int GetEvaluationError(void *); LOCALE void SetHaltExecution(void *,int); LOCALE int GetHaltExecution(void *); - LOCALE void ReturnValues(void *,struct dataObject *); - LOCALE void PrintDataObject(void *,char *,struct dataObject *); + LOCALE void ReturnValues(void *,struct dataObject *,intBool); + LOCALE void PrintDataObject(void *,const char *,struct dataObject *); LOCALE void EnvSetMultifieldErrorValue(void *,struct dataObject *); LOCALE void ValueInstall(void *,struct dataObject *); LOCALE void ValueDeinstall(void *,struct dataObject *); - LOCALE void PropagateReturnValue(void *,struct dataObject *); #if DEFFUNCTION_CONSTRUCT || DEFGENERIC_CONSTRUCT - LOCALE int EnvFunctionCall(void *,char *,char *,DATA_OBJECT *); - LOCALE int FunctionCall2(void *,FUNCTION_REFERENCE *,char *,DATA_OBJECT *); + LOCALE int EnvFunctionCall(void *,const char *,const char *,DATA_OBJECT *); + LOCALE int FunctionCall2(void *,FUNCTION_REFERENCE *,const char *,DATA_OBJECT *); #endif LOCALE void CopyDataObject(void *,DATA_OBJECT *,DATA_OBJECT *,int); LOCALE void AtomInstall(void *,int,void *); LOCALE void AtomDeinstall(void *,int,void *); LOCALE struct expr *ConvertValueToExpression(void *,DATA_OBJECT *); - LOCALE unsigned int GetAtomicHashValue(unsigned short,void *,int); + LOCALE unsigned long GetAtomicHashValue(unsigned short,void *,int); LOCALE void InstallPrimitive(void *,struct entityRecord *,int); + LOCALE int InstallExternalAddressType(void *,struct externalAddressType *); LOCALE void TransferDataObjectValues(DATA_OBJECT *,DATA_OBJECT *); - LOCALE struct expr *FunctionReferenceExpression(void *,char *); - LOCALE intBool GetFunctionReference(void *,char *,FUNCTION_REFERENCE *); + LOCALE struct expr *FunctionReferenceExpression(void *,const char *); + LOCALE intBool GetFunctionReference(void *,const char *,FUNCTION_REFERENCE *); LOCALE intBool DOsEqual(DATA_OBJECT_PTR,DATA_OBJECT_PTR); LOCALE int EvaluateAndStoreInDataObject(void *,int,EXPRESSION *,DATA_OBJECT *,int); -#endif - - - +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE void SetMultifieldErrorValue(DATA_OBJECT_PTR); + LOCALE int FunctionCall(const char *,const char *,DATA_OBJECT *); +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ +#endif /* _H_evaluatn */ diff --git a/src/expressn.c b/src/expressn.c index 1587682..c43ad3f 100644 --- a/src/expressn.c +++ b/src/expressn.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION MODULE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -25,6 +25,14 @@ /* 6.24: Corrected link errors with non-default */ /* setup.h configuration settings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed expression hashing value. */ +/* */ /*************************************************************/ #define _EXPRESSN_SOURCE_ @@ -87,7 +95,7 @@ globle void InitExpressionData( ExpressionData(theEnv)->ExpressionHashTable[i] = NULL; #endif } - + /*****************************************/ /* DeallocateExpressionData: Deallocates */ /* environment data for expressions. */ @@ -98,7 +106,7 @@ static void DeallocateExpressionData( #if ! RUN_TIME int i; EXPRESSION_HN *tmpPtr, *nextPtr; - + #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) if (! Bloaded(theEnv)) #endif @@ -115,19 +123,19 @@ static void DeallocateExpressionData( } } } - + rm(theEnv,ExpressionData(theEnv)->ExpressionHashTable, (int) (sizeof(EXPRESSION_HN *) * EXPRESSION_HASH_SIZE)); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif - + #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) if ((ExpressionData(theEnv)->NumberOfExpressions != 0) && Bloaded(theEnv)) { - genlongfree(theEnv,(void *) ExpressionData(theEnv)->ExpressionArray, + genfree(theEnv,(void *) ExpressionData(theEnv)->ExpressionArray, ExpressionData(theEnv)->NumberOfExpressions * sizeof(struct expr)); } #endif @@ -344,13 +352,20 @@ static unsigned HashExpression( EXPRESSION *theExp) { unsigned long tally = PRIME_THREE; + union + { + void *vv; + unsigned long uv; + } fis; if (theExp->argList != NULL) tally += HashExpression(theExp->argList) * PRIME_ONE; while (theExp != NULL) { tally += (unsigned long) (theExp->type * PRIME_TWO); - tally += (unsigned long) theExp->value; + fis.uv = 0; + fis.vv = theExp->value; + tally += fis.uv; theExp = theExp->nextArg; } return((unsigned) (tally % EXPRESSION_HASH_SIZE)); diff --git a/src/expressn.h b/src/expressn.h index 49fa3f3..d494f25 100644 --- a/src/expressn.h +++ b/src/expressn.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION HEADER FILE */ /*******************************************************/ @@ -14,12 +14,20 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed expression hashing value. */ +/* */ /*************************************************************/ #ifndef _H_expressn @@ -94,7 +102,7 @@ typedef struct exprHashNode #define EXPRESSION_DATA 45 struct expressionData - { + { void *PTR_AND; void *PTR_OR; void *PTR_EQ; diff --git a/src/exprnbin.c b/src/exprnbin.c index c517099..5d505ff 100644 --- a/src/exprnbin.c +++ b/src/exprnbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -14,10 +14,12 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #define _EXPRNBIN_SOURCE_ @@ -80,15 +82,15 @@ globle void AllocateExpressions( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &ExpressionData(theEnv)->NumberOfExpressions,(unsigned long) sizeof(long)); + GenReadBinary(theEnv,(void *) &ExpressionData(theEnv)->NumberOfExpressions,sizeof(long)); if (ExpressionData(theEnv)->NumberOfExpressions == 0L) ExpressionData(theEnv)->ExpressionArray = NULL; else { space = ExpressionData(theEnv)->NumberOfExpressions * sizeof(struct expr); - ExpressionData(theEnv)->ExpressionArray = (struct expr *) genlongalloc(theEnv,space); + ExpressionData(theEnv)->ExpressionArray = (struct expr *) genalloc(theEnv,space); } } @@ -246,7 +248,8 @@ static void UpdateExpression( globle void ClearBloadedExpressions( void *theEnv) { - unsigned long int i, space; + unsigned long int i; + size_t space; /*===============================================*/ /* Update the busy counts of atomic data values. */ @@ -297,7 +300,7 @@ globle void ClearBloadedExpressions( /*===================================*/ space = ExpressionData(theEnv)->NumberOfExpressions * sizeof(struct expr); - if (space != 0) genlongfree(theEnv,(void *) ExpressionData(theEnv)->ExpressionArray,space); + if (space != 0) genfree(theEnv,(void *) ExpressionData(theEnv)->ExpressionArray,space); ExpressionData(theEnv)->ExpressionArray = 0; } diff --git a/src/exprnbin.h b/src/exprnbin.h index 34b2346..87bc5c2 100644 --- a/src/exprnbin.h +++ b/src/exprnbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION BLOAD/BSAVE HEADER FILE */ /*******************************************************/ @@ -12,12 +12,14 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_exprnbin @@ -51,7 +53,7 @@ LOCALE void BsaveConstructExpressions(void *,FILE *); LOCALE void BsaveExpression(void *,struct expr *,FILE *); -#endif +#endif /* _H_exprnbin */ diff --git a/src/exprnops.c b/src/exprnops.c index bb38701..4cf5936 100644 --- a/src/exprnops.c +++ b/src/exprnops.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION OPERATIONS MODULE */ /*******************************************************/ @@ -14,12 +14,17 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Add NegateExpression function. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _EXPRNOPS_SOURCE_ @@ -345,7 +350,7 @@ globle struct expr *GenConstant( /*************************************************/ globle void PrintExpression( void *theEnv, - char *fileid, + const char *fileid, struct expr *theExpression) { struct expr *oldExpression; @@ -502,6 +507,43 @@ globle struct expr *CombineExpressions( return(tempPtr); } +/*********************/ +/* NegateExpression: */ +/*********************/ +globle struct expr *NegateExpression( + void *theEnv, + struct expr *theExpression) + { + struct expr *tempPtr; + + /*=========================================*/ + /* If the expression is NULL, return NULL. */ + /*=========================================*/ + + if (theExpression == NULL) return(NULL); + + /*==================================================*/ + /* The expression is already wrapped within a "not" */ + /* function call, just remove the function call. */ + /*==================================================*/ + + if (theExpression->value == ExpressionData(theEnv)->PTR_NOT) + { + tempPtr = theExpression->argList; + rtn_struct(theEnv,expr,theExpression); + return(tempPtr); + } + + /*===================================================*/ + /* Wrap the expression within a "not" function call. */ + /*===================================================*/ + + tempPtr = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_NOT); + tempPtr->argList = theExpression; + + return(tempPtr); + } + /********************************************************/ /* AppendExpressions: Attaches an expression to the end */ /* of another expression's nextArg list. */ diff --git a/src/exprnops.h b/src/exprnops.h index 1d061cf..e4e7c4f 100644 --- a/src/exprnops.h +++ b/src/exprnops.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION OPERATIONS HEADER FILE */ /*******************************************************/ @@ -14,12 +14,17 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Add NegateExpression function. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_exprnops @@ -41,7 +46,7 @@ #endif LOCALE intBool ConstantExpression(struct expr *); - LOCALE void PrintExpression(void *,char *,struct expr *); + LOCALE void PrintExpression(void *,const char *,struct expr *); LOCALE long ExpressionSize(struct expr *); LOCALE int CountArguments(struct expr *); LOCALE struct expr *CopyExpression(void *,struct expr *); @@ -54,7 +59,8 @@ LOCALE intBool ConstantType(int); LOCALE struct expr *CombineExpressions(void *,struct expr *,struct expr *); LOCALE struct expr *AppendExpressions(struct expr *,struct expr *); + LOCALE struct expr *NegateExpression(void *,struct expr *); -#endif +#endif /* _H_exprnops */ diff --git a/src/exprnpsr.c b/src/exprnpsr.c index 906202b..d3ece63 100644 --- a/src/exprnpsr.c +++ b/src/exprnpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* EXPRESSION PARSER MODULE */ /*******************************************************/ @@ -13,15 +13,31 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Module specifier can be used within an */ +/* expression to refer to a deffunction or */ +/* defgeneric exported by the specified module, */ +/* but not necessarily imported by the current */ +/* module. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _EXPRNPSR_SOURCE_ @@ -68,7 +84,7 @@ /***************************************************/ globle struct expr *Function0Parse( void *theEnv, - char *logicalName) + const char *logicalName) { struct token theToken; struct expr *top; @@ -98,7 +114,7 @@ globle struct expr *Function0Parse( /*******************************************************/ globle struct expr *Function1Parse( void *theEnv, - char *logicalName) + const char *logicalName) { struct token theToken; struct expr *top; @@ -130,11 +146,14 @@ globle struct expr *Function1Parse( /****************************************************/ globle struct expr *Function2Parse( void *theEnv, - char *logicalName, - char *name) + const char *logicalName, + const char *name) { struct FunctionDefinition *theFunction; struct expr *top; + int moduleSpecified = FALSE; + unsigned position; + struct symbolHashNode *moduleName = NULL, *constructName = NULL; #if DEFGENERIC_CONSTRUCT void *gfunc; #endif @@ -146,10 +165,11 @@ globle struct expr *Function2Parse( /* Module specification cannot be used in a function call. */ /*=========================================================*/ - if (FindModuleSeparator(name)) + if ((position = FindModuleSeparator(name)) != FALSE) { - IllegalModuleSpecifierMessage(theEnv); - return(NULL); + moduleName = ExtractModuleName(theEnv,position,name); + constructName = ExtractConstructName(theEnv,position,name); + moduleSpecified = TRUE; } /*================================*/ @@ -159,16 +179,35 @@ globle struct expr *Function2Parse( theFunction = FindFunction(theEnv,name); #if DEFGENERIC_CONSTRUCT - gfunc = (void *) LookupDefgenericInScope(theEnv,name); + if (moduleSpecified) + { + if (ConstructExported(theEnv,"defgeneric",moduleName,constructName) || + EnvGetCurrentModule(theEnv) == EnvFindDefmodule(theEnv,ValueToString(moduleName))) + { gfunc = (void *) EnvFindDefgenericInModule(theEnv,name); } + else + { gfunc = NULL; } + } + else + { gfunc = (void *) LookupDefgenericInScope(theEnv,name); } #endif #if DEFFUNCTION_CONSTRUCT - if ((theFunction == NULL) #if DEFGENERIC_CONSTRUCT - && (gfunc == NULL) + if ((theFunction == NULL) + && (gfunc == NULL)) +#else + if (theFunction == NULL) #endif - ) - dptr = (void *) LookupDeffunctionInScope(theEnv,name); + if (moduleSpecified) + { + if (ConstructExported(theEnv,"deffunction",moduleName,constructName) || + EnvGetCurrentModule(theEnv) == EnvFindDefmodule(theEnv,ValueToString(moduleName))) + { dptr = (void *) EnvFindDeffunctionInModule(theEnv,name); } + else + { dptr = NULL; } + } + else + { dptr = (void *) LookupDeffunctionInScope(theEnv,name); } else dptr = NULL; #endif @@ -401,8 +440,8 @@ globle void PopRtnBrkContexts( globle int CheckExpressionAgainstRestrictions( void *theEnv, struct expr *theExpression, - char *restrictions, - char *functionName) + const char *restrictions, + const char *functionName) { char theChar[2]; int i = 0, j = 1; @@ -529,7 +568,7 @@ globle int CheckExpressionAgainstRestrictions( globle struct expr *CollectArguments( void *theEnv, struct expr *top, - char *logicalName) + const char *logicalName) { int errorFlag; struct expr *lastOne, *nextOne; @@ -576,7 +615,7 @@ globle struct expr *CollectArguments( /********************************************/ globle struct expr *ArgumentParse( void *theEnv, - char *logicalName, + const char *logicalName, int *errorFlag) { struct expr *top; @@ -635,7 +674,7 @@ globle struct expr *ArgumentParse( /************************************************************/ globle struct expr *ParseAtomOrExpression( void *theEnv, - char *logicalName, + const char *logicalName, struct token *useToken) { struct token theToken, *thisToken; @@ -681,10 +720,10 @@ globle struct expr *ParseAtomOrExpression( /*********************************************/ globle struct expr *GroupActions( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken, int readFirstToken, - char *endWord, + const char *endWord, int functionNameParsed) { struct expr *top, *nextOne, *lastOne = NULL; @@ -833,11 +872,11 @@ globle intBool EnvGetSequenceOperatorRecognition( /*******************************************/ globle EXPRESSION *ParseConstantArguments( void *theEnv, - char *argstr, + const char *argstr, int *error) { EXPRESSION *top = NULL,*bot = NULL,*tmp; - char *router = "***FNXARGS***"; + const char *router = "***FNXARGS***"; struct token tkn; *error = FALSE; @@ -927,3 +966,23 @@ globle struct expr *RemoveUnneededProgn( return(theExpression); } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool SetSequenceOperatorRecognition( + int value) + { + return EnvSetSequenceOperatorRecognition(GetCurrentEnvironment(),value); + } + +globle intBool GetSequenceOperatorRecognition() + { + return EnvGetSequenceOperatorRecognition(GetCurrentEnvironment()); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + diff --git a/src/exprnpsr.h b/src/exprnpsr.h index ae37712..398263b 100644 --- a/src/exprnpsr.h +++ b/src/exprnpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXPRESSION PARSER HEADER FILE */ /*******************************************************/ @@ -16,8 +16,23 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Module specifier can be used within an */ +/* expression to refer to a deffunction or */ +/* defgeneric exported by the specified module, */ +/* but not necessarily imported by the current */ +/* module. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_exprnpsr @@ -52,35 +67,38 @@ typedef struct saved_contexts #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetSequenceOperatorRecognition(theEnv) EnvGetSequenceOperatorRecognition(theEnv) -#define SetSequenceOperatorRecognition(theEnv,a) EnvSetSequenceOperatorRecognition(theEnv,a) -#else -#define GetSequenceOperatorRecognition() EnvGetSequenceOperatorRecognition(GetCurrentEnvironment()) -#define SetSequenceOperatorRecognition(a) EnvSetSequenceOperatorRecognition(GetCurrentEnvironment(),a) -#endif - - LOCALE struct expr *Function0Parse(void *,char *); - LOCALE struct expr *Function1Parse(void *,char *); - LOCALE struct expr *Function2Parse(void *,char *,char *); + LOCALE struct expr *Function0Parse(void *,const char *); + LOCALE struct expr *Function1Parse(void *,const char *); + LOCALE struct expr *Function2Parse(void *,const char *,const char *); LOCALE void PushRtnBrkContexts(void *); LOCALE void PopRtnBrkContexts(void *); LOCALE intBool ReplaceSequenceExpansionOps(void *,struct expr *,struct expr *, void *,void *); - LOCALE struct expr *CollectArguments(void *,struct expr *,char *); - LOCALE struct expr *ArgumentParse(void *,char *,int *); - LOCALE struct expr *ParseAtomOrExpression(void *,char *,struct token *); - LOCALE EXPRESSION *ParseConstantArguments(void *,char *,int *); + LOCALE struct expr *CollectArguments(void *,struct expr *,const char *); + LOCALE struct expr *ArgumentParse(void *,const char *,int *); + LOCALE struct expr *ParseAtomOrExpression(void *,const char *,struct token *); + LOCALE EXPRESSION *ParseConstantArguments(void *,const char *,int *); LOCALE intBool EnvSetSequenceOperatorRecognition(void *,int); LOCALE intBool EnvGetSequenceOperatorRecognition(void *); - LOCALE struct expr *GroupActions(void *,char *,struct token *,int,char *,int); + LOCALE struct expr *GroupActions(void *,const char *,struct token *, + int,const char *,int); LOCALE struct expr *RemoveUnneededProgn(void *,struct expr *); + #if (! RUN_TIME) - LOCALE int CheckExpressionAgainstRestrictions(void *,struct expr *,char *,char *); -#endif + LOCALE int CheckExpressionAgainstRestrictions(void *,struct expr *, + const char *,const char *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool SetSequenceOperatorRecognition(int); + LOCALE intBool GetSequenceOperatorRecognition(void); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_exprnpsr */ + diff --git a/src/extnfunc.c b/src/extnfunc.c index a87f24f..c0996ab 100644 --- a/src/extnfunc.c +++ b/src/extnfunc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXTERNAL FUNCTION MODULE */ /*******************************************************/ @@ -14,13 +14,23 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _EXTNFUNC_SOURCE_ @@ -83,7 +93,7 @@ static void DeallocateExternalFunctionData( if (ExternalFunctionData(theEnv)->FunctionHashtable == NULL) { return; } - + for (i = 0; i < SIZE_FUNCTION_HASH; i++) { fhPtr = ExternalFunctionData(theEnv)->FunctionHashtable[i]; @@ -94,83 +104,71 @@ static void DeallocateExternalFunctionData( fhPtr = nextFHPtr; } } - + genfree(theEnv,ExternalFunctionData(theEnv)->FunctionHashtable, (int) sizeof (struct FunctionHash *) * SIZE_FUNCTION_HASH); } #if (! RUN_TIME) -/************************************************************/ -/* DefineFunction: Used to define a system or user external */ -/* function so that the KB can access it. */ -/************************************************************/ -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -globle int DefineFunction( - char *name, +/******************************************************/ +/* EnvDefineFunction: Used to define a system or user */ +/* external function so that the KB can access it. */ +/******************************************************/ +globle int EnvDefineFunction( + void *theEnv, + const char *name, int returnType, - int (*pointer)(void), - char *actualName) + int (*pointer)(void *), + const char *actualName) { - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - return(DefineFunction3(theEnv,name,returnType, - (int (*)(void *)) pointer, - actualName,NULL,FALSE)); + return(DefineFunction3(theEnv,name,returnType,pointer,actualName,NULL,TRUE,NULL)); } -#endif -/***************************************************************/ -/* EnvDefineFunction: Used to define a system or user external */ -/* function so that the KB can access it. */ -/***************************************************************/ -globle int EnvDefineFunction( +/************************************************************/ +/* EnvDefineFunctionWithContext: Used to define a system or */ +/* user external function so that the KB can access it. */ +/************************************************************/ +globle int EnvDefineFunctionWithContext( void *theEnv, - char *name, + const char *name, int returnType, int (*pointer)(void *), - char *actualName) + const char *actualName, + void *context) { - return(DefineFunction3(theEnv,name,returnType,pointer,actualName,NULL,TRUE)); + return(DefineFunction3(theEnv,name,returnType,pointer,actualName,NULL,TRUE,context)); } - -/*************************************************************/ -/* DefineFunction2: Used to define a system or user external */ -/* function so that the KB can access it. */ -/*************************************************************/ -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -globle int DefineFunction2( - char *name, + +/*******************************************************/ +/* EnvDefineFunction2: Used to define a system or user */ +/* external function so that the KB can access it. */ +/*******************************************************/ +globle int EnvDefineFunction2( + void *theEnv, + const char *name, int returnType, - int (*pointer)(void), - char *actualName, - char *restrictions) + int (*pointer)(void *), + const char *actualName, + const char *restrictions) { - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - return(DefineFunction3(theEnv,name,returnType, - (int (*)(void *)) pointer, - actualName,restrictions,FALSE)); + return(DefineFunction3(theEnv,name,returnType,pointer,actualName,restrictions,TRUE,NULL)); } -#endif - + /*************************************************************/ -/* EnvDefineFunction2: Used to define a system or user external */ -/* function so that the KB can access it. */ +/* EnvDefineFunction2WithContext: Used to define a system or */ +/* user external function so that the KB can access it. */ /*************************************************************/ -globle int EnvDefineFunction2( +globle int EnvDefineFunction2WithContext( void *theEnv, - char *name, + const char *name, int returnType, int (*pointer)(void *), - char *actualName, - char *restrictions) + const char *actualName, + const char *restrictions, + void *context) { - return(DefineFunction3(theEnv,name,returnType,pointer,actualName,restrictions,TRUE)); + return(DefineFunction3(theEnv,name,returnType,pointer,actualName,restrictions,TRUE,context)); } /*************************************************************/ @@ -183,11 +181,12 @@ globle int EnvDefineFunction2( /* c - character (converted to symbol) */ /* d - double precision float */ /* f - single precision float (converted to double) */ -/* i - integer (converted to long integer) */ +/* g - long long integer */ +/* i - integer (converted to long long integer) */ /* j - unknown (symbol, string, */ /* or instance name by convention) */ /* k - unknown (symbol or string by convention) */ -/* l - long integer */ +/* l - long integer (converted to long long integer) */ /* m - unknown (multifield by convention) */ /* n - unknown (integer or float by convention) */ /* o - instance name */ @@ -199,12 +198,13 @@ globle int EnvDefineFunction2( /*************************************************************/ globle int DefineFunction3( void *theEnv, - char *name, + const char *name, int returnType, int (*pointer)(void *), - char *actualName, - char *restrictions, - intBool environmentAware) + const char *actualName, + const char *restrictions, + intBool environmentAware, + void *context) { struct FunctionDefinition *newFunction; @@ -213,6 +213,7 @@ globle int DefineFunction3( (returnType != 'c') && (returnType != 'd') && (returnType != 'f') && + (returnType != 'g') && (returnType != 'i') && (returnType != 'j') && (returnType != 'k') && @@ -228,6 +229,9 @@ globle int DefineFunction3( #if OBJECT_SYSTEM (returnType != 'x') && #endif +#if DEFTEMPLATE_CONSTRUCT + (returnType != 'y') && +#endif (returnType != 'w') ) { return(0); } @@ -241,7 +245,7 @@ globle int DefineFunction3( ExternalFunctionData(theEnv)->ListOfFunctions = newFunction; AddHashFunction(theEnv,newFunction); } - + newFunction->returnValueType = (char) returnType; newFunction->functionPointer = (int (*)(void)) pointer; newFunction->actualFunctionName = actualName; @@ -258,17 +262,18 @@ globle int DefineFunction3( newFunction->sequenceuseok = TRUE; newFunction->environmentAware = (short) environmentAware; newFunction->usrData = NULL; + newFunction->context = context; return(1); } - + /***********************************************/ /* UndefineFunction: Used to remove a function */ /* definition from the list of functions. */ /***********************************************/ globle int UndefineFunction( void *theEnv, - char *functionName) + const char *functionName) { SYMBOL_HN *findValue; struct FunctionDefinition *fPtr, *lastPtr = NULL; @@ -288,7 +293,7 @@ globle int UndefineFunction( { ExternalFunctionData(theEnv)->ListOfFunctions = fPtr->next; } else { lastPtr->next = fPtr->next; } - + ClearUserDataList(theEnv,fPtr->usrData); rtn_struct(theEnv,FunctionDefinition,fPtr); return(TRUE); @@ -345,8 +350,8 @@ static int RemoveHashFunction( /***************************************************************************/ globle int AddFunctionParser( void *theEnv, - char *functionName, - struct expr *(*fpPtr)(void *,struct expr *,char *)) + const char *functionName, + struct expr *(*fpPtr)(void *,struct expr *,const char *)) { struct FunctionDefinition *fdPtr; @@ -369,7 +374,7 @@ globle int AddFunctionParser( /*********************************************************************/ globle int RemoveFunctionParser( void *theEnv, - char *functionName) + const char *functionName) { struct FunctionDefinition *fdPtr; @@ -391,7 +396,7 @@ globle int RemoveFunctionParser( /*****************************************************************/ globle int FuncSeqOvlFlags( void *theEnv, - char *functionName, + const char *functionName, int seqp, int ovlp) { @@ -414,7 +419,7 @@ globle int FuncSeqOvlFlags( /* GetArgumentTypeName: Returns a descriptive string for */ /* a function argument type (used by DefineFunction2). */ /*********************************************************/ -globle char *GetArgumentTypeName( +globle const char *GetArgumentTypeName( int theRestriction) { switch ((char) theRestriction) @@ -477,9 +482,6 @@ globle char *GetArgumentTypeName( case 'u': return("non-void return value"); - - default: - break; } return("unknown argument type"); @@ -590,14 +592,14 @@ globle void InstallFunctionList( /********************************************************/ globle struct FunctionDefinition *FindFunction( void *theEnv, - char *functionName) + const char *functionName) { struct FunctionHash *fhPtr; unsigned hashValue; SYMBOL_HN *findValue; if (ExternalFunctionData(theEnv)->FunctionHashtable == NULL) return(NULL); - + hashValue = HashSymbol(functionName,SIZE_FUNCTION_HASH); findValue = (SYMBOL_HN *) FindSymbolHN(theEnv,functionName); @@ -658,7 +660,8 @@ static void AddHashFunction( globle int GetMinimumArgs( struct FunctionDefinition *theFunction) { - char theChar[2], *restrictions; + char theChar[2]; + const char *restrictions; restrictions = theFunction->restrictions; if (restrictions == NULL) return(-1); @@ -670,10 +673,10 @@ globle int GetMinimumArgs( { return atoi(theChar); } else if (theChar[0] == '*') { return(-1); } - - return(-1); + + return(-1); } - + /*************************************************/ /* GetMaximumArgs: Returns the maximum number of */ /* arguments expected by an external function. */ @@ -681,7 +684,8 @@ globle int GetMinimumArgs( globle int GetMaximumArgs( struct FunctionDefinition *theFunction) { - char theChar[2], *restrictions; + char theChar[2]; + const char *restrictions; restrictions = theFunction->restrictions; if (restrictions == NULL) return(-1); @@ -694,6 +698,48 @@ globle int GetMaximumArgs( { return atoi(theChar); } else if (theChar[0] == '*') { return(-1); } - - return(-1); + + return(-1); } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if (! RUN_TIME) +globle int DefineFunction( + const char *name, + int returnType, + int (*pointer)(void), + const char *actualName) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + return(DefineFunction3(theEnv,name,returnType, + (int (*)(void *)) pointer, + actualName,NULL,FALSE,NULL)); + } + +globle int DefineFunction2( + const char *name, + int returnType, + int (*pointer)(void), + const char *actualName, + const char *restrictions) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + return(DefineFunction3(theEnv,name,returnType, + (int (*)(void *)) pointer, + actualName,restrictions,FALSE,NULL)); + } + +#endif /* (! RUN_TIME) */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ diff --git a/src/extnfunc.h b/src/extnfunc.h index cdfdcfd..87f555d 100644 --- a/src/extnfunc.h +++ b/src/extnfunc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* EXTERNAL FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -19,6 +19,17 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for passing context information */ +/* to user defined functions. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Replaced ALLOW_ENVIRONMENT_GLOBALS macros */ +/* with functions. */ +/* */ /*************************************************************/ #ifndef _H_extnfunc @@ -37,17 +48,18 @@ struct FunctionDefinition { struct symbolHashNode *callFunctionName; - char *actualFunctionName; + const char *actualFunctionName; char returnValueType; int (*functionPointer)(void); - struct expr *(*parser)(void *,struct expr *,char *); - char *restrictions; + struct expr *(*parser)(void *,struct expr *,const char *); + const char *restrictions; short int overloadable; short int sequenceuseok; short int environmentAware; short int bsaveIndex; struct FunctionDefinition *next; struct userData *usrData; + void *context; }; #define ValueFunctionType(target) (((struct FunctionDefinition *) target)->returnValueType) @@ -66,7 +78,7 @@ struct FunctionDefinition #define EXTERNAL_FUNCTION_DATA 50 struct externalFunctionData - { + { struct FunctionDefinition *ListOfFunctions; struct FunctionHash **FunctionHashtable; }; @@ -93,35 +105,40 @@ struct FunctionHash #define SIZE_FUNCTION_HASH 517 #endif -#if ENVIRONMENT_API_ONLY -#define DefineFunction(theEnv,a,b,c,d) EnvDefineFunction(theEnv,a,b,c,d) -#define DefineFunction2(theEnv,a,b,c,d,e) EnvDefineFunction2(theEnv,a,b,c,d,e) -#else - LOCALE int DefineFunction(char *,int,int (*)(void),char *); - LOCALE int DefineFunction2(char *,int,int (*)(void),char *,char *); -#endif - LOCALE void InitializeExternalFunctionData(void *); - LOCALE int EnvDefineFunction(void *,char *,int, - int (*)(void *),char *); - LOCALE int EnvDefineFunction2(void *,char *,int, - int (*)(void *),char *,char *); - LOCALE int DefineFunction3(void *,char *,int, - int (*)(void *),char *,char *,intBool); - LOCALE int AddFunctionParser(void *,char *, - struct expr *(*)( void *,struct expr *,char *)); - LOCALE int RemoveFunctionParser(void *,char *); - LOCALE int FuncSeqOvlFlags(void *,char *,int,int); + LOCALE int EnvDefineFunction(void *,const char *,int, + int (*)(void *),const char *); + LOCALE int EnvDefineFunction2(void *,const char *,int, + int (*)(void *),const char *,const char *); + LOCALE int EnvDefineFunctionWithContext(void *,const char *,int, + int (*)(void *),const char *,void *); + LOCALE int EnvDefineFunction2WithContext(void *,const char *,int, + int (*)(void *),const char *,const char *,void *); + LOCALE int DefineFunction3(void *,const char *,int, + int (*)(void *),const char *,const char *,intBool,void *); + LOCALE int AddFunctionParser(void *,const char *, + struct expr *(*)( void *,struct expr *,const char *)); + LOCALE int RemoveFunctionParser(void *,const char *); + LOCALE int FuncSeqOvlFlags(void *,const char *,int,int); LOCALE struct FunctionDefinition *GetFunctionList(void *); LOCALE void InstallFunctionList(void *,struct FunctionDefinition *); - LOCALE struct FunctionDefinition *FindFunction(void *,char *); + LOCALE struct FunctionDefinition *FindFunction(void *,const char *); LOCALE int GetNthRestriction(struct FunctionDefinition *,int); - LOCALE char *GetArgumentTypeName(int); - LOCALE int UndefineFunction(void *,char *); + LOCALE const char *GetArgumentTypeName(int); + LOCALE int UndefineFunction(void *,const char *); LOCALE int GetMinimumArgs(struct FunctionDefinition *); LOCALE int GetMaximumArgs(struct FunctionDefinition *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + +#if (! RUN_TIME) + LOCALE int DefineFunction(const char *,int,int (*)(void),const char *); + LOCALE int DefineFunction2(const char *,int,int (*)(void),const char *,const char *); +#endif /* (! RUN_TIME) */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_extnfunc */ diff --git a/src/factbin.c b/src/factbin.c index a2556b7..42feaf9 100644 --- a/src/factbin.c +++ b/src/factbin.c @@ -1,8 +1,7 @@ - /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -15,10 +14,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #define _FACTBIN_SOURCE_ @@ -86,7 +89,7 @@ globle void FactBinarySetup( void *theEnv) { AllocateEnvironmentData(theEnv,FACTBIN_DATA,sizeof(struct factBinaryData),DeallocateFactBloadData); - + #if BLOAD_AND_BSAVE AddBinaryItem(theEnv,"facts",0,BsaveFind,NULL, BsaveStorage,BsaveFactPatterns, @@ -99,7 +102,7 @@ globle void FactBinarySetup( ClearBload); #endif } - + /****************************************************/ /* DeallocateFactBloadData: Deallocates environment */ /* data for the fact bsave functionality. */ @@ -107,14 +110,14 @@ globle void FactBinarySetup( static void DeallocateFactBloadData( void *theEnv) { - unsigned long space; + size_t space; int i; - + for (i = 0; i < FactBinaryData(theEnv)->NumberOfPatterns; i++) - { DestroyAlphaBetaMemory(theEnv,FactBinaryData(theEnv)->FactPatternArray[i].header.alphaMemory); } + { DestroyAlphaMemory(theEnv,&FactBinaryData(theEnv)->FactPatternArray[i].header,FALSE); } space = FactBinaryData(theEnv)->NumberOfPatterns * sizeof(struct factPatternNode); - if (space != 0) genlongfree(theEnv,(void *) FactBinaryData(theEnv)->FactPatternArray,space); + if (space != 0) genfree(theEnv,(void *) FactBinaryData(theEnv)->FactPatternArray,space); } #if BLOAD_AND_BSAVE @@ -222,11 +225,11 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; space = sizeof(long); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); - GenWrite(&FactBinaryData(theEnv)->NumberOfPatterns,(unsigned long) sizeof(long int),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&FactBinaryData(theEnv)->NumberOfPatterns,sizeof(long int),fp); } /*****************************************************/ @@ -237,7 +240,7 @@ static void BsaveFactPatterns( void *theEnv, FILE *fp) { - unsigned long int space; + size_t space; struct deftemplate *theDeftemplate; struct defmodule *theModule; @@ -248,7 +251,7 @@ static void BsaveFactPatterns( /*========================================*/ space = FactBinaryData(theEnv)->NumberOfPatterns * sizeof(struct bsaveFactPatternNode); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*===========================*/ /* Loop through each module. */ @@ -291,7 +294,7 @@ static void BsavePatternNode( { struct bsaveFactPatternNode tempNode; - AssignBsavePatternHeaderValues(&tempNode.header,&thePattern->header); + AssignBsavePatternHeaderValues(theEnv,&tempNode.header,&thePattern->header); tempNode.whichField = thePattern->whichField; tempNode.leaveFields = thePattern->leaveFields; @@ -314,15 +317,15 @@ static void BsavePatternNode( static void BloadStorage( void *theEnv) { - unsigned long space; + size_t space; /*=========================================*/ /* Determine the number of factPatternNode */ /* data structures to be read. */ /*=========================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&FactBinaryData(theEnv)->NumberOfPatterns,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&FactBinaryData(theEnv)->NumberOfPatterns,sizeof(long int)); /*===================================*/ /* Allocate the space needed for the */ @@ -336,7 +339,7 @@ static void BloadStorage( } space = FactBinaryData(theEnv)->NumberOfPatterns * sizeof(struct factPatternNode); - FactBinaryData(theEnv)->FactPatternArray = (struct factPatternNode *) genlongalloc(theEnv,space); + FactBinaryData(theEnv)->FactPatternArray = (struct factPatternNode *) genalloc(theEnv,space); } /************************************************************/ @@ -346,7 +349,8 @@ static void BloadStorage( static void BloadBinaryItem( void *theEnv) { - unsigned long space; + size_t space; + long i; /*======================================================*/ /* Read in the amount of space used by the binary image */ @@ -354,7 +358,7 @@ static void BloadBinaryItem( /* is not available in the version being run). */ /*======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); /*=============================================*/ /* Read in the factPatternNode data structures */ @@ -363,6 +367,18 @@ static void BloadBinaryItem( BloadandRefresh(theEnv,FactBinaryData(theEnv)->NumberOfPatterns,(unsigned) sizeof(struct bsaveFactPatternNode), UpdateFactPatterns); + + for (i = 0; i < FactBinaryData(theEnv)->NumberOfPatterns; i++) + { + if ((FactBinaryData(theEnv)->FactPatternArray[i].lastLevel != NULL) && + (FactBinaryData(theEnv)->FactPatternArray[i].lastLevel->header.selector)) + { + AddHashedPatternNode(theEnv,FactBinaryData(theEnv)->FactPatternArray[i].lastLevel, + &FactBinaryData(theEnv)->FactPatternArray[i], + FactBinaryData(theEnv)->FactPatternArray[i].networkTest->type, + FactBinaryData(theEnv)->FactPatternArray[i].networkTest->value); + } + } } /*************************************************/ @@ -399,10 +415,24 @@ static void UpdateFactPatterns( static void ClearBload( void *theEnv) { - unsigned long int space; + size_t space; + long i; + + for (i = 0; i < FactBinaryData(theEnv)->NumberOfPatterns; i++) + { + if ((FactBinaryData(theEnv)->FactPatternArray[i].lastLevel != NULL) && + (FactBinaryData(theEnv)->FactPatternArray[i].lastLevel->header.selector)) + { + RemoveHashedPatternNode(theEnv,FactBinaryData(theEnv)->FactPatternArray[i].lastLevel, + &FactBinaryData(theEnv)->FactPatternArray[i], + FactBinaryData(theEnv)->FactPatternArray[i].networkTest->type, + FactBinaryData(theEnv)->FactPatternArray[i].networkTest->value); + } + } + space = FactBinaryData(theEnv)->NumberOfPatterns * sizeof(struct factPatternNode); - if (space != 0) genlongfree(theEnv,(void *) FactBinaryData(theEnv)->FactPatternArray,space); + if (space != 0) genfree(theEnv,(void *) FactBinaryData(theEnv)->FactPatternArray,space); FactBinaryData(theEnv)->NumberOfPatterns = 0; } diff --git a/src/factbin.h b/src/factbin.h index 371b18e..74b723d 100644 --- a/src/factbin.h +++ b/src/factbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT BLOAD/BSAVE HEADER FILE */ /*******************************************************/ @@ -16,6 +16,10 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_factbin @@ -27,11 +31,11 @@ #define FACTBIN_DATA 62 struct factBinaryData - { + { struct factPatternNode *FactPatternArray; long NumberOfPatterns; }; - + #define FactBinaryData(theEnv) ((struct factBinaryData *) GetEnvironmentData(theEnv,FACTBIN_DATA)) #ifdef LOCALE diff --git a/src/factbld.c b/src/factbld.c index 4db70d1..7974757 100644 --- a/src/factbld.c +++ b/src/factbld.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* FACT BUILD MODULE */ /*******************************************************/ @@ -21,6 +21,11 @@ /* */ /* 6.24: Removed INCREMENTAL_RESET compilation flag. */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ /*************************************************************/ #define _FACTBLD_SOURCE_ @@ -54,9 +59,9 @@ #if (! RUN_TIME) && (! BLOAD_ONLY) static struct factPatternNode *FindPatternNode(struct factPatternNode *,struct lhsParseNode *, - struct factPatternNode **,unsigned); + struct factPatternNode **,unsigned,unsigned); static struct factPatternNode *CreateNewPatternNode(void *,struct lhsParseNode *,struct factPatternNode *, - struct factPatternNode *,unsigned); + struct factPatternNode *,unsigned,unsigned); static void ClearPatternMatches(void *,struct factPatternNode *); static void DetachFactPattern(void *,struct patternNodeHeader *); static struct patternNodeHeader *PlaceFactPattern(void *,struct lhsParseNode *); @@ -82,12 +87,12 @@ globle void InitializeFactPatterns( newPtr->name = "facts"; newPtr->priority = 0; newPtr->entityType = &FactData(theEnv)->FactInfo; - + #if (! RUN_TIME) && (! BLOAD_ONLY) newPtr->recognizeFunction = FactPatternParserFind; newPtr->parseFunction = FactPatternParse; newPtr->postAnalysisFunction = NULL; - newPtr->addPatternFunction = PlaceFactPattern; + newPtr->addPatternFunction = PlaceFactPattern; newPtr->removePatternFunction = DetachFactPattern; newPtr->genJNConstantFunction = NULL; newPtr->replaceGetJNValueFunction = FactReplaceGetvar; @@ -103,7 +108,7 @@ globle void InitializeFactPatterns( newPtr->recognizeFunction = NULL; newPtr->parseFunction = NULL; newPtr->postAnalysisFunction = NULL; - newPtr->addPatternFunction = NULL; + newPtr->addPatternFunction = NULL; newPtr->removePatternFunction = NULL; newPtr->genJNConstantFunction = NULL; newPtr->replaceGetJNValueFunction = NULL; @@ -114,7 +119,7 @@ globle void InitializeFactPatterns( newPtr->genGetPNValueFunction = NULL; newPtr->genComparePNValuesFunction = NULL; newPtr->returnUserDataFunction = NULL; - newPtr->copyUserDataFunction = NULL; + newPtr->copyUserDataFunction = NULL; #endif newPtr->markIRPatternFunction = MarkFactPatternForIncrementalReset; @@ -130,7 +135,7 @@ globle void InitializeFactPatterns( #else newPtr->initialPatternFunction = NULL; newPtr->codeReferenceFunction = NULL; -#endif +#endif AddPatternParser(theEnv,newPtr); #endif @@ -145,12 +150,12 @@ static struct patternNodeHeader *PlaceFactPattern( void *theEnv, struct lhsParseNode *thePattern) { - struct lhsParseNode *tempPattern = NULL; + struct lhsParseNode *tempPattern; struct factPatternNode *currentLevel, *lastLevel; struct factPatternNode *nodeBeforeMatch, *newNode = NULL; unsigned endSlot; int count; - char *deftemplateName; + const char *deftemplateName; /*======================================================================*/ /* Get the name of the deftemplate associated with the pattern being */ @@ -179,17 +184,42 @@ static struct patternNodeHeader *PlaceFactPattern( if (thePattern->right->right == NULL) { ReturnExpression(theEnv,thePattern->right->networkTest); + ReturnExpression(theEnv,thePattern->right->constantSelector); + ReturnExpression(theEnv,thePattern->right->constantValue); thePattern->right->networkTest = NULL; + thePattern->right->constantSelector = NULL; + thePattern->right->constantValue = NULL; } else { tempPattern = thePattern->right; thePattern->right = thePattern->right->right; tempPattern->right = NULL; - ReturnLHSParseNodes(theEnv,tempPattern); - tempPattern = NULL; + ReturnLHSParseNodes(theEnv,tempPattern); + } + + /*====================================================*/ + /* Get the expression for hashing in the alpha memory */ + /* and attach it to the last node of the pattern. */ + /*====================================================*/ + + tempPattern = thePattern->right; + while (tempPattern->right != NULL) + { tempPattern = tempPattern->right; } + + if ((tempPattern->multifieldSlot) && (tempPattern->bottom != NULL)) + { + tempPattern = tempPattern->bottom; + + while (tempPattern->right != NULL) + { tempPattern = tempPattern->right; } } + tempPattern->rightHash = thePattern->rightHash; + thePattern->rightHash = NULL; + + tempPattern = NULL; + /*============================================================*/ /* Get a pointer to the deftemplate data structure associated */ /* with the pattern (use the deftemplate name extracted from */ @@ -243,7 +273,7 @@ static struct patternNodeHeader *PlaceFactPattern( /* that can be reused (shared)? */ /*========================================*/ - newNode = FindPatternNode(currentLevel,thePattern,&nodeBeforeMatch,endSlot); + newNode = FindPatternNode(currentLevel,thePattern,&nodeBeforeMatch,endSlot,FALSE); /*================================================*/ /* If the pattern node cannot be shared, then add */ @@ -251,7 +281,17 @@ static struct patternNodeHeader *PlaceFactPattern( /*================================================*/ if (newNode == NULL) - { newNode = CreateNewPatternNode(theEnv,thePattern,nodeBeforeMatch,lastLevel,endSlot); } + { newNode = CreateNewPatternNode(theEnv,thePattern,nodeBeforeMatch,lastLevel,endSlot,FALSE); } + + if (thePattern->constantSelector != NULL) + { + currentLevel = newNode->nextLevel; + lastLevel = newNode; + newNode = FindPatternNode(currentLevel,thePattern,&nodeBeforeMatch,endSlot,TRUE); + + if (newNode == NULL) + { newNode = CreateNewPatternNode(theEnv,thePattern,nodeBeforeMatch,lastLevel,endSlot,TRUE); } + } /*===========================================================*/ /* Move on to the next field in the new pattern to be added. */ @@ -300,10 +340,19 @@ static struct factPatternNode *FindPatternNode( struct factPatternNode *listOfNodes, struct lhsParseNode *thePattern, struct factPatternNode **nodeBeforeMatch, - unsigned endSlot) + unsigned endSlot, + unsigned constantSelector) { + struct expr *compareTest; *nodeBeforeMatch = NULL; + if (constantSelector) + { compareTest = thePattern->constantValue; } + else if (thePattern->constantSelector != NULL) + { compareTest = thePattern->constantSelector; } + else + { compareTest = thePattern->networkTest; } + /*==========================================================*/ /* Loop through the nodes at the given level in the pattern */ /* network looking for a node that can be reused (shared)? */ @@ -325,7 +374,8 @@ static struct factPatternNode *FindPatternNode( (listOfNodes->header.endSlot == endSlot) && (listOfNodes->whichField == thePattern->index) && (listOfNodes->whichSlot == (thePattern->slotNumber - 1)) && - IdenticalExpression(listOfNodes->networkTest,thePattern->networkTest)) + IdenticalExpression(listOfNodes->networkTest,compareTest) && + IdenticalExpression(listOfNodes->header.rightHash,thePattern->rightHash)) { return(listOfNodes); } } else if ((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) @@ -335,7 +385,8 @@ static struct factPatternNode *FindPatternNode( (listOfNodes->leaveFields == thePattern->singleFieldsAfter) && (listOfNodes->whichField == thePattern->index) && (listOfNodes->whichSlot == (thePattern->slotNumber - 1)) && - IdenticalExpression(listOfNodes->networkTest,thePattern->networkTest)) + IdenticalExpression(listOfNodes->networkTest,compareTest) && + IdenticalExpression(listOfNodes->header.rightHash,thePattern->rightHash)) { return(listOfNodes); } } @@ -477,6 +528,8 @@ static struct lhsParseNode *RemoveUnneededSlots( /*=======================================================*/ theTest = FactGenCheckLength(theEnv,tempPattern->bottom); + if (tempPattern->bottom->constantSelector != NULL) + { tempPattern->bottom->constantSelector->nextArg = CopyExpression(theEnv,theTest); } theTest = CombineExpressions(theEnv,theTest,tempPattern->bottom->networkTest); tempPattern->bottom->networkTest = theTest; @@ -540,7 +593,8 @@ static struct factPatternNode *CreateNewPatternNode( struct lhsParseNode *thePattern, struct factPatternNode *nodeBeforeMatch, struct factPatternNode *upperLevel, - unsigned endSlot) + unsigned endSlot, + unsigned constantSelector) { struct factPatternNode *newNode; @@ -556,15 +610,18 @@ static struct factPatternNode *CreateNewPatternNode( newNode->leaveFields = thePattern->singleFieldsAfter; InitializePatternHeader(theEnv,(struct patternNodeHeader *) &newNode->header); - if (thePattern->index > 0) + if (thePattern->index > 0) { newNode->whichField = (unsigned short) thePattern->index; } else newNode->whichField = 0; - if (thePattern->slotNumber >= 0) + if (thePattern->slotNumber >= 0) { newNode->whichSlot = (unsigned short) (thePattern->slotNumber - 1); } - else + else { newNode->whichSlot = newNode->whichField; } + if ((thePattern->constantSelector != NULL) && (! constantSelector)) + { newNode->header.selector = TRUE; } + /*=============================================================*/ /* Set the slot values which indicate whether the pattern node */ /* is a single-field, multifield, or end-of-pattern node. */ @@ -580,7 +637,19 @@ static struct factPatternNode *CreateNewPatternNode( /* Install the expression associated with this pattern node. */ /*===========================================================*/ - newNode->networkTest = AddHashedExpression(theEnv,thePattern->networkTest); + if (constantSelector) + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantValue); } + else if (thePattern->constantSelector != NULL) + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantSelector); } + else + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->networkTest); } + + /*==========================================*/ + /* Add the expression used for adding alpha */ + /* matches to the alpha memory. */ + /*==========================================*/ + + newNode->header.rightHash = AddHashedExpression(theEnv,thePattern->rightHash); /*===============================================*/ /* Set the upper level pointer for the new node. */ @@ -588,6 +657,9 @@ static struct factPatternNode *CreateNewPatternNode( newNode->lastLevel = upperLevel; + if ((upperLevel != NULL) && (upperLevel->header.selector)) + { AddHashedPatternNode(theEnv,upperLevel,newNode,newNode->networkTest->type,newNode->networkTest->value); } + /*======================================================*/ /* If there are no nodes on this level, then attach the */ /* new node to the child pointer of the upper level. */ @@ -669,12 +741,12 @@ static void DetachFactPattern( patternPtr = (struct factPatternNode *) thePattern; ClearPatternMatches(theEnv,patternPtr); - /*=====================================================*/ + /*=======================================================*/ /* If there are no joins entered from this pattern, then */ - /* the pattern node is no longer a stop node. Also if */ - /* the pattern has a next level pointer, then it can */ - /* not be removed since other patterns make use of it. */ - /*=====================================================*/ + /* the pattern node is no longer a stop node. Also if */ + /* the pattern has a next level pointer, then it can */ + /* not be removed since other patterns make use of it. */ + /*=======================================================*/ if (patternPtr->header.entryJoin == NULL) patternPtr->header.stopNode = FALSE; if (patternPtr->nextLevel != NULL) return; @@ -703,11 +775,15 @@ static void DetachFactPattern( { FindAndSetDeftemplatePatternNetwork(theEnv,patternPtr,NULL); } else { + if (upperLevel->header.selector) + { RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + upperLevel->nextLevel = NULL; if (upperLevel->header.stopNode) upperLevel = NULL; } RemoveHashedExpression(theEnv,patternPtr->networkTest); + RemoveHashedExpression(theEnv,patternPtr->header.rightHash); rtn_struct(theEnv,factPatternNode,patternPtr); } else if (upperLevel->leftNode != NULL) @@ -719,11 +795,17 @@ static void DetachFactPattern( /*====================================================*/ patternPtr = upperLevel; + + if ((patternPtr->lastLevel != NULL) && + (patternPtr->lastLevel->header.selector)) + { RemoveHashedPatternNode(theEnv,patternPtr->lastLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + upperLevel->leftNode->rightNode = upperLevel->rightNode; if (upperLevel->rightNode != NULL) { upperLevel->rightNode->leftNode = upperLevel->leftNode; } RemoveHashedExpression(theEnv,patternPtr->networkTest); + RemoveHashedExpression(theEnv,patternPtr->header.rightHash); rtn_struct(theEnv,factPatternNode,patternPtr); upperLevel = NULL; } @@ -740,10 +822,16 @@ static void DetachFactPattern( if (upperLevel == NULL) { FindAndSetDeftemplatePatternNetwork(theEnv,patternPtr,patternPtr->rightNode); } else - { upperLevel->nextLevel = patternPtr->rightNode; } + { + if (upperLevel->header.selector) + { RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + + upperLevel->nextLevel = patternPtr->rightNode; + } patternPtr->rightNode->leftNode = NULL; RemoveHashedExpression(theEnv,patternPtr->networkTest); + RemoveHashedExpression(theEnv,patternPtr->header.rightHash); rtn_struct(theEnv,factPatternNode,patternPtr); upperLevel = NULL; } @@ -761,27 +849,31 @@ globle void DestroyFactPatternNetwork( struct factPatternNode *thePattern) { struct factPatternNode *patternPtr; - + if (thePattern == NULL) return; - + while (thePattern != NULL) { patternPtr = thePattern->rightNode; - + DestroyFactPatternNetwork(theEnv,thePattern->nextLevel); - - DestroyAlphaBetaMemory(theEnv,thePattern->header.alphaMemory); - + + DestroyAlphaMemory(theEnv,&thePattern->header,FALSE); + + if ((thePattern->lastLevel != NULL) && + (thePattern->lastLevel->header.selector)) + { RemoveHashedPatternNode(theEnv,thePattern->lastLevel,thePattern,thePattern->networkTest->type,thePattern->networkTest->value); } + #if (! BLOAD_ONLY) && (! RUN_TIME) rtn_struct(theEnv,factPatternNode,thePattern); #endif - + thePattern = patternPtr; } } - + #if (! RUN_TIME) && (! BLOAD_ONLY) - + /***********************************************************/ /* FindAndSetDeftemplatePatternNetwork: When a deftemplate */ /* pattern is detached from the fact pattern network, it */ @@ -930,7 +1022,7 @@ static void ClearPatternMatches( } } } - + #endif /* (! RUN_TIME) && (! BLOAD_ONLY) */ #endif /* DEFTEMPLATE_CONSTRUCT && DEFRULE_CONSTRUCT */ diff --git a/src/factbld.h b/src/factbld.h index 7d3c551..2222e56 100644 --- a/src/factbld.h +++ b/src/factbld.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT BUILD HEADER FILE */ /*******************************************************/ @@ -16,6 +16,11 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ /*************************************************************/ #ifndef _H_factbld @@ -57,4 +62,4 @@ struct factPatternNode LOCALE void DestroyFactPatternNetwork(void *, struct factPatternNode *); -#endif +#endif /* _H_factbld */ diff --git a/src/factcmp.c b/src/factcmp.c index e7f6cb6..8f91f1b 100644 --- a/src/factcmp.c +++ b/src/factcmp.c @@ -2,7 +2,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT PATTERN NETWORK CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -18,6 +18,12 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _FACTCMP_SOURCE_ @@ -41,7 +47,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int PatternNetworkToCode(void *,char *,int,FILE *,int,int); + static int PatternNetworkToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void BeforePatternNetworkToCode(void *); static struct factPatternNode *GetNextPatternNode(struct factPatternNode *); static void CloseNetworkFiles(void *,FILE *,int); @@ -51,7 +57,7 @@ /* FactPatternsCompilerSetup: Initializes the constructs-to-c */ /* command for use with the fact pattern network. */ /**************************************************************/ -globle void FactPatternsCompilerSetup( +globle void FactPatternsCompilerSetup( void *theEnv) { FactData(theEnv)->FactCodeItem = AddCodeGeneratorItem(theEnv,"facts",0,BeforePatternNetworkToCode, @@ -156,7 +162,9 @@ static struct factPatternNode *GetNextPatternNode( /********************************************************************/ static int PatternNetworkToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -208,7 +216,7 @@ static int PatternNetworkToCode( thePatternNode != NULL; thePatternNode = GetNextPatternNode(thePatternNode)) { - networkFile = OpenFileIfNeeded(theEnv,networkFile,fileName,fileID,imageID,&fileCount, + networkFile = OpenFileIfNeeded(theEnv,networkFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, networkArrayVersion,headerFP, "struct factPatternNode",FactPrefix(),FALSE,NULL); if (networkFile == NULL) diff --git a/src/factcmp.h b/src/factcmp.h index fe3ed05..24e2081 100644 --- a/src/factcmp.h +++ b/src/factcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,12 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_factcmp @@ -42,4 +48,4 @@ LOCALE void FactPatternsCompilerSetup(void *); LOCALE void FactPatternNodeReference(void *,void *,FILE *,int,int); -#endif +#endif /* _H_factcmp */ diff --git a/src/factcom.c b/src/factcom.c index 101c52e..ec76b4d 100644 --- a/src/factcom.c +++ b/src/factcom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* FACT COMMANDS MODULE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Added environment parameter to GenClose. */ @@ -25,6 +26,25 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #include <stdio.h> @@ -72,12 +92,12 @@ /***************************************/ #if (! RUN_TIME) - static struct expr *AssertParse(void *,struct expr *,char *); + static struct expr *AssertParse(void *,struct expr *,const char *); #endif #if DEBUGGING_FUNCTIONS - static long int GetFactsArgument(void *,int,int); + static long long GetFactsArgument(void *,int,int); #endif - static struct expr *StandardLoadFact(void *,char *,struct token *); + static struct expr *StandardLoadFact(void *,const char *,struct token *); static DATA_OBJECT_PTR GetSaveFactsDeftemplateNames(void *,struct expr *,int,int *,int *); /***************************************/ @@ -104,12 +124,12 @@ globle void FactCommandDefinitions( EnvDefineFunction2(theEnv,"save-facts", 'b', PTIEF SaveFactsCommand, "SaveFactsCommand", "1*wk"); EnvDefineFunction2(theEnv,"load-facts", 'b', PTIEF LoadFactsCommand, "LoadFactsCommand", "11k"); - EnvDefineFunction2(theEnv,"fact-index", 'l', PTIEF FactIndexFunction,"FactIndexFunction", "11y"); + EnvDefineFunction2(theEnv,"fact-index", 'g', PTIEF FactIndexFunction,"FactIndexFunction", "11y"); AddFunctionParser(theEnv,"assert",AssertParse); FuncSeqOvlFlags(theEnv,"assert",FALSE,FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -132,7 +152,7 @@ globle void AssertCommand( int error = FALSE; int i; struct fact *theFact; - + /*===================================================*/ /* Set the default return value to the symbol FALSE. */ /*===================================================*/ @@ -177,6 +197,8 @@ globle void AssertCommand( /* the newly created fact. */ /*===================================================*/ + EnvIncrementClearReadyLocks(theEnv); + theField = newFact->theProposition.theFields; for (theExpression = theExpression->nextArg, i = 0; @@ -217,6 +239,8 @@ globle void AssertCommand( if (slotPtr != NULL) slotPtr = slotPtr->next; } + EnvDecrementClearReadyLocks(theEnv); + /*============================================*/ /* If an error occured while generating the */ /* fact's slot values, then abort the assert. */ @@ -254,7 +278,7 @@ globle void AssertCommand( globle void RetractCommand( void *theEnv) { - long int factIndex; + long long factIndex; struct fact *ptr; struct expr *theArgument; DATA_OBJECT theResult; @@ -309,7 +333,7 @@ globle void RetractCommand( else { char tempBuffer[20]; - sprintf(tempBuffer,"f-%ld",factIndex); + gensprintf(tempBuffer,"f-%lld",factIndex); CantFindItemErrorMessage(theEnv,"fact",tempBuffer); } } @@ -426,7 +450,7 @@ globle int GetFactDuplicationCommand( /* FactIndexFunction: H/L access routine */ /* for the fact-index function. */ /*******************************************/ -globle long int FactIndexFunction( +globle long long FactIndexFunction( void *theEnv) { DATA_OBJECT item; @@ -435,7 +459,7 @@ globle long int FactIndexFunction( /* Check for the correct number of arguments. */ /*============================================*/ - if (EnvArgCountCheck(theEnv,"fact-index",EXACTLY,1) == -1) return(-1L); + if (EnvArgCountCheck(theEnv,"fact-index",EXACTLY,1) == -1) return(-1LL); /*========================*/ /* Evaluate the argument. */ @@ -459,7 +483,7 @@ globle long int FactIndexFunction( /* return -1 for the fact index. */ /*================================================*/ - if (((struct fact *) GetValue(item))->garbage) return(-1L); + if (((struct fact *) GetValue(item))->garbage) return(-1LL); return (EnvFactIndex(theEnv,GetValue(item))); } @@ -474,7 +498,7 @@ globle void FactsCommand( void *theEnv) { int argumentCount; - long int start = UNSPECIFIED, end = UNSPECIFIED, max = UNSPECIFIED; + long long start = UNSPECIFIED, end = UNSPECIFIED, max = UNSPECIFIED; struct defmodule *theModule; DATA_OBJECT theValue; int argOffset; @@ -499,7 +523,7 @@ globle void FactsCommand( if (argumentCount == 0) { - EnvFacts(theEnv,WDISPLAY,theModule,(long) start,(long) end,(long) max); + EnvFacts(theEnv,WDISPLAY,theModule,start,end,max); return; } @@ -571,7 +595,7 @@ globle void FactsCommand( /* List the facts. */ /*=================*/ - EnvFacts(theEnv,WDISPLAY,theModule,(long) start,(long) end,(long) max); + EnvFacts(theEnv,WDISPLAY,theModule,start,end,max); } /*****************************************************/ @@ -579,11 +603,11 @@ globle void FactsCommand( /*****************************************************/ globle void EnvFacts( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheModule, - long start, - long end, - long max) + long long start, + long long end, + long long max) { struct fact *factPtr; long count = 0; @@ -693,12 +717,12 @@ globle void EnvFacts( /* A return value of -2 indicates that the value specified is */ /* invalid. */ /****************************************************************/ -static long int GetFactsArgument( +static long long GetFactsArgument( void *theEnv, int whichOne, int argumentCount) { - long int factIndex; + long long factIndex; DATA_OBJECT theValue; if (whichOne > argumentCount) return(UNSPECIFIED); @@ -769,9 +793,9 @@ globle void AssertStringFunction( globle int SaveFactsCommand( void *theEnv) { - char *fileName; + const char *fileName; int numArgs, saveCode = LOCAL_SAVE; - char *argument; + const char *argument; DATA_OBJECT theValue; struct expr *theList = NULL; @@ -822,7 +846,7 @@ globle int SaveFactsCommand( /* Call the SaveFacts driver routine. */ /*====================================*/ - if (EnvSaveFacts(theEnv,fileName,saveCode,theList) == FALSE) + if (EnvSaveFactsDriver(theEnv,fileName,saveCode,theList) == FALSE) { return(FALSE); } return(TRUE); @@ -835,7 +859,7 @@ globle int SaveFactsCommand( globle int LoadFactsCommand( void *theEnv) { - char *fileName; + const char *fileName; /*============================================*/ /* Check for the correct number of arguments. */ @@ -863,7 +887,18 @@ globle int LoadFactsCommand( /**************************************************************/ globle intBool EnvSaveFacts( void *theEnv, - char *fileName, + const char *fileName, + int saveCode) + { + return EnvSaveFactsDriver(theEnv,fileName,saveCode,NULL); + } + +/********************************************************************/ +/* EnvSaveFactsDriver: C access routine for the save-facts command. */ +/********************************************************************/ +globle intBool EnvSaveFactsDriver( + void *theEnv, + const char *fileName, int saveCode, struct expr *theList) { @@ -1094,7 +1129,7 @@ static DATA_OBJECT_PTR GetSaveFactsDeftemplateNames( if (saveCode == LOCAL_SAVE) { theDeftemplate = (struct deftemplate *) - EnvFindDeftemplate(theEnv,ValueToString(theDOArray[i].value)); + EnvFindDeftemplateInModule(theEnv,ValueToString(theDOArray[i].value)); if (theDeftemplate == NULL) { *error = TRUE; @@ -1139,7 +1174,7 @@ static DATA_OBJECT_PTR GetSaveFactsDeftemplateNames( /**************************************************************/ globle intBool EnvLoadFacts( void *theEnv, - char *fileName) + const char *fileName) { FILE *filePtr; struct token theToken; @@ -1192,10 +1227,10 @@ globle intBool EnvLoadFacts( /*********************************************/ globle intBool EnvLoadFactsFromString( void *theEnv, - char *theString, - int theMax) + const char *theString, + long theMax) { - char * theStrRouter = "*** load-facts-from-string ***"; + const char *theStrRouter = "*** load-facts-from-string ***"; struct token theToken; struct expr *testPtr; DATA_OBJECT rv; @@ -1205,7 +1240,7 @@ globle intBool EnvLoadFactsFromString( /*==========================*/ if ((theMax == -1) ? (!OpenStringSource(theEnv,theStrRouter,theString,0)) : - (!OpenTextSource(theEnv,theStrRouter,theString,0,(unsigned) theMax))) + (!OpenTextSource(theEnv,theStrRouter,theString,0,(size_t) theMax))) return(FALSE); /*=================*/ @@ -1241,7 +1276,7 @@ globle intBool EnvLoadFactsFromString( /**************************************************************************/ static struct expr *StandardLoadFact( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken) { int error = FALSE; @@ -1279,7 +1314,7 @@ static struct expr *StandardLoadFact( static struct expr *AssertParse( void *theEnv, struct expr *top, - char *logicalName) + const char *logicalName) { int error; struct expr *rv; @@ -1295,6 +1330,48 @@ static struct expr *AssertParse( #endif /* (! RUN_TIME) */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + +globle void Facts( + const char *logicalName, + void *vTheModule, + long long start, + long long end, + long long max) + { + EnvFacts(GetCurrentEnvironment(),logicalName,vTheModule,start,end,max); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +globle intBool LoadFacts( + const char *fileName) + { + return EnvLoadFacts(GetCurrentEnvironment(),fileName); + } + +globle intBool SaveFacts( + const char *fileName, + int saveCode) + { + return EnvSaveFacts(GetCurrentEnvironment(),fileName,saveCode); + } + +globle intBool LoadFactsFromString( + const char *theString, + int theMax) + { + return EnvLoadFactsFromString(GetCurrentEnvironment(),theString,theMax); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/factcom.h b/src/factcom.h index f4a10f8..f29e30e 100644 --- a/src/factcom.h +++ b/src/factcom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* FACT COMMANDS HEADER FILE */ /*******************************************************/ @@ -16,6 +16,30 @@ /* */ /* Revision History: */ /* */ +/* Revision History: */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ /*************************************************************/ #ifndef _H_factcom @@ -35,33 +59,33 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Facts(theEnv,a,b,c,d,e) EnvFacts(theEnv,a,b,c,d,e) -#define LoadFacts(theEnv,a) EnvLoadFacts(theEnv,a) -#define SaveFacts(theEnv,a,b,c) EnvSaveFacts(theEnv,a,b,c) -#define LoadFactsFromString(theEnv,a,b) EnvLoadFactsFromString(theEnv,a,b) -#else -#define Facts(a,b,c,d,e) EnvFacts(GetCurrentEnvironment(),a,b,c,d,e) -#define LoadFacts(a) EnvLoadFacts(GetCurrentEnvironment(),a) -#define SaveFacts(a,b,c) EnvSaveFacts(GetCurrentEnvironment(),a,b,c) -#define LoadFactsFromString(a,b) EnvLoadFactsFromString(GetCurrentEnvironment(),a,b) -#endif - LOCALE void FactCommandDefinitions(void *); LOCALE void AssertCommand(void *,DATA_OBJECT_PTR); LOCALE void RetractCommand(void *); LOCALE void AssertStringFunction(void *,DATA_OBJECT_PTR); LOCALE void FactsCommand(void *); - LOCALE void EnvFacts(void *,char *,void *,long,long,long); + LOCALE void EnvFacts(void *,const char *,void *,long long,long long,long long); LOCALE int SetFactDuplicationCommand(void *); LOCALE int GetFactDuplicationCommand(void *); LOCALE int SaveFactsCommand(void *); LOCALE int LoadFactsCommand(void *); - LOCALE int EnvSaveFacts(void *,char *,int,struct expr *); - LOCALE int EnvLoadFacts(void *,char *); - LOCALE int EnvLoadFactsFromString(void *,char *,int); - LOCALE long int FactIndexFunction(void *); + LOCALE int EnvSaveFacts(void *,const char *,int); + LOCALE int EnvSaveFactsDriver(void *,const char *,int,struct expr *); + LOCALE int EnvLoadFacts(void *,const char *); + LOCALE int EnvLoadFactsFromString(void *,const char *,long); + LOCALE long long FactIndexFunction(void *); + +#if ALLOW_ENVIRONMENT_GLOBALS +#if DEBUGGING_FUNCTIONS + LOCALE void Facts(const char *,void *,long long,long long,long long); #endif + LOCALE intBool LoadFacts(const char *); + LOCALE intBool SaveFacts(const char *,int); + LOCALE intBool LoadFactsFromString(const char *,int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_factcom */ diff --git a/src/factfun.c b/src/factfun.c index 32feb10..d71ac4e 100644 --- a/src/factfun.c +++ b/src/factfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* FACT FUNCTIONS MODULE */ /*******************************************************/ @@ -40,6 +40,7 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -47,6 +48,20 @@ /* */ /* 6.24: Added ppfact function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ #include <stdio.h> @@ -65,6 +80,7 @@ #include "prntutil.h" #include "tmpltutl.h" #include "router.h" +#include "sysdep.h" #include "factfun.h" @@ -82,7 +98,7 @@ globle void FactFunctionDefinitions( EnvDefineFunction2(theEnv,"get-fact-list",'m',PTIEF GetFactListFunction,"GetFactListFunction","01w"); EnvDefineFunction2(theEnv,"ppfact",'v',PTIEF PPFactFunction,"PPFactFunction","13*z"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -117,19 +133,16 @@ globle void *FactRelation( return((void *) theFact->whichDeftemplate->header.name); } - + /****************************************/ /* EnvFactDeftemplate: C access routine */ /* to retrieve a fact's deftemplate. */ /****************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void *EnvFactDeftemplate( void *theEnv, void *vTheFact) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -158,14 +171,11 @@ globle int FactExistpFunction( /* EnvFactExistp: C access routine */ /* for the fact-existp function. */ /***********************************/ -#if IBM_TBC -#pragma argsused -#endif globle int EnvFactExistp( void *theEnv, void *vTheFact) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif struct fact *theFact = (struct fact *) vTheFact; @@ -229,7 +239,7 @@ globle void FactSlotValueFunction( globle void FactSlotValue( void *theEnv, void *vTheFact, - char *theSlotName, + const char *theSlotName, DATA_OBJECT *returnValue) { struct fact *theFact = (struct fact *) vTheFact; @@ -507,7 +517,7 @@ globle void EnvGetFactList( RestoreCurrentModule(theEnv); UpdateDeftemplateScope(theEnv); } - + /**************************************/ /* PPFactFunction: H/L access routine */ /* for the ppfact function. */ @@ -517,11 +527,7 @@ globle void PPFactFunction( { struct fact *theFact; int numberOfArguments; -#if IBM_TBC - char *logicalName; /* Avoids warning */ -#else - char *logicalName = NULL; /* Avoids warning */ -#endif + const char *logicalName = NULL; /* Avoids warning */ int ignoreDefaults = FALSE; DATA_OBJECT theArg; @@ -535,10 +541,10 @@ globle void PPFactFunction( /*===============================================================*/ if (numberOfArguments == 1) - { logicalName = "stdout"; } + { logicalName = STDOUT; } else { - logicalName = GetLogicalName(theEnv,2,"stdout"); + logicalName = GetLogicalName(theEnv,2,STDOUT); if (logicalName == NULL) { IllegalLogicalNameMessage(theEnv,"ppfact"); @@ -547,12 +553,12 @@ globle void PPFactFunction( return; } } - + /*=========================================*/ /* Should slot values be printed if they */ /* are the same as the default slot value. */ /*=========================================*/ - + if (numberOfArguments == 3) { EnvRtnUnknown(theEnv,3,&theArg); @@ -562,7 +568,7 @@ globle void PPFactFunction( else { ignoreDefaults = TRUE; } } - + /*============================================================*/ /* Determine if any router recognizes the output destination. */ /*============================================================*/ @@ -582,16 +588,13 @@ globle void PPFactFunction( /* EnvPPFact: C access routine */ /* for the ppfact function. */ /*******************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvPPFact( void *theEnv, void *vTheFact, - char *logicalName, + const char *logicalName, int ignoreDefaults) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif struct fact *theFact = (struct fact *) vTheFact; @@ -601,22 +604,22 @@ globle void EnvPPFact( if (theFact->garbage) return; PrintFact(theEnv,logicalName,theFact,TRUE,ignoreDefaults); - + EnvPrintRouter(theEnv,logicalName,"\n"); } - + /**************************************************************/ /* GetFactAddressOrIndexArgument: Retrieves an argument for a */ /* function which should be a reference to a valid fact. */ /**************************************************************/ globle struct fact *GetFactAddressOrIndexArgument( void *theEnv, - char *theFunction, + const char *theFunction, int position, int noFactError) { DATA_OBJECT item; - long factIndex; + long long factIndex; struct fact *theFact; char tempBuffer[20]; @@ -639,7 +642,7 @@ globle struct fact *GetFactAddressOrIndexArgument( theFact = FindIndexedFact(theEnv,factIndex); if ((theFact == NULL) && noFactError) { - sprintf(tempBuffer,"f-%ld",factIndex); + gensprintf(tempBuffer,"f-%lld",factIndex); CantFindItemErrorMessage(theEnv,"fact",tempBuffer); return(NULL); } @@ -651,6 +654,48 @@ globle struct fact *GetFactAddressOrIndexArgument( return(NULL); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *FactDeftemplate( + void *vTheFact) + { + return EnvFactDeftemplate(GetCurrentEnvironment(),vTheFact); + } + +globle int FactExistp( + void *vTheFact) + { + return EnvFactExistp(GetCurrentEnvironment(),vTheFact); + } + +globle void FactSlotNames( + void *vTheFact, + DATA_OBJECT *returnValue) + { + EnvFactSlotNames(GetCurrentEnvironment(),vTheFact,returnValue); + } + +globle void GetFactList( + DATA_OBJECT_PTR returnValue, + void *vTheModule) + { + EnvGetFactList(GetCurrentEnvironment(),returnValue,vTheModule); + } + +globle void PPFact( + void *vTheFact, + const char *logicalName, + int ignoreDefaults) + { + EnvPPFact(GetCurrentEnvironment(),vTheFact,logicalName,ignoreDefaults); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/factfun.h b/src/factfun.h index 3b8ffce..3fad09f 100644 --- a/src/factfun.h +++ b/src/factfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -15,10 +15,24 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ -/* 6.24: Added ppfact command. */ +/* 6.24: Added ppfact function. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -39,20 +53,6 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define FactDeftemplate(theEnv,a) EnvFactDeftemplate(theEnv,a) -#define FactExistp(theEnv,a) EnvFactExistp(theEnv,a) -#define FactSlotNames(theEnv,a,b) EnvFactSlotNames(theEnv,a,b) -#define GetFactList(theEnv,a,b) EnvGetFactList(theEnv,a,b) -#define PPFact(theEnv,a,b,c) EnvPPFact(theEnv,a,b,c) -#else -#define FactDeftemplate(a) EnvFactDeftemplate(GetCurrentEnvironment(),a) -#define FactExistp(a) EnvFactExistp(GetCurrentEnvironment(),a) -#define FactSlotNames(a,b) EnvFactSlotNames(GetCurrentEnvironment(),a,b) -#define GetFactList(a,b) EnvGetFactList(GetCurrentEnvironment(),a,b) -#define PPFact(a,b,c) EnvPPFact(GetCurrentEnvironment(),a,b,c) -#endif - LOCALE void FactFunctionDefinitions(void *); LOCALE void *FactRelationFunction(void *); LOCALE void *FactRelation(void *); @@ -60,14 +60,24 @@ LOCALE int FactExistpFunction(void *); LOCALE int EnvFactExistp(void *,void *); LOCALE void FactSlotValueFunction(void *,DATA_OBJECT *); - LOCALE void FactSlotValue(void *,void *,char *,DATA_OBJECT *); + LOCALE void FactSlotValue(void *,void *,const char *,DATA_OBJECT *); LOCALE void FactSlotNamesFunction(void *,DATA_OBJECT *); LOCALE void EnvFactSlotNames(void *,void *,DATA_OBJECT *); LOCALE void GetFactListFunction(void *,DATA_OBJECT *); LOCALE void EnvGetFactList(void *,DATA_OBJECT *,void *); LOCALE void PPFactFunction(void *); - LOCALE void EnvPPFact(void *,void *,char *,int); - LOCALE struct fact *GetFactAddressOrIndexArgument(void *,char *,int,int); + LOCALE void EnvPPFact(void *,void *,const char *,int); + LOCALE struct fact *GetFactAddressOrIndexArgument(void *,const char *,int,int); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void *FactDeftemplate(void *); + LOCALE int FactExistp(void *); + LOCALE void FactSlotNames(void *,DATA_OBJECT *); + LOCALE void GetFactList(DATA_OBJECT_PTR,void *); + LOCALE void PPFact(void *,const char *,int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_factfun */ diff --git a/src/factgen.c b/src/factgen.c index 2e91074..5fe4fa6 100644 --- a/src/factgen.c +++ b/src/factgen.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE FUNCTION GENERATION MODULE */ /*******************************************************/ @@ -21,6 +21,11 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Support for performance optimizations. */ +/* */ +/* Increased maximum values for pattern/slot */ +/* indices. */ +/* */ /*************************************************************/ #define _FACTGEN_SOURCE_ @@ -55,7 +60,7 @@ #define FACTGEN_DATA 2 struct factgenData - { + { globle struct entityRecord FactJNGV1Info; globle struct entityRecord FactJNGV2Info; globle struct entityRecord FactJNGV3Info; @@ -70,7 +75,7 @@ struct factgenData globle struct entityRecord FactPNConstant1Info; globle struct entityRecord FactPNConstant2Info; }; - + #define FactgenData(theEnv) ((struct factgenData *) GetEnvironmentData(theEnv,FACTGEN_DATA)) /***************************************/ @@ -78,9 +83,9 @@ struct factgenData /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static void *FactGetVarJN1(void *,struct lhsParseNode *); - static void *FactGetVarJN2(void *,struct lhsParseNode *); - static void *FactGetVarJN3(void *,struct lhsParseNode *); + static void *FactGetVarJN1(void *,struct lhsParseNode *,int); + static void *FactGetVarJN2(void *,struct lhsParseNode *,int); + static void *FactGetVarJN3(void *,struct lhsParseNode *,int); static void *FactGetVarPN1(void *,struct lhsParseNode *); static void *FactGetVarPN2(void *,struct lhsParseNode *); static void *FactGetVarPN3(void *,struct lhsParseNode *); @@ -98,99 +103,99 @@ globle void InitializeFactReteFunctions( PrintFactJNGetVar1, PrintFactJNGetVar1,NULL, FactJNGetVar1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factJNGV2Info = { "FACT_JN_VAR2", FACT_JN_VAR2,0,1,0, PrintFactJNGetVar2, PrintFactJNGetVar2,NULL, FactJNGetVar2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factJNGV3Info = { "FACT_JN_VAR3", FACT_JN_VAR3,0,1,0, PrintFactJNGetVar3, PrintFactJNGetVar3,NULL, FactJNGetVar3, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNGV1Info = { "FACT_PN_VAR1", FACT_PN_VAR1,0,1,0, PrintFactPNGetVar1, PrintFactPNGetVar1,NULL, FactPNGetVar1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNGV2Info = { "FACT_PN_VAR2", FACT_PN_VAR2,0,1,0, PrintFactPNGetVar2, PrintFactPNGetVar2,NULL, FactPNGetVar2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNGV3Info = { "FACT_PN_VAR3", FACT_PN_VAR3,0,1,0, PrintFactPNGetVar3, PrintFactPNGetVar3,NULL, FactPNGetVar3, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factJNCV1Info = { "FACT_JN_CMP1", FACT_JN_CMP1,0,1,1, PrintFactJNCompVars1, PrintFactJNCompVars1,NULL, FactJNCompVars1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factJNCV2Info = { "FACT_JN_CMP2", FACT_JN_CMP2,0,1,1, PrintFactJNCompVars2, PrintFactJNCompVars2,NULL, FactJNCompVars2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNCV1Info = { "FACT_PN_CMP1", FACT_PN_CMP1,0,1,1, PrintFactPNCompVars1, PrintFactPNCompVars1,NULL, FactPNCompVars1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factStoreMFInfo = { "FACT_STORE_MULTIFIELD", FACT_STORE_MULTIFIELD,0,1,0, NULL,NULL,NULL, FactStoreMultifield, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factSlotLengthInfo = { "FACT_SLOT_LENGTH", FACT_SLOT_LENGTH,0,1,0, PrintFactSlotLength, PrintFactSlotLength,NULL, FactSlotLength, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNConstant1Info = { "FACT_PN_CONSTANT1", FACT_PN_CONSTANT1,0,1,1, PrintFactPNConstant1, PrintFactPNConstant1,NULL, FactPNConstant1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord factPNConstant2Info = { "FACT_PN_CONSTANT2", FACT_PN_CONSTANT2,0,1,1, PrintFactPNConstant2, PrintFactPNConstant2,NULL, FactPNConstant2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; AllocateEnvironmentData(theEnv,FACTGEN_DATA,sizeof(struct factgenData),NULL); - - memcpy(&FactgenData(theEnv)->FactJNGV1Info,&factJNGV1Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactJNGV2Info,&factJNGV2Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactJNGV3Info,&factJNGV3Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNGV1Info,&factPNGV1Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNGV2Info,&factPNGV2Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNGV3Info,&factPNGV3Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactJNCV1Info,&factJNCV1Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactJNCV2Info,&factJNCV2Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNCV1Info,&factPNCV1Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactStoreMFInfo,&factStoreMFInfo,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactSlotLengthInfo,&factSlotLengthInfo,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNConstant1Info,&factPNConstant1Info,sizeof(struct entityRecord)); - memcpy(&FactgenData(theEnv)->FactPNConstant2Info,&factPNConstant2Info,sizeof(struct entityRecord)); - + + memcpy(&FactgenData(theEnv)->FactJNGV1Info,&factJNGV1Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactJNGV2Info,&factJNGV2Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactJNGV3Info,&factJNGV3Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNGV1Info,&factPNGV1Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNGV2Info,&factPNGV2Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNGV3Info,&factPNGV3Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactJNCV1Info,&factJNCV1Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactJNCV2Info,&factJNCV2Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNCV1Info,&factPNCV1Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactStoreMFInfo,&factStoreMFInfo,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactSlotLengthInfo,&factSlotLengthInfo,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNConstant1Info,&factPNConstant1Info,sizeof(struct entityRecord)); + memcpy(&FactgenData(theEnv)->FactPNConstant2Info,&factPNConstant2Info,sizeof(struct entityRecord)); + InstallPrimitive(theEnv,(ENTITY_RECORD_PTR) &FactData(theEnv)->FactInfo,FACT_ADDRESS); InstallPrimitive(theEnv,&FactgenData(theEnv)->FactJNGV1Info,FACT_JN_VAR1); InstallPrimitive(theEnv,&FactgenData(theEnv)->FactJNGV2Info,FACT_JN_VAR2); @@ -237,9 +242,9 @@ globle struct expr *FactGenPNConstant( if (theField->negated) hack1.testForEquality = FALSE; else hack1.testForEquality = TRUE; - hack1.whichSlot = theField->slotNumber - 1; + hack1.whichSlot = (unsigned short) (theField->slotNumber - 1); - top = GenConstant(theEnv,FACT_PN_CONSTANT1,AddBitMap(theEnv,&hack1,sizeof(struct factConstantPN1Call))); + top = GenConstant(theEnv,FACT_PN_CONSTANT1,EnvAddBitMap(theEnv,&hack1,sizeof(struct factConstantPN1Call))); top->argList = GenConstant(theEnv,theField->type,theField->value); @@ -261,7 +266,7 @@ globle struct expr *FactGenPNConstant( if (theField->negated) hack2.testForEquality = FALSE; else hack2.testForEquality = TRUE; - hack2.whichSlot = theField->slotNumber - 1; + hack2.whichSlot = (unsigned short) (theField->slotNumber - 1); if (theField->multiFieldsBefore == 0) { @@ -274,7 +279,7 @@ globle struct expr *FactGenPNConstant( hack2.offset = theField->singleFieldsAfter; } - top = GenConstant(theEnv,FACT_PN_CONSTANT2,AddBitMap(theEnv,&hack2,sizeof(struct factConstantPN2Call))); + top = GenConstant(theEnv,FACT_PN_CONSTANT2,EnvAddBitMap(theEnv,&hack2,sizeof(struct factConstantPN2Call))); top->argList = GenConstant(theEnv,theField->type,theField->value); @@ -333,7 +338,7 @@ globle struct expr *FactGenGetfield( /* value to be retrieved. */ /*=====================================================*/ - if (((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE)) && + if (((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE) || ConstantType(theNode->type)) && ((theNode->multiFieldsBefore == 0) || ((theNode->multiFieldsBefore == 1) && (theNode->multiFieldsAfter == 0)))) { return(GenConstant(theEnv,FACT_PN_VAR3,FactGetVarPN3(theEnv,theNode))); } @@ -357,14 +362,15 @@ globle struct expr *FactGenGetfield( /**************************************************/ globle struct expr *FactGenGetvar( void *theEnv, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { /*====================================================*/ /* Generate call to retrieve single field slot value. */ /*====================================================*/ if ((theNode->slotNumber > 0) && (theNode->withinMultifieldSlot == FALSE)) - { return(GenConstant(theEnv,FACT_JN_VAR2,FactGetVarJN2(theEnv,theNode))); } + { return(GenConstant(theEnv,FACT_JN_VAR2,FactGetVarJN2(theEnv,theNode,side))); } /*=====================================================*/ /* Generate call to retrieve a value from a multifield */ @@ -376,19 +382,19 @@ globle struct expr *FactGenGetvar( if (((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE)) && ((theNode->multiFieldsBefore == 0) || ((theNode->multiFieldsBefore == 1) && (theNode->multiFieldsAfter == 0)))) - { return(GenConstant(theEnv,FACT_JN_VAR3,FactGetVarJN3(theEnv,theNode))); } + { return(GenConstant(theEnv,FACT_JN_VAR3,FactGetVarJN3(theEnv,theNode,side))); } if (((theNode->type == MF_WILDCARD) || (theNode->type == MF_VARIABLE)) && (theNode->multiFieldsBefore == 0) && (theNode->multiFieldsAfter == 0)) - { return(GenConstant(theEnv,FACT_JN_VAR3,FactGetVarJN3(theEnv,theNode))); } + { return(GenConstant(theEnv,FACT_JN_VAR3,FactGetVarJN3(theEnv,theNode,side))); } /*=========================================*/ /* Generate call to retrieve a value using */ /* the most general retrieval function. */ /*=========================================*/ - return(GenConstant(theEnv,FACT_JN_VAR1,FactGetVarJN1(theEnv,theNode))); + return(GenConstant(theEnv,FACT_JN_VAR1,FactGetVarJN1(theEnv,theNode,side))); } /**************************************************************/ @@ -448,7 +454,7 @@ globle struct expr *FactGenCheckLength( /* Generate call to test the length of a multifield slot. */ /*========================================================*/ - return(GenConstant(theEnv,FACT_SLOT_LENGTH,AddBitMap(theEnv,&hack,sizeof(struct factCheckLengthPNCall)))); + return(GenConstant(theEnv,FACT_SLOT_LENGTH,EnvAddBitMap(theEnv,&hack,sizeof(struct factCheckLengthPNCall)))); } /**************************************************************/ @@ -468,7 +474,7 @@ globle struct expr *FactGenCheckZeroLength( hack.exactly = 1; hack.minLength = 0; - return(GenConstant(theEnv,FACT_SLOT_LENGTH,AddBitMap(theEnv,&hack,sizeof(struct factCheckLengthPNCall)))); + return(GenConstant(theEnv,FACT_SLOT_LENGTH,EnvAddBitMap(theEnv,&hack,sizeof(struct factCheckLengthPNCall)))); } /*********************************************************************/ @@ -479,7 +485,8 @@ globle struct expr *FactGenCheckZeroLength( globle void FactReplaceGetvar( void *theEnv, struct expr *theItem, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { /*====================================================*/ /* Generate call to retrieve single field slot value. */ @@ -488,7 +495,7 @@ globle void FactReplaceGetvar( if ((theNode->slotNumber > 0) && (theNode->withinMultifieldSlot == FALSE)) { theItem->type = FACT_JN_VAR2; - theItem->value = FactGetVarJN2(theEnv,theNode); + theItem->value = FactGetVarJN2(theEnv,theNode,side); return; } @@ -504,7 +511,7 @@ globle void FactReplaceGetvar( ((theNode->multiFieldsBefore == 1) && (theNode->multiFieldsAfter == 0)))) { theItem->type = FACT_JN_VAR3; - theItem->value = FactGetVarJN3(theEnv,theNode); + theItem->value = FactGetVarJN3(theEnv,theNode,side); return; } @@ -513,7 +520,7 @@ globle void FactReplaceGetvar( (theNode->multiFieldsAfter == 0)) { theItem->type = FACT_JN_VAR3; - theItem->value = FactGetVarJN3(theEnv,theNode); + theItem->value = FactGetVarJN3(theEnv,theNode,side); return; } @@ -523,7 +530,7 @@ globle void FactReplaceGetvar( /*=========================================*/ theItem->type = FACT_JN_VAR1; - theItem->value = FactGetVarJN1(theEnv,theNode); + theItem->value = FactGetVarJN1(theEnv,theNode,side); } /***********************************************************************/ @@ -591,7 +598,8 @@ globle void FactReplaceGetfield( /*************************************************************/ static void *FactGetVarJN1( void *theEnv, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { struct factGetVarJN1Call hack; @@ -601,6 +609,29 @@ static void *FactGetVarJN1( ClearBitString(&hack,sizeof(struct factGetVarJN1Call)); + /*=========================================*/ + /* Store the position in the partial match */ + /* from which the fact will be retrieved. */ + /*=========================================*/ + + if (side == LHS) + { + hack.lhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else if (side == RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) 0; + } + else if (side == NESTED_RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else + { hack.whichPattern = (unsigned short) theNode->joinDepth; } + /*========================================*/ /* A slot value of zero indicates that we */ /* want the pattern address returned. */ @@ -643,18 +674,11 @@ static void *FactGetVarJN1( hack.whichField = (unsigned short) (theNode->index - 1); } - /*=========================================*/ - /* Store the position in the partial match */ - /* from which the fact will be retrieved. */ - /*=========================================*/ - - hack.whichPattern = (unsigned short) (theNode->pattern - 1); - /*=============================*/ /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarJN1Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarJN1Call))); } /**************************************************************/ @@ -667,7 +691,8 @@ static void *FactGetVarJN1( /**************************************************************/ static void *FactGetVarJN2( void *theEnv, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { struct factGetVarJN2Call hack; @@ -684,13 +709,30 @@ static void *FactGetVarJN2( /*=====================================================*/ hack.whichSlot = (unsigned short) (theNode->slotNumber - 1); - hack.whichPattern = (unsigned short) (theNode->pattern - 1); + + if (side == LHS) + { + hack.lhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else if (side == RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) 0; + } + else if (side == NESTED_RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else + { hack.whichPattern = (unsigned short) theNode->joinDepth; } /*=============================*/ /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarJN2Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarJN2Call))); } /*************************************************************/ @@ -707,7 +749,8 @@ static void *FactGetVarJN2( /*************************************************************/ static void *FactGetVarJN3( void *theEnv, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { struct factGetVarJN3Call hack; @@ -724,7 +767,24 @@ static void *FactGetVarJN3( /*=====================================================*/ hack.whichSlot = (unsigned short) (theNode->slotNumber - 1); - hack.whichPattern = (unsigned short) (theNode->pattern - 1); + + if (side == LHS) + { + hack.lhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else if (side == RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) 0; + } + else if (side == NESTED_RHS) + { + hack.rhs = 1; + hack.whichPattern = (unsigned short) theNode->joinDepth; + } + else + { hack.whichPattern = (unsigned short) theNode->joinDepth; } /*==============================================================*/ /* If a single field variable value is being retrieved, then... */ @@ -765,7 +825,7 @@ static void *FactGetVarJN3( /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarJN3Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarJN3Call))); } /*============================================================*/ @@ -788,7 +848,7 @@ static void *FactGetVarJN3( /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarJN3Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarJN3Call))); } /**************************************************************/ @@ -857,7 +917,7 @@ static void *FactGetVarPN1( /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarPN1Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarPN1Call))); } /***************************************************************/ @@ -890,7 +950,7 @@ static void *FactGetVarPN2( /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarPN2Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarPN2Call))); } /*************************************************************/ @@ -927,7 +987,7 @@ static void *FactGetVarPN3( /* If a single field variable value is being retrieved, then... */ /*==============================================================*/ - if ((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE)) + if ((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE) || ConstantType(theNode->type)) { /*=========================================================*/ /* If no multifield values occur before the variable, then */ @@ -958,7 +1018,7 @@ static void *FactGetVarPN3( hack.endOffset = theNode->singleFieldsAfter; } - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarPN3Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarPN3Call))); } /*============================================================*/ @@ -981,7 +1041,7 @@ static void *FactGetVarPN3( /* Return the argument bitmap. */ /*=============================*/ - return(AddBitMap(theEnv,&hack,sizeof(struct factGetVarPN3Call))); + return(EnvAddBitMap(theEnv,&hack,sizeof(struct factGetVarPN3Call))); } /*************************************************************/ @@ -1015,13 +1075,13 @@ globle struct expr *FactPNVariableComparison( { hack.pass = 0; hack.fail = 0; - hack.field1 = (unsigned int) selfNode->slotNumber - 1; - hack.field2 = (unsigned int) referringNode->slotNumber - 1; + hack.field1 = (unsigned short) (selfNode->slotNumber - 1); + hack.field2 = (unsigned short) (referringNode->slotNumber - 1); if (selfNode->negated) hack.fail = 1; else hack.pass = 1; - top = GenConstant(theEnv,FACT_PN_CMP1,AddBitMap(theEnv,&hack,sizeof(struct factCompVarsPN1Call))); + top = GenConstant(theEnv,FACT_PN_CMP1,EnvAddBitMap(theEnv,&hack,sizeof(struct factCompVarsPN1Call))); } /*================================================================*/ @@ -1054,11 +1114,13 @@ globle struct expr *FactPNVariableComparison( globle struct expr *FactJNVariableComparison( void *theEnv, struct lhsParseNode *selfNode, - struct lhsParseNode *referringNode) + struct lhsParseNode *referringNode, + int nandJoin) { struct expr *top; struct factCompVarsJN1Call hack1; struct factCompVarsJN2Call hack2; + struct lhsParseNode *firstNode; /*================================================================*/ /* If two single field slots of a deftemplate are being compared, */ @@ -1073,15 +1135,31 @@ globle struct expr *FactJNVariableComparison( ClearBitString(&hack1,sizeof(struct factCompVarsJN1Call)); hack1.pass = 0; hack1.fail = 0; - hack1.slot1 = (unsigned int) selfNode->slotNumber - 1; - hack1.pattern2 = (unsigned int) referringNode->pattern; + + if (nandJoin) + { firstNode = referringNode; } + else + { firstNode = selfNode; } + + hack1.slot1 = (unsigned short) (firstNode->slotNumber - 1); + + if (nandJoin) + { hack1.pattern1 = (unsigned short) referringNode->joinDepth; } + else + { hack1.pattern1 = 0; } + + hack1.p1rhs = TRUE; + hack1.p2lhs = TRUE; + + hack1.pattern2 = (unsigned short) referringNode->joinDepth; + if (referringNode->index < 0) hack1.slot2 = 0; - else hack1.slot2 = (unsigned int) referringNode->slotNumber - 1; + else hack1.slot2 = (unsigned short) (referringNode->slotNumber - 1); if (selfNode->negated) hack1.fail = 1; else hack1.pass = 1; - top = GenConstant(theEnv,FACT_JN_CMP1,AddBitMap(theEnv,&hack1,sizeof(struct factCompVarsJN1Call))); + top = GenConstant(theEnv,FACT_JN_CMP1,EnvAddBitMap(theEnv,&hack1,sizeof(struct factCompVarsJN1Call))); } /*===============================================================*/ @@ -1105,19 +1183,34 @@ globle struct expr *FactJNVariableComparison( ClearBitString(&hack2,sizeof(struct factCompVarsJN2Call)); hack2.pass = 0; hack2.fail = 0; - hack2.slot1 = (unsigned int) selfNode->slotNumber - 1; - hack2.pattern2 = (unsigned int) referringNode->pattern; - hack2.slot2 = (unsigned int) referringNode->slotNumber - 1; - if (selfNode->multiFieldsBefore == 0) + if (nandJoin) + { firstNode = referringNode; } + else + { firstNode = selfNode; } + + hack2.slot1 = (unsigned short) (firstNode->slotNumber - 1); + + if (nandJoin) + { hack2.pattern1 = (unsigned short) referringNode->joinDepth; } + else + { hack2.pattern1 = 0; } + + hack2.p1rhs = TRUE; + hack2.p2lhs = TRUE; + + hack2.pattern2 = (unsigned short) referringNode->joinDepth; + hack2.slot2 = (unsigned short) (referringNode->slotNumber - 1); + + if (firstNode->multiFieldsBefore == 0) { hack2.fromBeginning1 = 1; - hack2.offset1 = selfNode->singleFieldsBefore; + hack2.offset1 = firstNode->singleFieldsBefore; } else { hack2.fromBeginning1 = 0; - hack2.offset1 = selfNode->singleFieldsAfter; + hack2.offset1 = firstNode->singleFieldsAfter; } if (referringNode->multiFieldsBefore == 0) @@ -1134,7 +1227,7 @@ globle struct expr *FactJNVariableComparison( if (selfNode->negated) hack2.fail = 1; else hack2.pass = 1; - top = GenConstant(theEnv,FACT_JN_CMP2,AddBitMap(theEnv,&hack2,sizeof(struct factCompVarsJN2Call))); + top = GenConstant(theEnv,FACT_JN_CMP2,EnvAddBitMap(theEnv,&hack2,sizeof(struct factCompVarsJN2Call))); } /*===============================================================*/ @@ -1150,8 +1243,12 @@ globle struct expr *FactJNVariableComparison( else { top = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_EQ); } - top->argList = FactGenGetvar(theEnv,selfNode); - top->argList->nextArg = FactGenGetvar(theEnv,referringNode); + if (nandJoin) + { top->argList = FactGenGetvar(theEnv,selfNode,NESTED_RHS); } + else + { top->argList = FactGenGetvar(theEnv,selfNode,RHS); } + + top->argList->nextArg = FactGenGetvar(theEnv,referringNode,LHS); } /*======================================*/ diff --git a/src/factgen.h b/src/factgen.h index 2f04b85..d28b83e 100644 --- a/src/factgen.h +++ b/src/factgen.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE FUNCTION GENERATION HEADER FILE */ /*******************************************************/ @@ -16,6 +16,11 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Support for performance optimizations. */ +/* */ +/* Increased maximum values for pattern/slot */ +/* indices. */ +/* */ /*************************************************************/ #ifndef _H_factgen @@ -82,7 +87,7 @@ struct factGetVarPN3Call struct factConstantPN1Call { unsigned int testForEquality : 1; - unsigned int whichSlot : 8; + unsigned short whichSlot; }; /******************************************************************/ @@ -96,8 +101,8 @@ struct factConstantPN2Call { unsigned int testForEquality : 1; unsigned int fromBeginning : 1; - unsigned int offset : 8; - unsigned int whichSlot : 8; + unsigned short offset; + unsigned short whichSlot; }; /**********************************************************/ @@ -109,6 +114,8 @@ struct factGetVarJN1Call { unsigned int factAddress : 1; unsigned int allFields : 1; + unsigned int lhs : 1; + unsigned int rhs : 1; unsigned short whichPattern; unsigned short whichSlot; unsigned short whichField; @@ -119,6 +126,8 @@ struct factGetVarJN1Call /**********************************************************/ struct factGetVarJN2Call { + unsigned int lhs : 1; + unsigned int rhs : 1; unsigned short whichPattern; unsigned short whichSlot; }; @@ -130,6 +139,8 @@ struct factGetVarJN3Call { unsigned int fromBeginning : 1; unsigned int fromEnd : 1; + unsigned int lhs : 1; + unsigned int rhs : 1; unsigned short beginOffset; unsigned short endOffset; unsigned short whichPattern; @@ -143,8 +154,8 @@ struct factCompVarsPN1Call { unsigned int pass : 1; unsigned int fail : 1; - unsigned int field1 : 7; - unsigned int field2 : 7; + unsigned short field1; + unsigned short field2; }; /**********************************************************/ @@ -154,9 +165,14 @@ struct factCompVarsJN1Call { unsigned int pass : 1; unsigned int fail : 1; - unsigned int slot1 : 7; - unsigned int pattern2 : 8; - unsigned int slot2 : 7; + unsigned int p1lhs: 1; + unsigned int p1rhs: 1; + unsigned int p2lhs: 1; + unsigned int p2rhs: 1; + unsigned short pattern1; + unsigned short pattern2; + unsigned short slot1; + unsigned short slot2; }; /**********************************************************/ @@ -166,13 +182,18 @@ struct factCompVarsJN2Call { unsigned int pass : 1; unsigned int fail : 1; - unsigned int slot1 : 7; + unsigned int p1lhs: 1; + unsigned int p1rhs: 1; + unsigned int p2lhs: 1; + unsigned int p2rhs: 1; unsigned int fromBeginning1 : 1; - unsigned int offset1 : 7; - unsigned int pattern2 : 8; - unsigned int slot2 : 7; unsigned int fromBeginning2 : 1; - unsigned int offset2 : 7; + unsigned short offset1; + unsigned short offset2; + unsigned short pattern1; + unsigned short pattern2; + unsigned short slot1; + unsigned short slot2; }; /**********************************************************/ @@ -197,13 +218,13 @@ struct factCheckLengthPNCall LOCALE struct expr *FactPNVariableComparison(void *,struct lhsParseNode *, struct lhsParseNode *); LOCALE struct expr *FactJNVariableComparison(void *,struct lhsParseNode *, - struct lhsParseNode *); - LOCALE void FactReplaceGetvar(void *,struct expr *,struct lhsParseNode *); + struct lhsParseNode *,int); + LOCALE void FactReplaceGetvar(void *,struct expr *,struct lhsParseNode *,int); LOCALE void FactReplaceGetfield(void *,struct expr *,struct lhsParseNode *); LOCALE struct expr *FactGenPNConstant(void *,struct lhsParseNode *); LOCALE struct expr *FactGenGetfield(void *,struct lhsParseNode *); - LOCALE struct expr *FactGenGetvar(void *,struct lhsParseNode *); + LOCALE struct expr *FactGenGetvar(void *,struct lhsParseNode *,int); LOCALE struct expr *FactGenCheckLength(void *,struct lhsParseNode *); LOCALE struct expr *FactGenCheckZeroLength(void *,unsigned); -#endif +#endif /* _H_factgen */ diff --git a/src/facthsh.c b/src/facthsh.c index 8141cd2..a46a2aa 100644 --- a/src/facthsh.c +++ b/src/facthsh.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT HASHING MODULE */ /*******************************************************/ @@ -22,6 +22,14 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Fact hash table is resizable. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added FactWillBeAsserted. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _FACTHSH_SOURCE_ @@ -37,6 +45,7 @@ #include "constant.h" #include "memalloc.h" #include "router.h" +#include "sysdep.h" #include "envrnmnt.h" #if DEFRULE_CONSTRUCT @@ -49,43 +58,43 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct fact *FactExists(void *,struct fact *,int); + static struct fact *FactExists(void *,struct fact *,unsigned long); + static struct factHashEntry **CreateFactHashTable(void *,unsigned long); + static void ResizeFactHashTable(void *); + static void ResetFactHashTable(void *); /************************************************/ /* HashFact: Returns the hash value for a fact. */ /************************************************/ -int HashFact( +unsigned long HashFact( struct fact *theFact) { - int count = 0; - int hashValue; + unsigned long count = 0; /*============================================*/ /* Get a hash value for the deftemplate name. */ /*============================================*/ - count += (int) HashSymbol(ValueToString(theFact->whichDeftemplate->header.name), - SIZE_FACT_HASH); + count += (unsigned long) theFact->whichDeftemplate->header.name->bucket * 73981; /*=================================================*/ /* Add in the hash value for the rest of the fact. */ /*=================================================*/ - count += (int) HashMultifield(&theFact->theProposition,SIZE_FACT_HASH); + count += HashMultifield(&theFact->theProposition,0); /*================================*/ /* Make sure the hash value falls */ /* in the appropriate range. */ /*================================*/ - hashValue = (int) (count % SIZE_FACT_HASH); - if (hashValue < 0) hashValue = - hashValue; + theFact->hashValue = count; /*========================*/ /* Return the hash value. */ /*========================*/ - return(hashValue); + return(count); } /**********************************************/ @@ -95,14 +104,19 @@ int HashFact( static struct fact *FactExists( void *theEnv, struct fact *theFact, - int hashValue) + unsigned long hashValue) { struct factHashEntry *theFactHash; + hashValue = (hashValue % FactData(theEnv)->FactHashTableSize); + for (theFactHash = FactData(theEnv)->FactHashTable[hashValue]; theFactHash != NULL; theFactHash = theFactHash->next) { + if (theFact->hashValue != theFactHash->theFact->hashValue) + { continue; } + if ((theFact->whichDeftemplate == theFactHash->theFact->whichDeftemplate) ? MultifieldsEqual(&theFact->theProposition, &theFactHash->theFact->theProposition) : FALSE) @@ -118,13 +132,18 @@ static struct fact *FactExists( globle void AddHashedFact( void *theEnv, struct fact *theFact, - int hashValue) + unsigned long hashValue) { struct factHashEntry *newhash, *temp; + if (FactData(theEnv)->NumberOfFacts > FactData(theEnv)->FactHashTableSize) + { ResizeFactHashTable(theEnv); } + newhash = get_struct(theEnv,factHashEntry); newhash->theFact = theFact; + hashValue = (hashValue % FactData(theEnv)->FactHashTableSize); + temp = FactData(theEnv)->FactHashTable[hashValue]; FactData(theEnv)->FactHashTable[hashValue] = newhash; newhash->next = temp; @@ -138,10 +157,11 @@ globle intBool RemoveHashedFact( void *theEnv, struct fact *theFact) { - int hashValue; + unsigned long hashValue; struct factHashEntry *hptr, *prev; hashValue = HashFact(theFact); + hashValue = (hashValue % FactData(theEnv)->FactHashTableSize); for (hptr = FactData(theEnv)->FactHashTable[hashValue], prev = NULL; hptr != NULL; @@ -153,12 +173,16 @@ globle intBool RemoveHashedFact( { FactData(theEnv)->FactHashTable[hashValue] = hptr->next; rtn_struct(theEnv,factHashEntry,hptr); + if (FactData(theEnv)->NumberOfFacts == 1) + { ResetFactHashTable(theEnv); } return(1); } else { prev->next = hptr->next; rtn_struct(theEnv,factHashEntry,hptr); + if (FactData(theEnv)->NumberOfFacts == 1) + { ResetFactHashTable(theEnv); } return(1); } } @@ -168,18 +192,41 @@ globle intBool RemoveHashedFact( return(0); } +/****************************************************/ +/* FactWillBeAsserted: Determines if a fact will be */ +/* asserted based on the duplication settings. */ +/****************************************************/ +globle intBool FactWillBeAsserted( + void *theEnv, + void *theFact) + { + struct fact *tempPtr; + unsigned long hashValue; + + if (FactData(theEnv)->FactDuplication) return(TRUE); + + hashValue = HashFact((struct fact *) theFact); + + tempPtr = FactExists(theEnv,(struct fact *) theFact,hashValue); + if (tempPtr == NULL) return(TRUE); + + return(FALSE); + } + /*****************************************************/ /* HandleFactDuplication: Determines if a fact to be */ /* added to the fact-list is a duplicate entry and */ /* takes appropriate action based on the current */ /* setting of the fact-duplication flag. */ /*****************************************************/ -globle int HandleFactDuplication( +globle unsigned long HandleFactDuplication( void *theEnv, - void *theFact) + void *theFact, + intBool *duplicate) { struct fact *tempPtr; - int hashValue; + unsigned long hashValue; + *duplicate = FALSE; hashValue = HashFact((struct fact *) theFact); @@ -192,7 +239,8 @@ globle int HandleFactDuplication( #if DEFRULE_CONSTRUCT AddLogicalDependencies(theEnv,(struct patternEntity *) tempPtr,TRUE); #endif - return(-1); + *duplicate = TRUE; + return(0); } /*******************************************/ @@ -201,8 +249,8 @@ globle int HandleFactDuplication( /*******************************************/ globle intBool EnvGetFactDuplication( void *theEnv) - { - return(FactData(theEnv)->FactDuplication); + { + return(FactData(theEnv)->FactDuplication); } /*******************************************/ @@ -227,14 +275,102 @@ globle intBool EnvSetFactDuplication( globle void InitializeFactHashTable( void *theEnv) { - int i; + FactData(theEnv)->FactHashTable = CreateFactHashTable(theEnv,SIZE_FACT_HASH); + FactData(theEnv)->FactHashTableSize = SIZE_FACT_HASH; + } + +/*******************************************************************/ +/* CreateFactHashTable: Creates and initializes a fact hash table. */ +/*******************************************************************/ +static struct factHashEntry **CreateFactHashTable( + void *theEnv, + unsigned long tableSize) + { + unsigned long i; + struct factHashEntry **theTable; - FactData(theEnv)->FactHashTable = (struct factHashEntry **) - gm3(theEnv,sizeof (struct factHashEntry *) * SIZE_FACT_HASH); + theTable = (struct factHashEntry **) + gm3(theEnv,sizeof (struct factHashEntry *) * tableSize); - if (FactData(theEnv)->FactHashTable == NULL) EnvExitRouter(theEnv,EXIT_FAILURE); + if (theTable == NULL) EnvExitRouter(theEnv,EXIT_FAILURE); - for (i = 0; i < SIZE_FACT_HASH; i++) FactData(theEnv)->FactHashTable[i] = NULL; + for (i = 0; i < tableSize; i++) theTable[i] = NULL; + + return(theTable); + } + +/*******************************************************************/ +/* ResizeFactHashTable: */ +/*******************************************************************/ +static void ResizeFactHashTable( + void *theEnv) + { + unsigned long i, newSize, newLocation; + struct factHashEntry **theTable, **newTable; + struct factHashEntry *theEntry, *nextEntry; + + theTable = FactData(theEnv)->FactHashTable; + + newSize = (FactData(theEnv)->FactHashTableSize * 2) + 1; + newTable = CreateFactHashTable(theEnv,newSize); + + /*========================================*/ + /* Copy the old entries to the new table. */ + /*========================================*/ + + for (i = 0; i < FactData(theEnv)->FactHashTableSize; i++) + { + theEntry = theTable[i]; + while (theEntry != NULL) + { + nextEntry = theEntry->next; + + newLocation = theEntry->theFact->hashValue % newSize; + theEntry->next = newTable[newLocation]; + newTable[newLocation] = theEntry; + + theEntry = nextEntry; + } + } + + /*=====================================================*/ + /* Replace the old hash table with the new hash table. */ + /*=====================================================*/ + + rm3(theEnv,theTable,sizeof(struct factHashEntry *) * FactData(theEnv)->FactHashTableSize); + FactData(theEnv)->FactHashTableSize = newSize; + FactData(theEnv)->FactHashTable = newTable; + } + +/*******************************************************************/ +/* ResetFactHashTable: */ +/*******************************************************************/ +static void ResetFactHashTable( + void *theEnv) + { + struct factHashEntry **newTable; + + /*=============================================*/ + /* Don't reset the table unless the hash table */ + /* has been expanded from its original size. */ + /*=============================================*/ + + if (FactData(theEnv)->FactHashTableSize == SIZE_FACT_HASH) + { return; } + + /*=======================*/ + /* Create the new table. */ + /*=======================*/ + + newTable = CreateFactHashTable(theEnv,SIZE_FACT_HASH); + + /*=====================================================*/ + /* Replace the old hash table with the new hash table. */ + /*=====================================================*/ + + rm3(theEnv,FactData(theEnv)->FactHashTable,sizeof(struct factHashEntry *) * FactData(theEnv)->FactHashTableSize); + FactData(theEnv)->FactHashTableSize = SIZE_FACT_HASH; + FactData(theEnv)->FactHashTable = newTable; } #if DEVELOPER @@ -250,7 +386,7 @@ globle void ShowFactHashTable( struct factHashEntry *theEntry; char buffer[20]; - for (i = 0; i < SIZE_FACT_HASH; i++) + for (i = 0; i < FactData(theEnv)->FactHashTableSize; i++) { for (theEntry = FactData(theEnv)->FactHashTable[i], count = 0; theEntry != NULL; @@ -259,7 +395,7 @@ globle void ShowFactHashTable( if (count != 0) { - sprintf(buffer,"%4d: %4d\n",i,count); + gensprintf(buffer,"%4d: %4d\n",i,count); EnvPrintRouter(theEnv,WDISPLAY,buffer); } } @@ -267,5 +403,24 @@ globle void ShowFactHashTable( #endif /* DEVELOPER */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool GetFactDuplication() + { + return EnvGetFactDuplication(GetCurrentEnvironment()); + } + +globle intBool SetFactDuplication( + int value) + { + return EnvSetFactDuplication(GetCurrentEnvironment(),value); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/facthsh.h b/src/facthsh.h index aa659c2..3b9a752 100644 --- a/src/facthsh.h +++ b/src/facthsh.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT HASHING MODULE */ /*******************************************************/ @@ -16,7 +16,17 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Fact hash table is resizable. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added FactWillBeAsserted. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -36,7 +46,7 @@ struct factHashEntry struct factHashEntry *next; }; -#define SIZE_FACT_HASH 7717 +#define SIZE_FACT_HASH 16231 #ifdef LOCALE #undef LOCALE @@ -47,23 +57,23 @@ struct factHashEntry #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetFactDuplication(theEnv) EnvGetFactDuplication(theEnv) -#define SetFactDuplication(theEnv,a) EnvSetFactDuplication(theEnv,a) -#else -#define GetFactDuplication() EnvGetFactDuplication(GetCurrentEnvironment()) -#define SetFactDuplication(a) EnvSetFactDuplication(GetCurrentEnvironment(),a) -#endif - - LOCALE void AddHashedFact(void *,struct fact *,int); + LOCALE void AddHashedFact(void *,struct fact *,unsigned long); LOCALE intBool RemoveHashedFact(void *,struct fact *); - LOCALE int HandleFactDuplication(void *,void *); + LOCALE unsigned long HandleFactDuplication(void *,void *,intBool *); LOCALE intBool EnvGetFactDuplication(void *); LOCALE intBool EnvSetFactDuplication(void *,int); LOCALE void InitializeFactHashTable(void *); LOCALE void ShowFactHashTable(void *); - LOCALE int HashFact(struct fact *); + LOCALE unsigned long HashFact(struct fact *); + LOCALE intBool FactWillBeAsserted(void *,void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool GetFactDuplication(void); + LOCALE intBool SetFactDuplication(int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_facthsh */ diff --git a/src/factlhs.c b/src/factlhs.c index f16d443..2a35f10 100644 --- a/src/factlhs.c +++ b/src/factlhs.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT LHS PATTERN PARSING MODULE */ /*******************************************************/ @@ -21,6 +21,15 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Initialize the exists member. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _FACTLHS_SOURCE_ @@ -55,7 +64,7 @@ /***********************************************/ globle struct lhsParseNode *SequenceRestrictionParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken) { struct lhsParseNode *topNode; @@ -68,11 +77,13 @@ globle struct lhsParseNode *SequenceRestrictionParse( topNode = GetLHSParseNode(theEnv); topNode->type = SF_WILDCARD; topNode->negated = FALSE; + topNode->exists = FALSE; topNode->index = -1; topNode->slotNumber = 1; topNode->bottom = GetLHSParseNode(theEnv); topNode->bottom->type = SYMBOL; topNode->bottom->negated = FALSE; + topNode->bottom->exists = FALSE; topNode->bottom->value = (void *) theToken->value; /*======================================================*/ @@ -145,7 +156,7 @@ globle struct lhsParseNode *CreateInitialFactPattern( struct lhsParseNode *topNode; struct deftemplate *theDeftemplate; int count; - + /*==================================*/ /* If the initial-fact deftemplate */ /* doesn't exist, then create it. */ @@ -192,13 +203,10 @@ globle struct lhsParseNode *CreateInitialFactPattern( /* all patterns begin with a symbol, it follows that all patterns */ /* can be parsed as a fact pattern. */ /**********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int FactPatternParserFind( SYMBOL_HN *theRelation) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theRelation) #endif return(TRUE); @@ -210,7 +218,7 @@ globle int FactPatternParserFind( /******************************************************/ globle struct lhsParseNode *FactPatternParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken) { struct deftemplate *theDeftemplate; diff --git a/src/factlhs.h b/src/factlhs.h index 3648365..033f83f 100644 --- a/src/factlhs.h +++ b/src/factlhs.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT BUILD HEADER FILE */ /*******************************************************/ @@ -16,6 +16,15 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Initialize the exists member. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_factlhs @@ -40,8 +49,8 @@ #endif LOCALE int FactPatternParserFind(SYMBOL_HN *); - LOCALE struct lhsParseNode *FactPatternParse(void *,char *,struct token *); - LOCALE struct lhsParseNode *SequenceRestrictionParse(void *,char *,struct token *); + LOCALE struct lhsParseNode *FactPatternParse(void *,const char *,struct token *); + LOCALE struct lhsParseNode *SequenceRestrictionParse(void *,const char *,struct token *); LOCALE struct lhsParseNode *CreateInitialFactPattern(void *); -#endif +#endif /* _H_factlhs */ diff --git a/src/factmch.c b/src/factmch.c index 930cdff..0952bc6 100644 --- a/src/factmch.c +++ b/src/factmch.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT MATCH MODULE */ /*******************************************************/ @@ -16,12 +16,24 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed INCREMENTAL_RESET compilation flag. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Fix for DR0880. 2008-01-24 */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ #define _FACTMCH_SOURCE_ @@ -43,6 +55,7 @@ #include "memalloc.h" #include "reteutil.h" #include "router.h" +#include "sysdep.h" #include "tmpltdef.h" #include "factmch.h" @@ -51,7 +64,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static intBool EvaluatePatternExpression(void *,struct factPatternNode *,struct expr *,int); + static intBool EvaluatePatternExpression(void *,struct factPatternNode *,struct expr *); static void TraceErrorToJoin(void *,struct factPatternNode *,int); static void ProcessFactAlphaMatch(void *,struct fact *,struct multifieldMarker *,struct factPatternNode *); static struct factPatternNode *GetNextFactPatternNode(void *,int,struct factPatternNode *); @@ -75,6 +88,8 @@ globle void FactPatternMatch( { int theSlotField; int offsetSlot; + DATA_OBJECT theResult; + struct factPatternNode *tempPtr; /*=========================================================*/ /* If there's nothing left in the pattern network to match */ @@ -163,13 +178,38 @@ globle void FactPatternMatch( { patternPtr = GetNextFactPatternNode(theEnv,TRUE,patternPtr); } else + if (patternPtr->header.selector) + { + if (EvaluatePatternExpression(theEnv,patternPtr,patternPtr->networkTest->nextArg)) + { + EvaluateExpression(theEnv,patternPtr->networkTest,&theResult); + + tempPtr = (struct factPatternNode *) FindHashedPatternNode(theEnv,patternPtr,theResult.type,theResult.value); + } + else + { tempPtr = NULL; } + + if (tempPtr != NULL) + { + if (SkipFactPatternNode(theEnv,tempPtr)) + { patternPtr = GetNextFactPatternNode(theEnv,TRUE,patternPtr); } + else + { + if (tempPtr->header.stopNode) + { ProcessFactAlphaMatch(theEnv,theFact,markers,tempPtr); } + + patternPtr = GetNextFactPatternNode(theEnv,FALSE,tempPtr); + } + } + else + { patternPtr = GetNextFactPatternNode(theEnv,TRUE,patternPtr); } + } + /*=============================================*/ /* If the constraints are satisified, then ... */ /*=============================================*/ - if (EvaluatePatternExpression(theEnv,patternPtr, - patternPtr->networkTest, - theSlotField)) + else if (EvaluatePatternExpression(theEnv,patternPtr,patternPtr->networkTest)) { /*=======================================================*/ /* If a leaf pattern node has been successfully reached, */ @@ -246,6 +286,9 @@ static void ProcessMultifieldNode( struct multifieldMarker *newMark, *oldMark; int repeatCount; struct multifield *theSlotValue; + DATA_OBJECT theResult; + struct factPatternNode *tempPtr; + intBool success; /*========================================*/ /* Get a pointer to the slot value of the */ @@ -303,10 +346,29 @@ static void ProcessMultifieldNode( /* Determine if the constraint is satisfied. */ /*===========================================*/ - if ((thePattern->networkTest == NULL) ? + if (thePattern->header.selector) + { + if (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest->nextArg)) + { + EvaluateExpression(theEnv,thePattern->networkTest,&theResult); + + thePattern = (struct factPatternNode *) FindHashedPatternNode(theEnv,thePattern,theResult.type,theResult.value); + if (thePattern != NULL) + { success = TRUE; } + else + { success = FALSE; } + } + else + { success = FALSE; } + } + else if ((thePattern->networkTest == NULL) ? TRUE : - (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest, - (int) thePattern->whichField + offset))) + (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest))) + { success = TRUE; } + else + { success = FALSE; } + + if (success) { /*=======================================================*/ /* If a leaf pattern node has been successfully reached, */ @@ -349,10 +411,24 @@ static void ProcessMultifieldNode( { newMark->endPosition = newMark->startPosition + (repeatCount - 1); - if ((thePattern->networkTest == NULL) ? - TRUE : - (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest, - (int) thePattern->whichField + offset))) + if (thePattern->header.selector) + { + if (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest->nextArg)) + { + EvaluateExpression(theEnv,thePattern->networkTest,&theResult); + + tempPtr = (struct factPatternNode *) FindHashedPatternNode(theEnv,thePattern,theResult.type,theResult.value); + if (tempPtr != NULL) + { + FactPatternMatch(theEnv,FactData(theEnv)->CurrentPatternFact, + tempPtr->nextLevel,offset + repeatCount - 1, + FactData(theEnv)->CurrentPatternMarks,newMark); + } + } + } + else if ((thePattern->networkTest == NULL) ? + TRUE : + (EvaluatePatternExpression(theEnv,thePattern,thePattern->networkTest))) { FactPatternMatch(theEnv,FactData(theEnv)->CurrentPatternFact, thePattern->nextLevel,offset + repeatCount - 1, @@ -395,7 +471,9 @@ static struct factPatternNode *GetNextFactPatternNode( /* network until a side branch can be taken. */ /*================================================*/ - while (thePattern->rightNode == NULL) + while ((thePattern->rightNode == NULL) || + ((thePattern->lastLevel != NULL) && + (thePattern->lastLevel->header.selector))) { /*========================================*/ /* Back up to check the next side branch. */ @@ -410,6 +488,15 @@ static struct factPatternNode *GetNextFactPatternNode( if (thePattern == NULL) return(NULL); + /*======================================*/ + /* Skip selector constants and pop back */ + /* back to the selector node. */ + /*======================================*/ + + if ((thePattern->lastLevel != NULL) && + (thePattern->lastLevel->header.selector)) + { thePattern = thePattern->lastLevel; } + /*===================================================*/ /* If we branched up to a multifield node, then stop */ /* since these nodes are handled recursively. The */ @@ -443,12 +530,20 @@ static void ProcessFactAlphaMatch( struct partialMatch *theMatch; struct patternMatch *listOfMatches; struct joinNode *listOfJoins; + unsigned long hashValue; + + /*============================================*/ + /* Create the hash value for the alpha match. */ + /*============================================*/ + + hashValue = ComputeRightHashValue(theEnv,&thePattern->header); /*===========================================*/ /* Create the partial match for the pattern. */ /*===========================================*/ - theMatch = CreateAlphaMatch(theEnv,theFact,theMarks,(struct patternNodeHeader *) &thePattern->header); + theMatch = CreateAlphaMatch(theEnv,theFact,theMarks,(struct patternNodeHeader *) &thePattern->header,hashValue); + theMatch->owner = &thePattern->header; /*=======================================================*/ /* Add the pattern to the list of matches for this fact. */ @@ -467,7 +562,7 @@ static void ProcessFactAlphaMatch( for (listOfJoins = thePattern->header.entryJoin; listOfJoins != NULL; listOfJoins = listOfJoins->rightMatchNode) - { NetworkAssert(theEnv,theMatch,listOfJoins,RHS); } + { NetworkAssert(theEnv,theMatch,listOfJoins); } } /*****************************************************************/ @@ -478,8 +573,7 @@ static void ProcessFactAlphaMatch( static int EvaluatePatternExpression( void *theEnv, struct factPatternNode *patternPtr, - struct expr *theTest, - int thePosition) + struct expr *theTest) { DATA_OBJECT theResult; struct expr *oldArgument; @@ -535,9 +629,6 @@ static int EvaluatePatternExpression( rv = FactSlotLength(theEnv,theTest->value,&theResult); EvaluationData(theEnv)->CurrentExpression = oldArgument; return(rv); - - default: - break; } /*==============================================*/ @@ -552,7 +643,7 @@ static int EvaluatePatternExpression( theTest != NULL; theTest = theTest->nextArg) { - if (EvaluatePatternExpression(theEnv,patternPtr,theTest,thePosition) == TRUE) + if (EvaluatePatternExpression(theEnv,patternPtr,theTest) == TRUE) { if (EvaluationData(theEnv)->EvaluationError) return(FALSE); return(TRUE); @@ -575,7 +666,7 @@ static int EvaluatePatternExpression( theTest != NULL; theTest = theTest->nextArg) { - if (EvaluatePatternExpression(theEnv,patternPtr,theTest,thePosition) == FALSE) + if (EvaluatePatternExpression(theEnv,patternPtr,theTest) == FALSE) { return(FALSE); } if (EvaluationData(theEnv)->EvaluationError) return(FALSE); } @@ -633,12 +724,12 @@ static void PatternNetErrorMessage( /*==============================================*/ if (FactData(theEnv)->CurrentPatternFact->whichDeftemplate->implied) - { sprintf(buffer," Problem resides in field #%d\n",patternPtr->whichField); } + { gensprintf(buffer," Problem resides in field #%d\n",patternPtr->whichField); } else { theSlots = FactData(theEnv)->CurrentPatternFact->whichDeftemplate->slotList; for (i = 0; i < (int) patternPtr->whichSlot; i++) theSlots = theSlots->next; - sprintf(buffer," Problem resides in slot %s\n",ValueToString(theSlots->slotName)); + gensprintf(buffer," Problem resides in slot %s\n",ValueToString(theSlots->slotName)); } EnvPrintRouter(theEnv,WERROR,buffer); @@ -667,7 +758,6 @@ static void TraceErrorToJoin( int traceRight) { struct joinNode *joinPtr; - char buffer[60]; while (patternPtr != NULL) { @@ -676,11 +766,7 @@ static void TraceErrorToJoin( for (joinPtr = patternPtr->header.entryJoin; joinPtr != NULL; joinPtr = joinPtr->rightMatchNode) - { - sprintf(buffer," Of pattern #%d in rule(s):\n",GetPatternNumberFromJoin(joinPtr)); - EnvPrintRouter(theEnv,WERROR,buffer); - TraceErrorToRule(theEnv,joinPtr," "); - } + { TraceErrorToRule(theEnv,joinPtr," "); } } else { TraceErrorToJoin(theEnv,patternPtr->nextLevel,TRUE); } @@ -701,10 +787,6 @@ static int SkipFactPatternNode( void *theEnv, struct factPatternNode *thePattern) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,thePattern) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) if (EngineData(theEnv)->IncrementalResetInProgress && (thePattern->header.initialize == FALSE)) @@ -723,16 +805,14 @@ static int SkipFactPatternNode( /* that the nodes were traversed ("initialized") by the */ /* incremental reset. */ /***************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void MarkFactPatternForIncrementalReset( void *theEnv, struct patternNodeHeader *thePattern, int value) { struct factPatternNode *patternPtr = (struct factPatternNode *) thePattern; -#if MAC_MCW || IBM_MCW || MAC_XCD + struct joinNode *theJoin; +#if MAC_XCD #pragma unused(theEnv) #endif @@ -743,12 +823,23 @@ globle void MarkFactPatternForIncrementalReset( Bogus(patternPtr == NULL); - /*============================================*/ - /* If the pattern was previously initialized, */ - /* then don't bother with it. */ - /*============================================*/ + /*===============================================================*/ + /* If the pattern was previously initialized, then don't bother */ + /* with it unless the pattern was subsumed by another pattern */ + /* and associated with a join that hasn't been initialized. */ + /* DR0880 2008-01-24 */ + /*===============================================================*/ - if (patternPtr->header.initialize == FALSE) return; + if (patternPtr->header.initialize == FALSE) + { + for (theJoin = patternPtr->header.entryJoin; + theJoin != NULL; + theJoin = theJoin->rightMatchNode) + { + if (theJoin->initialize == FALSE) + { return; } + } + } /*======================================================*/ /* Set the initialization field of this pattern network */ @@ -778,9 +869,11 @@ globle void FactsIncrementalReset( factPtr != NULL; factPtr = (struct fact *) EnvGetNextFact(theEnv,factPtr)) { + EngineData(theEnv)->JoinOperationInProgress = TRUE; FactPatternMatch(theEnv,factPtr, factPtr->whichDeftemplate->patternNetwork, 0,NULL,NULL); + EngineData(theEnv)->JoinOperationInProgress = FALSE; } } diff --git a/src/factmch.h b/src/factmch.h index 71e2897..b8af038 100644 --- a/src/factmch.h +++ b/src/factmch.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT MATCH HEADER FILE */ /*******************************************************/ @@ -16,6 +16,23 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Fix for DR0880. 2008-01-24 */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ #ifndef _H_factmch @@ -49,7 +66,7 @@ LOCALE void MarkFactPatternForIncrementalReset(void *,struct patternNodeHeader *,int); LOCALE void FactsIncrementalReset(void *); -#endif +#endif /* _H_factmch */ diff --git a/src/factmngr.c b/src/factmngr.c index 16d6d9c..52e5213 100644 --- a/src/factmngr.c +++ b/src/factmngr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* FACT MANAGER MODULE */ /*******************************************************/ @@ -16,9 +16,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ @@ -32,6 +33,34 @@ /* */ /* Support for ppfact command. */ /* */ +/* 6.30: Callback function support for assertion, */ +/* retraction, and modification of facts. */ +/* */ +/* Updates to fact pattern entity record. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Removed unused global variables. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* JoinOperationInProgress mechanism. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ @@ -72,6 +101,7 @@ #include "default.h" #include "commline.h" #include "envrnmnt.h" +#include "sysdep.h" #include "engine.h" #include "lgcldpnd.h" @@ -106,23 +136,24 @@ globle void InitializeFacts( EnvRetract, NULL, EnvGetNextFact, - EnvIncrementFactCount, - EnvDecrementFactCount,NULL,NULL,NULL,NULL + EnvDecrementFactCount, + EnvIncrementFactCount,NULL,NULL,NULL,NULL,NULL }, DecrementFactBasisCount, IncrementFactBasisCount, MatchFactFunction, - NULL + NULL, + FactIsDeleted }; - - struct fact dummyFact = { { NULL }, NULL, NULL, -1L, 0, 1, - NULL, NULL, NULL, NULL, { 1, 0, 0 } }; - + + struct fact dummyFact = { { NULL, NULL, 0, 0L }, NULL, NULL, -1L, 0, 1, + NULL, NULL, NULL, NULL, { 1, 0UL, NULL, { { 0, NULL } } } }; + AllocateEnvironmentData(theEnv,FACTS_DATA,sizeof(struct factsData),DeallocateFactData); - memcpy(&FactData(theEnv)->FactInfo,&factInfo,sizeof(struct patternEntityRecord)); - dummyFact.factHeader.theInfo = &FactData(theEnv)->FactInfo; - memcpy(&FactData(theEnv)->DummyFact,&dummyFact,sizeof(struct fact)); + memcpy(&FactData(theEnv)->FactInfo,&factInfo,sizeof(struct patternEntityRecord)); + dummyFact.factHeader.theInfo = &FactData(theEnv)->FactInfo; + memcpy(&FactData(theEnv)->DummyFact,&dummyFact,sizeof(struct fact)); FactData(theEnv)->LastModuleIndex = -1; /*=========================================*/ @@ -168,11 +199,11 @@ globle void InitializeFacts( FactCommandDefinitions(theEnv); FactFunctionDefinitions(theEnv); - + /*==============================*/ /* Initialize fact set queries. */ /*==============================*/ - + #if FACT_SET_QUERIES SetupFactQuery(theEnv); #endif @@ -195,7 +226,7 @@ globle void InitializeFacts( FactPatternsCompilerSetup(theEnv); #endif } - + /***********************************/ /* DeallocateFactData: Deallocates */ /* environment data for facts. */ @@ -205,13 +236,13 @@ static void DeallocateFactData( { struct factHashEntry *tmpFHEPtr, *nextFHEPtr; struct fact *tmpFactPtr, *nextFactPtr; - int i; + unsigned long i; struct patternMatch *theMatch, *tmpMatch; - - for (i = 0; i < SIZE_FACT_HASH; i++) + + for (i = 0; i < FactData(theEnv)->FactHashTableSize; i++) { tmpFHEPtr = FactData(theEnv)->FactHashTable[i]; - + while (tmpFHEPtr != NULL) { nextFHEPtr = tmpFHEPtr->next; @@ -219,16 +250,16 @@ static void DeallocateFactData( tmpFHEPtr = nextFHEPtr; } } - + rm3(theEnv,FactData(theEnv)->FactHashTable, - sizeof(struct factHashEntry *) * SIZE_FACT_HASH); - + sizeof(struct factHashEntry *) * FactData(theEnv)->FactHashTableSize); + tmpFactPtr = FactData(theEnv)->FactList; while (tmpFactPtr != NULL) { nextFactPtr = tmpFactPtr->nextFact; - theMatch = (struct patternMatch *) tmpFactPtr->list; + theMatch = (struct patternMatch *) tmpFactPtr->list; while (theMatch != NULL) { tmpMatch = theMatch->next; @@ -236,18 +267,24 @@ static void DeallocateFactData( theMatch = tmpMatch; } + ReturnEntityDependencies(theEnv,(struct patternEntity *) tmpFactPtr); + ReturnFact(theEnv,tmpFactPtr); - tmpFactPtr = nextFactPtr; + tmpFactPtr = nextFactPtr; } - + tmpFactPtr = FactData(theEnv)->GarbageFacts; while (tmpFactPtr != NULL) { nextFactPtr = tmpFactPtr->nextFact; ReturnFact(theEnv,tmpFactPtr); - tmpFactPtr = nextFactPtr; + tmpFactPtr = nextFactPtr; } + + DeallocateCallListWithArg(theEnv,FactData(theEnv)->ListOfAssertFunctions); + DeallocateCallListWithArg(theEnv,FactData(theEnv)->ListOfRetractFunctions); + DeallocateCallListWithArg(theEnv,FactData(theEnv)->ListOfModifyFunctions); } /**********************************************/ @@ -256,12 +293,12 @@ static void DeallocateFactData( /**********************************************/ globle void PrintFactWithIdentifier( void *theEnv, - char *logicalName, + const char *logicalName, struct fact *factPtr) { char printSpace[20]; - sprintf(printSpace,"f-%-5ld ",factPtr->factIndex); + gensprintf(printSpace,"f-%-5lld ",factPtr->factIndex); EnvPrintRouter(theEnv,logicalName,printSpace); PrintFact(theEnv,logicalName,factPtr,FALSE,FALSE); } @@ -271,12 +308,12 @@ globle void PrintFactWithIdentifier( /****************************************************/ globle void PrintFactIdentifier( void *theEnv, - char *logicalName, + const char *logicalName, void *factPtr) { char printSpace[20]; - sprintf(printSpace,"f-%ld",((struct fact *) factPtr)->factIndex); + gensprintf(printSpace,"f-%lld",((struct fact *) factPtr)->factIndex); EnvPrintRouter(theEnv,logicalName,printSpace); } @@ -286,7 +323,7 @@ globle void PrintFactIdentifier( /********************************************/ globle void PrintFactIdentifierInLongForm( void *theEnv, - char *logicalName, + const char *logicalName, void *factPtr) { if (PrintUtilityData(theEnv)->AddressesToStrings) EnvPrintRouter(theEnv,logicalName,"\""); @@ -346,6 +383,20 @@ globle void IncrementFactBasisCount( } } +/******************/ +/* FactIsDeleted: */ +/******************/ +globle intBool FactIsDeleted( + void *theEnv, + void *theFact) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + + return(((struct fact *) theFact)->garbage); + } + /**************************************************/ /* PrintFact: Displays the printed representation */ /* of a fact containing the relation name and */ @@ -353,7 +404,7 @@ globle void IncrementFactBasisCount( /**************************************************/ globle void PrintFact( void *theEnv, - char *logicalName, + const char *logicalName, struct fact *factPtr, int seperateLines, int ignoreDefaults) @@ -413,6 +464,7 @@ globle intBool EnvRetract( { struct fact *theFact = (struct fact *) vTheFact; struct deftemplate *theTemplate = theFact->whichDeftemplate; + struct callFunctionItemWithArg *theRetractFunction; /*===========================================*/ /* A fact can not be retracted while another */ @@ -443,6 +495,22 @@ globle intBool EnvRetract( if (theFact->garbage) return(FALSE); + /*==========================================*/ + /* Execute the list of functions that are */ + /* to be called before each fact assertion. */ + /*==========================================*/ + + for (theRetractFunction = FactData(theEnv)->ListOfRetractFunctions; + theRetractFunction != NULL; + theRetractFunction = theRetractFunction->next) + { + SetEnvironmentCallbackContext(theEnv,theRetractFunction->context); + if (theRetractFunction->environmentAware) + { (*theRetractFunction->func)(theEnv,theFact); } + else + { ((void (*)(void *))(*theRetractFunction->func))(theFact); } + } + /*============================*/ /* Print retraction output if */ /* facts are being watched. */ @@ -481,7 +549,7 @@ globle intBool EnvRetract( /*=========================================*/ /* Remove the fact from its template list. */ /*=========================================*/ - + if (theFact == theTemplate->lastFact) { theTemplate->lastFact = theFact->previousTemplateFact; } @@ -497,7 +565,7 @@ globle intBool EnvRetract( if (theFact->nextTemplateFact != NULL) { theFact->nextTemplateFact->previousTemplateFact = theFact->previousTemplateFact; } } - + /*=====================================*/ /* Remove the fact from the fact list. */ /*=====================================*/ @@ -518,15 +586,6 @@ globle intBool EnvRetract( { theFact->nextFact->previousFact = theFact->previousFact; } } - /*==================================*/ - /* Update busy counts and ephemeral */ - /* garbage information. */ - /*==================================*/ - - FactDeinstall(theEnv,theFact); - UtilityData(theEnv)->EphemeralItemCount++; - UtilityData(theEnv)->EphemeralItemSize += sizeof(struct fact) + (sizeof(struct field) * theFact->theProposition.multifieldLength); - /*========================================*/ /* Add the fact to the fact garbage list. */ /*========================================*/ @@ -534,6 +593,7 @@ globle intBool EnvRetract( theFact->nextFact = FactData(theEnv)->GarbageFacts; FactData(theEnv)->GarbageFacts = theFact; theFact->garbage = TRUE; + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; /*===================================================*/ /* Reset the evaluation error flag since expressions */ @@ -572,9 +632,16 @@ globle intBool EnvRetract( /* executed from an embedded application. */ /*===========================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { CleanCurrentGarbageFrame(theEnv,NULL); } + + /*==================================*/ + /* Update busy counts and ephemeral */ + /* garbage information. */ + /*==================================*/ + + FactDeinstall(theEnv,theFact); /*==================================*/ /* Return TRUE to indicate the fact */ @@ -601,11 +668,8 @@ static void RemoveGarbageFacts( while (factPtr != NULL) { nextPtr = factPtr->nextFact; - if ((factPtr->factHeader.busyCount == 0) && - (((int) factPtr->depth) > EvaluationData(theEnv)->CurrentEvaluationDepth)) + if (factPtr->factHeader.busyCount == 0) { - UtilityData(theEnv)->EphemeralItemCount--; - UtilityData(theEnv)->EphemeralItemSize -= sizeof(struct fact) + (sizeof(struct field) * factPtr->theProposition.multifieldLength); ReturnFact(theEnv,factPtr); if (lastPtr == NULL) FactData(theEnv)->GarbageFacts = nextPtr; else lastPtr->nextFact = nextPtr; @@ -624,10 +688,12 @@ globle void *EnvAssert( void *theEnv, void *vTheFact) { - int hashValue; + unsigned long hashValue; unsigned long length, i; struct field *theField; struct fact *theFact = (struct fact *) vTheFact; + intBool duplicate; + struct callFunctionItemWithArg *theAssertFunction; /*==========================================*/ /* A fact can not be asserted while another */ @@ -663,8 +729,8 @@ globle void *EnvAssert( /* then search the fact list for a duplicate fact. */ /*========================================================*/ - hashValue = HandleFactDuplication(theEnv,theFact); - if (hashValue < 0) return(NULL); + hashValue = HandleFactDuplication(theEnv,theFact,&duplicate); + if (duplicate) return(NULL); /*==========================================================*/ /* If necessary, add logical dependency links between the */ @@ -699,17 +765,17 @@ globle void *EnvAssert( /*====================================*/ /* Add the fact to its template list. */ /*====================================*/ - + theFact->previousTemplateFact = theFact->whichDeftemplate->lastFact; theFact->nextTemplateFact = NULL; - + if (theFact->whichDeftemplate->lastFact == NULL) { theFact->whichDeftemplate->factList = theFact; } else { theFact->whichDeftemplate->lastFact->nextTemplateFact = theFact; } - + theFact->whichDeftemplate->lastFact = theFact; - + /*==================================*/ /* Set the fact index and time tag. */ /*==================================*/ @@ -723,6 +789,22 @@ globle void *EnvAssert( FactInstall(theEnv,theFact); + /*==========================================*/ + /* Execute the list of functions that are */ + /* to be called before each fact assertion. */ + /*==========================================*/ + + for (theAssertFunction = FactData(theEnv)->ListOfAssertFunctions; + theAssertFunction != NULL; + theAssertFunction = theAssertFunction->next) + { + SetEnvironmentCallbackContext(theEnv,theAssertFunction->context); + if (theAssertFunction->environmentAware) + { (*theAssertFunction->func)(theEnv,theFact); } + else + { ((void (*)(void *))(*theAssertFunction->func))(theFact); } + } + /*==========================*/ /* Print assert output if */ /* facts are being watched. */ @@ -785,9 +867,12 @@ globle void *EnvAssert( /* executed from an embedded application. */ /*==========================================*/ - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } /*===============================*/ /* Return a pointer to the fact. */ @@ -866,7 +951,7 @@ globle struct fact *EnvCreateFact( globle intBool EnvGetFactSlot( void *theEnv, void *vTheFact, - char *slotName, + const char *slotName, DATA_OBJECT *theValue) { struct fact *theFact = (struct fact *) vTheFact; @@ -929,7 +1014,7 @@ globle intBool EnvGetFactSlot( globle intBool EnvPutFactSlot( void *theEnv, void *vTheFact, - char *slotName, + const char *slotName, DATA_OBJECT *theValue) { struct fact *theFact = (struct fact *) vTheFact; @@ -959,7 +1044,7 @@ globle intBool EnvPutFactSlot( theFact->theProposition.theFields[0].type = theValue->type; theFact->theProposition.theFields[0].value = DOToMultifield(theEnv,theValue); - + return(TRUE); } @@ -993,7 +1078,7 @@ globle intBool EnvPutFactSlot( { theFact->theProposition.theFields[whichSlot-1].value = DOToMultifield(theEnv,theValue); } else { theFact->theProposition.theFields[whichSlot-1].value = theValue->value; } - + return(TRUE); } @@ -1044,7 +1129,7 @@ globle intBool EnvAssignFactSlotDefaults( /*======================================================*/ /* Assign the default value for the slot if one exists. */ /*======================================================*/ - + if (DeftemplateSlotDefault(theEnv,theDeftemplate,slotPtr,&theResult,FALSE)) { theFact->theProposition.theFields[i].type = theResult.type; @@ -1059,7 +1144,7 @@ globle intBool EnvAssignFactSlotDefaults( return(TRUE); } - + /********************************************************/ /* DeftemplateSlotDefault: Determines the default value */ /* for the specified slot of a deftemplate. */ @@ -1206,11 +1291,10 @@ globle struct fact *CreateFactBySize( if (size <= 0) newSize = 1; else newSize = size; - theFact = get_var_struct2(theEnv,fact,sizeof(struct field) * (newSize - 1)); + theFact = get_var_struct(theEnv,fact,sizeof(struct field) * (newSize - 1)); - theFact->depth = (unsigned) EvaluationData(theEnv)->CurrentEvaluationDepth; theFact->garbage = FALSE; - theFact->factIndex = 0L; + theFact->factIndex = 0LL; theFact->factHeader.busyCount = 0; theFact->factHeader.theInfo = &FactData(theEnv)->FactInfo; theFact->factHeader.dependents = NULL; @@ -1222,7 +1306,6 @@ globle struct fact *CreateFactBySize( theFact->list = NULL; theFact->theProposition.multifieldLength = size; - theFact->theProposition.depth = (short) EvaluationData(theEnv)->CurrentEvaluationDepth; theFact->theProposition.busyCount = 0; return(theFact); @@ -1236,21 +1319,27 @@ globle void ReturnFact( void *theEnv, struct fact *theFact) { - struct multifield *theSegment; - unsigned newSize, i; + struct multifield *theSegment, *subSegment; + long newSize, i; theSegment = &theFact->theProposition; for (i = 0; i < theSegment->multifieldLength; i++) { if (theSegment->theFields[i].type == MULTIFIELD) - { ReturnMultifield(theEnv,(struct multifield *) theSegment->theFields[i].value); } + { + subSegment = (struct multifield *) theSegment->theFields[i].value; + if (subSegment->busyCount == 0) + { ReturnMultifield(theEnv,subSegment); } + else + { AddToMultifieldList(theEnv,subSegment); } + } } if (theFact->theProposition.multifieldLength == 0) newSize = 1; else newSize = theFact->theProposition.multifieldLength; - - rtn_var_struct2(theEnv,fact,sizeof(struct field) * (newSize - 1),theFact); + + rtn_var_struct(theEnv,fact,sizeof(struct field) * (newSize - 1),theFact); } /*************************************************************/ @@ -1303,14 +1392,11 @@ globle void FactDeinstall( /* EnvIncrementFactCount: Increments the number */ /* of references to a specified fact. */ /************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvIncrementFactCount( void *theEnv, void *factPtr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1321,14 +1407,11 @@ globle void EnvIncrementFactCount( /* EnvDecrementFactCount: Decrements the number */ /* of references to a specified fact. */ /************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvDecrementFactCount( void *theEnv, void *factPtr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1424,7 +1507,7 @@ globle void *GetNextFactInScope( globle void EnvGetFactPPForm( void *theEnv, char *buffer, - unsigned bufferLength, + size_t bufferLength, void *theFact) { OpenStringDestination(theEnv,"FactPPForm",buffer,bufferLength); @@ -1436,14 +1519,11 @@ globle void EnvGetFactPPForm( /* EnvFactIndex: C access routine */ /* for the fact-index function. */ /**********************************/ -#if IBM_TBC -#pragma argsused -#endif -globle long int EnvFactIndex( +globle long long EnvFactIndex( void *theEnv, void *factPtr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1456,12 +1536,18 @@ globle long int EnvFactIndex( /*************************************/ globle void *EnvAssertString( void *theEnv, - char *theString) + const char *theString) { struct fact *theFact; + int danglingConstructs; + danglingConstructs = ConstructData(theEnv)->DanglingConstructs; if ((theFact = StringToFact(theEnv,theString)) == NULL) return(NULL); + if ((! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL)) + { ConstructData(theEnv)->DanglingConstructs = danglingConstructs; } + return((void *) EnvAssert(theEnv,(void *) theFact)); } @@ -1472,7 +1558,7 @@ globle void *EnvAssertString( globle int EnvGetFactListChanged( void *theEnv) { - return(FactData(theEnv)->ChangeToFactList); + return(FactData(theEnv)->ChangeToFactList); } /***********************************************************/ @@ -1492,8 +1578,8 @@ globle void EnvSetFactListChanged( /****************************************/ globle unsigned long GetNumberOfFacts( void *theEnv) - { - return(FactData(theEnv)->NumberOfFacts); + { + return(FactData(theEnv)->NumberOfFacts); } /***********************************************************/ @@ -1524,6 +1610,13 @@ static void ResetFacts( static int ClearFactsReady( void *theEnv) { + /*======================================*/ + /* Facts can not be deleted when a join */ + /* operation is already in progress. */ + /*======================================*/ + + if (EngineData(theEnv)->JoinOperationInProgress) return(FALSE); + /*====================================*/ /* Initialize the fact index to zero. */ /*====================================*/ @@ -1557,7 +1650,7 @@ static int ClearFactsReady( /***************************************************/ globle struct fact *FindIndexedFact( void *theEnv, - long int factIndexSought) + long long factIndexSought) { struct fact *theFact; @@ -1572,5 +1665,325 @@ globle struct fact *FindIndexedFact( return(NULL); } +/*****************************************/ +/* EnvAddAssertFunction: Adds a function */ +/* to the ListOfAssertFunctions. */ +/*****************************************/ +globle intBool EnvAddAssertFunction( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority) + { + FactData(theEnv)->ListOfAssertFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority, + functionPtr, + FactData(theEnv)->ListOfAssertFunctions,TRUE); + return(1); + } + +/********************************************/ +/* EnvAddAssertFunctionWithContext: Adds a */ +/* function to the ListOfAssertFunctions. */ +/********************************************/ +globle intBool EnvAddAssertFunctionWithContext( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority, + void *context) + { + FactData(theEnv)->ListOfAssertFunctions = + AddFunctionToCallListWithArgWithContext(theEnv,name,priority,functionPtr, + FactData(theEnv)->ListOfAssertFunctions, + TRUE,context); + return(1); + } + +/***********************************************/ +/* EnvRemoveAssertFunction: Removes a function */ +/* from the ListOfAssertFunctions. */ +/***********************************************/ +globle intBool EnvRemoveAssertFunction( + void *theEnv, + const char *name) + { + int found; + + FactData(theEnv)->ListOfAssertFunctions = + RemoveFunctionFromCallListWithArg(theEnv,name,FactData(theEnv)->ListOfAssertFunctions,&found); + + if (found) return(TRUE); + + return(FALSE); + } + +/******************************************/ +/* EnvAddRetractFunction: Adds a function */ +/* to the ListOfRetractFunctions. */ +/******************************************/ +globle intBool EnvAddRetractFunction( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority) + { + FactData(theEnv)->ListOfRetractFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority, + functionPtr, + FactData(theEnv)->ListOfRetractFunctions,TRUE); + return(1); + } + +/*********************************************/ +/* EnvAddRetractFunctionWithContext: Adds a */ +/* function to the ListOfRetractFunctions. */ +/*********************************************/ +globle intBool EnvAddRetractFunctionWithContext( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *), + int priority, + void *context) + { + FactData(theEnv)->ListOfRetractFunctions = + AddFunctionToCallListWithArgWithContext(theEnv,name,priority,functionPtr, + FactData(theEnv)->ListOfRetractFunctions, + TRUE,context); + return(1); + } + +/************************************************/ +/* EnvRemoveRetractFunction: Removes a function */ +/* from the ListOfRetractFunctions. */ +/************************************************/ +globle intBool EnvRemoveRetractFunction( + void *theEnv, + const char *name) + { + int found; + + FactData(theEnv)->ListOfRetractFunctions = + RemoveFunctionFromCallListWithArg(theEnv,name,FactData(theEnv)->ListOfRetractFunctions,&found); + + if (found) return(TRUE); + + return(FALSE); + } + +/*****************************************/ +/* EnvAddModifyFunction: Adds a function */ +/* to the ListOfModifyFunctions. */ +/*****************************************/ +globle intBool EnvAddModifyFunction( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *, void *), + int priority) + { + FactData(theEnv)->ListOfModifyFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority, + (void (*)(void *, void *)) functionPtr, + FactData(theEnv)->ListOfModifyFunctions,TRUE); + return(1); + } + +/********************************************/ +/* EnvAddModifyFunctionWithContext: Adds a */ +/* function to the ListOfModifyFunctions. */ +/********************************************/ +globle intBool EnvAddModifyFunctionWithContext( + void *theEnv, + const char *name, + void (*functionPtr)(void *, void *, void *), + int priority, + void *context) + { + FactData(theEnv)->ListOfModifyFunctions = + AddFunctionToCallListWithArgWithContext(theEnv,name,priority, + (void (*)(void *, void *)) functionPtr, + FactData(theEnv)->ListOfModifyFunctions, + TRUE,context); + return(1); + } + +/***********************************************/ +/* EnvRemoveModifyFunction: Removes a function */ +/* from the ListOfModifyFunctions. */ +/***********************************************/ +globle intBool EnvRemoveModifyFunction( + void *theEnv, + const char *name) + { + int found; + + FactData(theEnv)->ListOfModifyFunctions = + RemoveFunctionFromCallListWithArg(theEnv,name,FactData(theEnv)->ListOfModifyFunctions,&found); + + if (found) return(TRUE); + + return(FALSE); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool AddAssertFunction( + const char *name, + void (*functionPtr)(void *,void *), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + FactData(theEnv)->ListOfAssertFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority,(void (*)(void *, void *)) functionPtr, + FactData(theEnv)->ListOfAssertFunctions,TRUE); + return(1); + } + +globle intBool AddModifyFunction( + const char *name, + void (*functionPtr)(void *,void *,void *), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + FactData(theEnv)->ListOfModifyFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority,(void (*)(void *, void *)) functionPtr, + FactData(theEnv)->ListOfModifyFunctions,TRUE); + return(1); + } + +globle intBool AddRetractFunction( + const char *name, + void (*functionPtr)(void *,void *), + int priority) + { + void *theEnv; + + theEnv = GetCurrentEnvironment(); + + FactData(theEnv)->ListOfRetractFunctions = + AddFunctionToCallListWithArg(theEnv,name,priority,(void (*)(void *, void *)) functionPtr, + FactData(theEnv)->ListOfRetractFunctions,TRUE); + return(1); + } + +globle void *Assert( + void *vTheFact) + { + return EnvAssert(GetCurrentEnvironment(),vTheFact); + } + +globle void *AssertString( + const char *theString) + { + return EnvAssertString(GetCurrentEnvironment(),theString); + } + +globle intBool AssignFactSlotDefaults( + void *vTheFact) + { + return EnvAssignFactSlotDefaults(GetCurrentEnvironment(),vTheFact); + } + +globle struct fact *CreateFact( + void *vTheDeftemplate) + { + return EnvCreateFact(GetCurrentEnvironment(),vTheDeftemplate); + } + +globle void DecrementFactCount( + void *factPtr) + { + EnvDecrementFactCount(GetCurrentEnvironment(),factPtr); + } + +globle long long FactIndex( + void *factPtr) + { + return(EnvFactIndex(GetCurrentEnvironment(),factPtr)); + } + +globle int GetFactListChanged() + { + return EnvGetFactListChanged(GetCurrentEnvironment()); + } + +globle void GetFactPPForm( + char *buffer, + unsigned bufferLength, + void *theFact) + { + EnvGetFactPPForm(GetCurrentEnvironment(),buffer,bufferLength,theFact); + } + +globle intBool GetFactSlot( + void *vTheFact, + const char *slotName, + DATA_OBJECT *theValue) + { + return(EnvGetFactSlot(GetCurrentEnvironment(),vTheFact,slotName,theValue)); + } + +globle void *GetNextFact( + void *factPtr) + { + return EnvGetNextFact(GetCurrentEnvironment(),factPtr); + } + +globle void IncrementFactCount( + void *factPtr) + { + EnvIncrementFactCount(GetCurrentEnvironment(),factPtr); + } + +globle intBool PutFactSlot( + void *vTheFact, + const char *slotName, + DATA_OBJECT *theValue) + { + return EnvPutFactSlot(GetCurrentEnvironment(),vTheFact,slotName,theValue); + } + +globle intBool RemoveAssertFunction( + const char *name) + { + return EnvRemoveAssertFunction(GetCurrentEnvironment(),name); + } + +globle intBool RemoveModifyFunction( + const char *name) + { + return EnvRemoveModifyFunction(GetCurrentEnvironment(),name); + } + +globle intBool RemoveRetractFunction( + const char *name) + { + return EnvRemoveRetractFunction(GetCurrentEnvironment(),name); + } + +globle intBool Retract( + void *vTheFact) + { + return EnvRetract(GetCurrentEnvironment(),vTheFact); + } + +globle void SetFactListChanged( + int value) + { + EnvSetFactListChanged(GetCurrentEnvironment(),value); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT && DEFRULE_CONSTRUCT */ diff --git a/src/factmngr.h b/src/factmngr.h index 12def43..9ce435d 100644 --- a/src/factmngr.h +++ b/src/factmngr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* FACTS MANAGER HEADER FILE */ /*******************************************************/ @@ -15,10 +15,43 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* AssignFactSlotDefaults function does not */ +/* properly handle defaults for multifield slots. */ +/* DR0869 */ +/* */ +/* Support for ppfact command. */ +/* */ +/* 6.30: Callback function support for assertion, */ +/* retraction, and modification of facts. */ +/* */ +/* Updates to fact pattern entity record. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Removed unused global variables. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* JoinOperationInProgress mechanism. */ /* */ /*************************************************************/ @@ -50,8 +83,8 @@ struct fact struct patternEntity factHeader; struct deftemplate *whichDeftemplate; void *list; - long int factIndex; - unsigned int depth : 15; + long long factIndex; + unsigned long hashValue; unsigned int garbage : 1; struct fact *previousFact; struct fact *nextFact; @@ -59,7 +92,7 @@ struct fact struct fact *nextTemplateFact; struct multifield theProposition; }; - + #define FACTS_DATA 3 struct factsData @@ -72,8 +105,11 @@ struct factsData struct fact *GarbageFacts; struct fact *LastFact; struct fact *FactList; - long int NextFactIndex; + long long NextFactIndex; unsigned long NumberOfFacts; + struct callFunctionItemWithArg *ListOfAssertFunctions; + struct callFunctionItemWithArg *ListOfRetractFunctions; + struct callFunctionItemWithArg *ListOfModifyFunctions; struct patternEntityRecord FactInfo; #if (! RUN_TIME) && (! BLOAD_ONLY) struct deftemplate *CurrentDeftemplate; @@ -82,6 +118,7 @@ struct factsData struct CodeGeneratorItem *FactCodeItem; #endif struct factHashEntry **FactHashTable; + unsigned long FactHashTableSize; intBool FactDuplication; #if DEFRULE_CONSTRUCT struct fact *CurrentPatternFact; @@ -89,7 +126,7 @@ struct factsData #endif long LastModuleIndex; }; - + #define FactData(theEnv) ((struct factsData *) GetEnvironmentData(theEnv,FACTS_DATA)) #ifdef LOCALE @@ -101,47 +138,15 @@ struct factsData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Assert(theEnv,a) EnvAssert(theEnv,a) -#define AssertString(theEnv,a) EnvAssertString(theEnv,a) -#define AssignFactSlotDefaults(theEnv,a) EnvAssignFactSlotDefaults(theEnv,a) -#define CreateFact(theEnv,a) EnvCreateFact(theEnv,a) -#define DecrementFactCount(theEnv,a) EnvDecrementFactCount(theEnv,a) -#define FactIndex(theEnv,a) EnvFactIndex(theEnv,a) -#define GetFactListChanged(theEnv) EnvGetFactListChanged(theEnv) -#define GetFactPPForm(theEnv,a,b,c) EnvGetFactPPForm(theEnv,a,b,c) -#define GetFactSlot(theEnv,a,b,c) EnvGetFactSlot(theEnv,a,b,c) -#define GetNextFact(theEnv,a) EnvGetNextFact(theEnv,a) -#define IncrementFactCount(theEnv,a) EnvIncrementFactCount(theEnv,a) -#define PutFactSlot(theEnv,a,b,c) EnvPutFactSlot(theEnv,a,b,c) -#define Retract(theEnv,a) EnvRetract(theEnv,a) -#define SetFactListChanged(theEnv,a) EnvSetFactListChanged(theEnv,a) -#else -#define Assert(a) EnvAssert(GetCurrentEnvironment(),a) -#define AssertString(a) EnvAssertString(GetCurrentEnvironment(),a) -#define AssignFactSlotDefaults(a) EnvAssignFactSlotDefaults(GetCurrentEnvironment(),a) -#define CreateFact(a) EnvCreateFact(GetCurrentEnvironment(),a) -#define DecrementFactCount(a) EnvDecrementFactCount(GetCurrentEnvironment(),a) -#define FactIndex(a) EnvFactIndex(GetCurrentEnvironment(),a) -#define GetFactListChanged() EnvGetFactListChanged(GetCurrentEnvironment()) -#define GetFactPPForm(a,b,c) EnvGetFactPPForm(GetCurrentEnvironment(),a,b,c) -#define GetFactSlot(a,b,c) EnvGetFactSlot(GetCurrentEnvironment(),a,b,c) -#define GetNextFact(a) EnvGetNextFact(GetCurrentEnvironment(),a) -#define IncrementFactCount(a) EnvIncrementFactCount(GetCurrentEnvironment(),a) -#define PutFactSlot(a,b,c) EnvPutFactSlot(GetCurrentEnvironment(),a,b,c) -#define Retract(a) EnvRetract(GetCurrentEnvironment(),a) -#define SetFactListChanged(a) EnvSetFactListChanged(GetCurrentEnvironment(),a) -#endif - LOCALE void *EnvAssert(void *,void *); - LOCALE void *EnvAssertString(void *,char *); + LOCALE void *EnvAssertString(void *,const char *); LOCALE struct fact *EnvCreateFact(void *,void *); LOCALE void EnvDecrementFactCount(void *,void *); - LOCALE long int EnvFactIndex(void *,void *); - LOCALE intBool EnvGetFactSlot(void *,void *,char *,DATA_OBJECT *); - LOCALE void PrintFactWithIdentifier(void *,char *,struct fact *); - LOCALE void PrintFact(void *,char *,struct fact *,int,int); - LOCALE void PrintFactIdentifierInLongForm(void *,char *,void *); + LOCALE long long EnvFactIndex(void *,void *); + LOCALE intBool EnvGetFactSlot(void *,void *,const char *,DATA_OBJECT *); + LOCALE void PrintFactWithIdentifier(void *,const char *,struct fact *); + LOCALE void PrintFact(void *,const char *,struct fact *,int,int); + LOCALE void PrintFactIdentifierInLongForm(void *,const char *,void *); LOCALE intBool EnvRetract(void *,void *); LOCALE void RemoveAllFacts(void *); LOCALE struct fact *CreateFactBySize(void *,unsigned); @@ -149,33 +154,67 @@ struct factsData LOCALE void FactDeinstall(void *,struct fact *); LOCALE void *EnvGetNextFact(void *,void *); LOCALE void *GetNextFactInScope(void *theEnv,void *); - LOCALE void EnvGetFactPPForm(void *,char *,unsigned,void *); + LOCALE void EnvGetFactPPForm(void *,char *,size_t,void *); LOCALE int EnvGetFactListChanged(void *); LOCALE void EnvSetFactListChanged(void *,int); LOCALE unsigned long GetNumberOfFacts(void *); LOCALE void InitializeFacts(void *); - LOCALE struct fact *FindIndexedFact(void *,long); + LOCALE struct fact *FindIndexedFact(void *,long long); LOCALE void EnvIncrementFactCount(void *,void *); - LOCALE void PrintFactIdentifier(void *,char *,void *); + LOCALE void PrintFactIdentifier(void *,const char *,void *); LOCALE void DecrementFactBasisCount(void *,void *); LOCALE void IncrementFactBasisCount(void *,void *); + LOCALE intBool FactIsDeleted(void *,void *); LOCALE void ReturnFact(void *,struct fact *); LOCALE void MatchFactFunction(void *,void *); - LOCALE intBool EnvPutFactSlot(void *,void *,char *,DATA_OBJECT *); + LOCALE intBool EnvPutFactSlot(void *,void *,const char *,DATA_OBJECT *); LOCALE intBool EnvAssignFactSlotDefaults(void *,void *); LOCALE intBool CopyFactSlotValues(void *,void *,void *); LOCALE intBool DeftemplateSlotDefault(void *,struct deftemplate *, struct templateSlot *,DATA_OBJECT *,int); - -#ifndef _FACTMNGR_SOURCE_ - extern int ChangeToFactList; - extern struct fact DummyFact; -#if DEBUGGING_FUNCTIONS - extern unsigned WatchFacts; -#endif -#endif - -#endif + LOCALE intBool EnvAddAssertFunction(void *,const char *, + void (*)(void *,void *),int); + LOCALE intBool EnvAddAssertFunctionWithContext(void *,const char *, + void (*)(void *,void *),int,void *); + LOCALE intBool EnvRemoveAssertFunction(void *,const char *); + LOCALE intBool EnvAddRetractFunction(void *,const char *, + void (*)(void *,void *),int); + LOCALE intBool EnvAddRetractFunctionWithContext(void *,const char *, + void (*)(void *,void *),int,void *); + LOCALE intBool EnvRemoveRetractFunction(void *,const char *); + LOCALE intBool EnvAddModifyFunction(void *,const char *, + void (*)(void *,void *,void *),int); + LOCALE intBool EnvAddModifyFunctionWithContext(void *,const char *, + void (*)(void *,void *,void *),int,void *); + LOCALE intBool EnvRemoveModifyFunction(void *,const char *); + + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool AddAssertFunction(const char *,void (*)(void *,void *),int); + LOCALE intBool AddModifyFunction(const char *,void (*)(void *,void *,void *),int); + LOCALE intBool AddRetractFunction(const char *,void (*)(void *,void *),int); + LOCALE void *Assert(void *); + LOCALE void *AssertString(const char *); + LOCALE intBool AssignFactSlotDefaults(void *); + LOCALE struct fact *CreateFact(void *); + LOCALE void DecrementFactCount(void *); + LOCALE long long FactIndex(void *); + LOCALE int GetFactListChanged(void); + LOCALE void GetFactPPForm(char *,unsigned,void *); + LOCALE intBool GetFactSlot(void *,const char *,DATA_OBJECT *); + LOCALE void *GetNextFact(void *); + LOCALE void IncrementFactCount(void *); + LOCALE intBool PutFactSlot(void *,const char *,DATA_OBJECT *); + LOCALE intBool RemoveAssertFunction(const char *); + LOCALE intBool RemoveModifyFunction(const char *); + LOCALE intBool RemoveRetractFunction(const char *); + LOCALE intBool Retract(void *); + LOCALE void SetFactListChanged(int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_factmngr */ diff --git a/src/factprt.c b/src/factprt.c index e95184a..3db0e94 100644 --- a/src/factprt.c +++ b/src/factprt.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE PRINT FUNCTIONS MODULE */ /*******************************************************/ @@ -16,6 +16,17 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Updates to support new struct members. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _FACTPRT_SOURCE_ @@ -38,12 +49,9 @@ /* PrintFactJNCompVars1: Print routine */ /* for the FactJNCompVars1 function. */ /***************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactJNCompVars1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -51,16 +59,33 @@ globle void PrintFactJNCompVars1( hack = (struct factCompVarsJN1Call *) ValueToBitMap(theValue); EnvPrintRouter(theEnv,logicalName,"(fact-jn-cmp-vars1 "); - if (hack->pass) EnvPrintRouter(theEnv,logicalName,"p "); - else EnvPrintRouter(theEnv,logicalName,"n "); - PrintLongInteger(theEnv,logicalName,(long) hack->slot1); - EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->pattern2); - EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->slot2); + if (hack->pass) EnvPrintRouter(theEnv,logicalName,"= "); + else EnvPrintRouter(theEnv,logicalName,"<> "); + + EnvPrintRouter(theEnv,logicalName,"p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->pattern1 + 1); + + if (hack->p1lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->p1rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } + + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->slot1); + + EnvPrintRouter(theEnv,logicalName," p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->pattern2 + 1); + + if (hack->p2lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->p2rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } + + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->slot2); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -72,12 +97,9 @@ globle void PrintFactJNCompVars1( /* PrintFactJNCompVars2: Print routine */ /* for the FactJNCompVars2 function. */ /***************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactJNCompVars2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -85,36 +107,45 @@ globle void PrintFactJNCompVars2( hack = (struct factCompVarsJN2Call *) ValueToBitMap(theValue); EnvPrintRouter(theEnv,logicalName,"(fact-jn-cmp-vars2 "); - if (hack->pass) EnvPrintRouter(theEnv,logicalName,"p "); - else EnvPrintRouter(theEnv,logicalName,"n "); + if (hack->pass) EnvPrintRouter(theEnv,logicalName,"= "); + else EnvPrintRouter(theEnv,logicalName,"<> "); - EnvPrintRouter(theEnv,logicalName,"s"); - PrintLongInteger(theEnv,logicalName,(long) hack->slot1); - EnvPrintRouter(theEnv,logicalName," "); + EnvPrintRouter(theEnv,logicalName,"p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->pattern1 + 1); - if (hack->fromBeginning1) EnvPrintRouter(theEnv,logicalName,"b "); - else EnvPrintRouter(theEnv,logicalName,"e "); + if (hack->p1lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->p1rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } - EnvPrintRouter(theEnv,logicalName,"f"); - PrintLongInteger(theEnv,logicalName,(long) hack->offset1); - EnvPrintRouter(theEnv,logicalName," "); + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->slot1); - EnvPrintRouter(theEnv,logicalName,"p"); - PrintLongInteger(theEnv,logicalName,(long) hack->pattern2); - EnvPrintRouter(theEnv,logicalName," "); + if (hack->fromBeginning1) EnvPrintRouter(theEnv,logicalName, " b"); + else EnvPrintRouter(theEnv,logicalName," e"); - EnvPrintRouter(theEnv,logicalName,"s"); - PrintLongInteger(theEnv,logicalName,(long) hack->slot2); - EnvPrintRouter(theEnv,logicalName," "); + EnvPrintRouter(theEnv,logicalName," f"); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset1); + + EnvPrintRouter(theEnv,logicalName," p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->pattern2 + 1); - if (hack->fromBeginning2) EnvPrintRouter(theEnv,logicalName,"b "); - else EnvPrintRouter(theEnv,logicalName,"e "); + if (hack->p2lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->p2rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } - EnvPrintRouter(theEnv,logicalName,"f"); - PrintLongInteger(theEnv,logicalName,(long) hack->offset2); + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->slot2); + + if (hack->fromBeginning2) EnvPrintRouter(theEnv,logicalName," b"); + else EnvPrintRouter(theEnv,logicalName," e"); + + EnvPrintRouter(theEnv,logicalName," f"); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset2); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -126,12 +157,9 @@ globle void PrintFactJNCompVars2( /* PrintFactPNCompVars1: Print routine */ /* for the FactPNCompVars1 function. */ /***************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNCompVars1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -141,12 +169,12 @@ globle void PrintFactPNCompVars1( EnvPrintRouter(theEnv,logicalName,"(fact-pn-cmp-vars "); if (hack->pass) EnvPrintRouter(theEnv,logicalName,"p "); else EnvPrintRouter(theEnv,logicalName,"n "); - PrintLongInteger(theEnv,logicalName,(long) hack->field1); + PrintLongInteger(theEnv,logicalName,(long long) hack->field1); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->field2); + PrintLongInteger(theEnv,logicalName,(long long) hack->field2); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -158,12 +186,9 @@ globle void PrintFactPNCompVars1( /* PrintFactSlotLength: Print routine */ /* for the FactSlotLength function. */ /**************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactSlotLength( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -172,14 +197,14 @@ globle void PrintFactSlotLength( hack = (struct factCheckLengthPNCall *) ValueToBitMap(theValue); EnvPrintRouter(theEnv,logicalName,"(slot-length "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); EnvPrintRouter(theEnv,logicalName," "); if (hack->exactly) EnvPrintRouter(theEnv,logicalName,"= "); else EnvPrintRouter(theEnv,logicalName,">= "); - PrintLongInteger(theEnv,logicalName,(long) hack->minLength); + PrintLongInteger(theEnv,logicalName,(long long) hack->minLength); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -191,12 +216,9 @@ globle void PrintFactSlotLength( /* PrintFactJNGetVar1: Print routine */ /* for the FactJNGetvar1 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactJNGetVar1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -209,14 +231,20 @@ globle void PrintFactJNGetVar1( if (hack->allFields) EnvPrintRouter(theEnv,logicalName,"t "); else EnvPrintRouter(theEnv,logicalName,"f "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); - EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichField); + EnvPrintRouter(theEnv,logicalName,"p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern + 1); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichField); + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); + + if (hack->lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -228,26 +256,28 @@ globle void PrintFactJNGetVar1( /* PrintFactJNGetVar2: Print routine */ /* for the FactJNGetvar2 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactJNGetVar2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER struct factGetVarJN2Call *hack; hack = (struct factGetVarJN2Call *) ValueToBitMap(theValue); - EnvPrintRouter(theEnv,logicalName,"(fact-jn-getvar-2 "); - - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); - EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + EnvPrintRouter(theEnv,logicalName,"(fact-jn-getvar-2"); + + EnvPrintRouter(theEnv,logicalName," p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern + 1); + EnvPrintRouter(theEnv,logicalName," s"); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); + if (hack->lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -259,12 +289,9 @@ globle void PrintFactJNGetVar2( /* PrintFactJNGetVar3: Print routine */ /* for the FactJNGetVar3 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactJNGetVar3( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -277,14 +304,23 @@ globle void PrintFactJNGetVar3( if (hack->fromEnd) EnvPrintRouter(theEnv,logicalName,"t "); else EnvPrintRouter(theEnv,logicalName,"f "); - PrintLongInteger(theEnv,logicalName,(long) hack->beginOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->beginOffset); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->endOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->endOffset); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); + + EnvPrintRouter(theEnv,logicalName," p"); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern + 1); + + if (hack->lhs) + { EnvPrintRouter(theEnv,logicalName," L"); } + else if (hack->rhs) + { EnvPrintRouter(theEnv,logicalName," R"); } + EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -296,12 +332,9 @@ globle void PrintFactJNGetVar3( /* PrintFactPNGetVar1: Print routine */ /* for the FactPNGetvar1 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNGetVar1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -314,12 +347,12 @@ globle void PrintFactPNGetVar1( if (hack->allFields) EnvPrintRouter(theEnv,logicalName,"t F"); else EnvPrintRouter(theEnv,logicalName,"f F"); - PrintLongInteger(theEnv,logicalName,(long) hack->whichField); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichField); EnvPrintRouter(theEnv,logicalName," S"); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -331,12 +364,9 @@ globle void PrintFactPNGetVar1( /* PrintFactPNGetVar2: Print routine */ /* for the FactPNGetvar2 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNGetVar2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -344,10 +374,10 @@ globle void PrintFactPNGetVar2( hack = (struct factGetVarPN2Call *) ValueToBitMap(theValue);; EnvPrintRouter(theEnv,logicalName,"(fact-pn-getvar-2 S"); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -359,12 +389,9 @@ globle void PrintFactPNGetVar2( /* PrintFactPNGetVar3: Print routine */ /* for the FactPNGetvar3 function. */ /*************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNGetVar3( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -378,14 +405,14 @@ globle void PrintFactPNGetVar3( if (hack->fromEnd) EnvPrintRouter(theEnv,logicalName,"t B"); else EnvPrintRouter(theEnv,logicalName,"f B"); - PrintLongInteger(theEnv,logicalName,(long) hack->beginOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->beginOffset); EnvPrintRouter(theEnv,logicalName," E"); - PrintLongInteger(theEnv,logicalName,(long) hack->endOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->endOffset); EnvPrintRouter(theEnv,logicalName," S"); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -397,12 +424,9 @@ globle void PrintFactPNGetVar3( /* PrintFactPNConstant1: Print routine */ /* for the FactPNConstant1 function. */ /***************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNConstant1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -412,7 +436,7 @@ globle void PrintFactPNConstant1( EnvPrintRouter(theEnv,logicalName,"(fact-pn-constant1 "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); if (hack->testForEquality) EnvPrintRouter(theEnv,logicalName," = "); else EnvPrintRouter(theEnv,logicalName," != "); @@ -420,7 +444,7 @@ globle void PrintFactPNConstant1( PrintAtom(theEnv,logicalName,GetFirstArgument()->type,GetFirstArgument()->value); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -432,12 +456,9 @@ globle void PrintFactPNConstant1( /* PrintFactPNConstant2: Print routine */ /* for the FactPNConstant2 function. */ /***************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintFactPNConstant2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -447,11 +468,11 @@ globle void PrintFactPNConstant2( EnvPrintRouter(theEnv,logicalName,"(fact-pn-constant2 "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichSlot); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichSlot); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->offset); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset); if (hack->testForEquality) EnvPrintRouter(theEnv,logicalName," = "); else EnvPrintRouter(theEnv,logicalName," != "); @@ -459,7 +480,7 @@ globle void PrintFactPNConstant2( PrintAtom(theEnv,logicalName,GetFirstArgument()->type,GetFirstArgument()->value); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) diff --git a/src/factprt.h b/src/factprt.h index 4c80dfa..afaab4f 100644 --- a/src/factprt.h +++ b/src/factprt.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE PRINT FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -16,6 +16,17 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Updates to support new struct members. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_factprt @@ -32,19 +43,19 @@ #define LOCALE extern #endif - LOCALE void PrintFactJNCompVars1(void *,char *,void *); - LOCALE void PrintFactJNCompVars2(void *,char *,void *); - LOCALE void PrintFactPNCompVars1(void *,char *,void *); - LOCALE void PrintFactJNGetVar1(void *,char *,void *); - LOCALE void PrintFactJNGetVar2(void *,char *,void *); - LOCALE void PrintFactJNGetVar3(void *,char *,void *); - LOCALE void PrintFactPNGetVar1(void *,char *,void *); - LOCALE void PrintFactPNGetVar2(void *,char *,void *); - LOCALE void PrintFactPNGetVar3(void *,char *,void *); - LOCALE void PrintFactSlotLength(void *,char *,void *); - LOCALE void PrintFactPNConstant1(void *,char *,void *); - LOCALE void PrintFactPNConstant2(void *,char *,void *); - -#endif + LOCALE void PrintFactJNCompVars1(void *,const char *,void *); + LOCALE void PrintFactJNCompVars2(void *,const char *,void *); + LOCALE void PrintFactPNCompVars1(void *,const char *,void *); + LOCALE void PrintFactJNGetVar1(void *,const char *,void *); + LOCALE void PrintFactJNGetVar2(void *,const char *,void *); + LOCALE void PrintFactJNGetVar3(void *,const char *,void *); + LOCALE void PrintFactPNGetVar1(void *,const char *,void *); + LOCALE void PrintFactPNGetVar2(void *,const char *,void *); + LOCALE void PrintFactPNGetVar3(void *,const char *,void *); + LOCALE void PrintFactSlotLength(void *,const char *,void *); + LOCALE void PrintFactPNConstant1(void *,const char *,void *); + LOCALE void PrintFactPNConstant2(void *,const char *,void *); + +#endif /* _H_factprt */ diff --git a/src/factqpsr.c b/src/factqpsr.c index a694836..2fbcc06 100644 --- a/src/factqpsr.c +++ b/src/factqpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* FACT-SET QUERIES PARSER MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: Fact_set Queries Parsing Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ +/* */ /* 6.23: Added fact-set queries. */ /* */ /* Changed name of variable exp to theExp */ @@ -24,6 +25,17 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Fixed memory leaks when error occurred. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ /* ========================================= @@ -63,15 +75,15 @@ INTERNALLY VISIBLE FUNCTION HEADERS ========================================= ***************************************** */ - + /***************************************/ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static EXPRESSION *ParseQueryRestrictions(void *,EXPRESSION *,char *,struct token *); + static EXPRESSION *ParseQueryRestrictions(void *,EXPRESSION *,const char *,struct token *); static intBool ReplaceTemplateNameWithReference(void *,EXPRESSION *); - static int ParseQueryTestExpression(void *,EXPRESSION *,char *); - static int ParseQueryActionExpression(void *,EXPRESSION *,char *,EXPRESSION *,struct token *); + static int ParseQueryTestExpression(void *,EXPRESSION *,const char *); + static int ParseQueryActionExpression(void *,EXPRESSION *,const char *,EXPRESSION *,struct token *); static void ReplaceFactVariables(void *,EXPRESSION *,EXPRESSION *,int,int); static void ReplaceSlotReference(void *,EXPRESSION *,EXPRESSION *, struct FunctionDefinition *,int); @@ -115,7 +127,7 @@ globle EXPRESSION *FactParseQueryNoAction( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *factQuerySetVars; struct token queryInputToken; @@ -123,20 +135,20 @@ globle EXPRESSION *FactParseQueryNoAction( factQuerySetVars = ParseQueryRestrictions(theEnv,top,readSource,&queryInputToken); if (factQuerySetVars == NULL) { return(NULL); } - + IncrementIndentDepth(theEnv,3); PPCRAndIndent(theEnv); - + if (ParseQueryTestExpression(theEnv,top,readSource) == FALSE) { DecrementIndentDepth(theEnv,3); ReturnExpression(theEnv,factQuerySetVars); return(NULL); } - + DecrementIndentDepth(theEnv,3); - - GetToken(theEnv,readSource,&queryInputToken); + + GetToken(theEnv,readSource,&queryInputToken); if (GetType(queryInputToken) != RPAREN) { SyntaxErrorMessage(theEnv,"fact-set query function"); @@ -144,10 +156,10 @@ globle EXPRESSION *FactParseQueryNoAction( ReturnExpression(theEnv,factQuerySetVars); return(NULL); } - + ReplaceFactVariables(theEnv,factQuerySetVars,top->argList,TRUE,0); ReturnExpression(theEnv,factQuerySetVars); - + return(top); } @@ -183,7 +195,7 @@ globle EXPRESSION *FactParseQueryNoAction( globle EXPRESSION *FactParseQueryAction( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *factQuerySetVars; struct token queryInputToken; @@ -191,28 +203,28 @@ globle EXPRESSION *FactParseQueryAction( factQuerySetVars = ParseQueryRestrictions(theEnv,top,readSource,&queryInputToken); if (factQuerySetVars == NULL) { return(NULL); } - + IncrementIndentDepth(theEnv,3); PPCRAndIndent(theEnv); - + if (ParseQueryTestExpression(theEnv,top,readSource) == FALSE) { DecrementIndentDepth(theEnv,3); ReturnExpression(theEnv,factQuerySetVars); return(NULL); } - + PPCRAndIndent(theEnv); - + if (ParseQueryActionExpression(theEnv,top,readSource,factQuerySetVars,&queryInputToken) == FALSE) { DecrementIndentDepth(theEnv,3); ReturnExpression(theEnv,factQuerySetVars); return(NULL); } - + DecrementIndentDepth(theEnv,3); - + if (GetType(queryInputToken) != RPAREN) { SyntaxErrorMessage(theEnv,"fact-set query function"); @@ -220,11 +232,11 @@ globle EXPRESSION *FactParseQueryAction( ReturnExpression(theEnv,factQuerySetVars); return(NULL); } - + ReplaceFactVariables(theEnv,factQuerySetVars,top->argList,TRUE,0); ReplaceFactVariables(theEnv,factQuerySetVars,top->argList->nextArg,FALSE,0); ReturnExpression(theEnv,factQuerySetVars); - + return(top); } @@ -251,7 +263,7 @@ globle EXPRESSION *FactParseQueryAction( static EXPRESSION *ParseQueryRestrictions( void *theEnv, EXPRESSION *top, - char *readSource, + const char *readSource, struct token *queryInputToken) { EXPRESSION *factQuerySetVars = NULL,*lastFactQuerySetVars = NULL, @@ -260,21 +272,21 @@ static EXPRESSION *ParseQueryRestrictions( int error = FALSE; SavePPBuffer(theEnv," "); - + GetToken(theEnv,readSource,queryInputToken); if (queryInputToken->type != LPAREN) { goto ParseQueryRestrictionsError1; } - + GetToken(theEnv,readSource,queryInputToken); if (queryInputToken->type != LPAREN) { goto ParseQueryRestrictionsError1; } - + while (queryInputToken->type == LPAREN) { GetToken(theEnv,readSource,queryInputToken); if (queryInputToken->type != SF_VARIABLE) { goto ParseQueryRestrictionsError1; } - + tmp = factQuerySetVars; while (tmp != NULL) { @@ -286,33 +298,33 @@ static EXPRESSION *ParseQueryRestrictions( EnvPrintRouter(theEnv,WERROR,".\n"); goto ParseQueryRestrictionsError2; } - + tmp = tmp->nextArg; } - + tmp = GenConstant(theEnv,SF_VARIABLE,queryInputToken->value); if (factQuerySetVars == NULL) { factQuerySetVars = tmp; } else { lastFactQuerySetVars->nextArg = tmp; } - + lastFactQuerySetVars = tmp; SavePPBuffer(theEnv," "); - + templateExp = ArgumentParse(theEnv,readSource,&error); - + if (error) { goto ParseQueryRestrictionsError2; } - + if (templateExp == NULL) { goto ParseQueryRestrictionsError1; } - + if (ReplaceTemplateNameWithReference(theEnv,templateExp) == FALSE) { goto ParseQueryRestrictionsError2; } - + lastTemplateExp = templateExp; SavePPBuffer(theEnv," "); - + while ((tmp = ArgumentParse(theEnv,readSource,&error)) != NULL) { if (ReplaceTemplateNameWithReference(theEnv,tmp) == FALSE) @@ -321,33 +333,33 @@ static EXPRESSION *ParseQueryRestrictions( lastTemplateExp = tmp; SavePPBuffer(theEnv," "); } - + if (error) { goto ParseQueryRestrictionsError2; } - + PPBackup(theEnv); PPBackup(theEnv); SavePPBuffer(theEnv,")"); - + tmp = GenConstant(theEnv,SYMBOL,(void *) FactQueryData(theEnv)->QUERY_DELIMETER_SYMBOL); - + lastTemplateExp->nextArg = tmp; lastTemplateExp = tmp; - + if (top->argList == NULL) { top->argList = templateExp; } else { lastOne->nextArg = templateExp; } - + lastOne = lastTemplateExp; templateExp = NULL; SavePPBuffer(theEnv," "); GetToken(theEnv,readSource,queryInputToken); } - + if (queryInputToken->type != RPAREN) { goto ParseQueryRestrictionsError1; } - + PPBackup(theEnv); PPBackup(theEnv); SavePPBuffer(theEnv,")"); @@ -381,24 +393,24 @@ static intBool ReplaceTemplateNameWithReference( void *theEnv, EXPRESSION *theExp) { - char *theTemplateName; + const char *theTemplateName; void *theDeftemplate; int count; if (theExp->type == SYMBOL) { theTemplateName = ValueToString(theExp->value); - + theDeftemplate = (struct deftemplate *) FindImportedConstruct(theEnv,"deftemplate",NULL,theTemplateName, &count,TRUE,NULL); if (theDeftemplate == NULL) - { /* TBD */ + { CantFindItemErrorMessage(theEnv,"deftemplate",theTemplateName); return(FALSE); } - + if (count > 1) { AmbiguousReferenceErrorMessage(theEnv,"deftemplate",theTemplateName); @@ -407,7 +419,13 @@ static intBool ReplaceTemplateNameWithReference( theExp->type = DEFTEMPLATE_PTR; theExp->value = theDeftemplate; + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif } + return(TRUE); } @@ -426,7 +444,7 @@ static intBool ReplaceTemplateNameWithReference( static int ParseQueryTestExpression( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *qtest; int error; @@ -435,27 +453,29 @@ static int ParseQueryTestExpression( error = FALSE; oldBindList = GetParsedBindNames(theEnv); SetParsedBindNames(theEnv,NULL); - + qtest = ArgumentParse(theEnv,readSource,&error); - + if (error == TRUE) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); ReturnExpression(theEnv,top); return(FALSE); } - + if (qtest == NULL) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); SyntaxErrorMessage(theEnv,"fact-set query function"); ReturnExpression(theEnv,top); return(FALSE); } - + qtest->nextArg = top->argList; top->argList = qtest; - + if (ParsedBindNamesEmpty(theEnv) == FALSE) { ClearParsedBindNames(theEnv); @@ -467,9 +487,9 @@ static int ParseQueryTestExpression( ReturnExpression(theEnv,top); return(FALSE); } - + SetParsedBindNames(theEnv,oldBindList); - + return(TRUE); } @@ -490,47 +510,39 @@ static int ParseQueryTestExpression( static int ParseQueryActionExpression( void *theEnv, EXPRESSION *top, - char *readSource, + const char *readSource, EXPRESSION *factQuerySetVars, struct token *queryInputToken) { EXPRESSION *qaction,*tmpFactSetVars; - int error; struct BindInfo *oldBindList,*newBindList,*prev; - error = FALSE; oldBindList = GetParsedBindNames(theEnv); SetParsedBindNames(theEnv,NULL); - + ExpressionData(theEnv)->BreakContext = TRUE; ExpressionData(theEnv)->ReturnContext = ExpressionData(theEnv)->svContexts->rtn; qaction = GroupActions(theEnv,readSource,queryInputToken,TRUE,NULL,FALSE); - + PPBackup(theEnv); PPBackup(theEnv); SavePPBuffer(theEnv,queryInputToken->printForm); ExpressionData(theEnv)->BreakContext = FALSE; - - if (error == TRUE) - { - SetParsedBindNames(theEnv,oldBindList); - ReturnExpression(theEnv,top); - return(FALSE); - } - + if (qaction == NULL) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); SyntaxErrorMessage(theEnv,"fact-set query function"); ReturnExpression(theEnv,top); return(FALSE); } - + qaction->nextArg = top->argList->nextArg; top->argList->nextArg = qaction; - + newBindList = GetParsedBindNames(theEnv); prev = NULL; while (newBindList != NULL) @@ -556,12 +568,12 @@ static int ParseQueryActionExpression( prev = newBindList; newBindList = newBindList->next; } - + if (prev == NULL) { SetParsedBindNames(theEnv,oldBindList); } else { prev->next = oldBindList; } - + return(TRUE); } @@ -612,8 +624,8 @@ static void ReplaceFactVariables( { bexp->type = FCALL; bexp->value = (void *) rindx_func; - eptr = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) ndepth)); - eptr->nextArg = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) posn)); + eptr = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) ndepth)); + eptr->nextArg = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) posn)); bexp->argList = eptr; } else if (sdirect == TRUE) @@ -652,10 +664,10 @@ static void ReplaceSlotReference( struct FunctionDefinition *func, int ndepth) { - unsigned len; + size_t len; int posn,oldpp; - register unsigned i; - register char *str; + size_t i; + const char *str; EXPRESSION *eptr; struct token itkn; @@ -686,9 +698,9 @@ static void ReplaceSlotReference( CloseStringSource(theEnv,"query-var"); theExp->type = FCALL; theExp->value = (void *) func; - theExp->argList = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) ndepth)); + theExp->argList = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) ndepth)); theExp->argList->nextArg = - GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) posn)); + GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) posn)); theExp->argList->nextArg->nextArg = GenConstant(theEnv,itkn.type,itkn.value); break; } diff --git a/src/factqpsr.h b/src/factqpsr.h index 4d977de..a7d770c 100644 --- a/src/factqpsr.h +++ b/src/factqpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,14 +10,28 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ +/* */ /* 6.23: Added fact-set queries. */ /* */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Fixed memory leaks when error occurred. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_factqpsr @@ -39,15 +53,9 @@ #define LOCALE extern #endif -LOCALE EXPRESSION *FactParseQueryNoAction(void *,EXPRESSION *,char *); -LOCALE EXPRESSION *FactParseQueryAction(void *,EXPRESSION *,char *); - -#ifndef _FACTQPSR_SOURCE_ -#endif - -#endif - -#endif - + LOCALE EXPRESSION *FactParseQueryNoAction(void *,EXPRESSION *,const char *); + LOCALE EXPRESSION *FactParseQueryAction(void *,EXPRESSION *,const char *); +#endif /* FACT_SET_QUERIES && (! RUN_TIME) */ +#endif /* _H_factqpsr */ diff --git a/src/factqury.c b/src/factqury.c index 4b8138c..e0765cf 100644 --- a/src/factqury.c +++ b/src/factqury.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Query Functions for Objects */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ @@ -24,6 +24,12 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Fixes for run-time use of query functions. */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -59,8 +65,8 @@ static void PushQueryCore(void *); static void PopQueryCore(void *); static QUERY_CORE *FindQueryCore(void *,int); -static QUERY_TEMPLATE *DetermineQueryTemplates(void *,EXPRESSION *,char *,unsigned *); -static QUERY_TEMPLATE *FormChain(void *,char *,DATA_OBJECT *); +static QUERY_TEMPLATE *DetermineQueryTemplates(void *,EXPRESSION *,const char *,unsigned *); +static QUERY_TEMPLATE *FormChain(void *,const char *,DATA_OBJECT *); static void DeleteQueryTemplates(void *,QUERY_TEMPLATE *); static int TestForFirstInChain(void *,QUERY_TEMPLATE *,int); static int TestForFirstFactInTemplate(void *,struct deftemplate *,QUERY_TEMPLATE *,int); @@ -83,6 +89,10 @@ globle void SetupFactQuery( { AllocateEnvironmentData(theEnv,FACT_QUERY_DATA,sizeof(struct factQueryData),NULL); +#if RUN_TIME + FactQueryData(theEnv)->QUERY_DELIMETER_SYMBOL = FindSymbolHN(theEnv,QUERY_DELIMETER_STRING); +#endif + #if ! RUN_TIME FactQueryData(theEnv)->QUERY_DELIMETER_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,QUERY_DELIMETER_STRING); IncrementSymbolCount(FactQueryData(theEnv)->QUERY_DELIMETER_SYMBOL); @@ -134,11 +144,10 @@ globle void GetQueryFact( { register QUERY_CORE *core; - core = FindQueryCore(theEnv,DOPToInteger(GetFirstArgument())); - + core = FindQueryCore(theEnv,ValueToInteger(GetpValue(GetFirstArgument()))); + result->type = FACT_ADDRESS; - result->value = core->solns[DOPToInteger(GetFirstArgument()->nextArg)]; - /* return(GetFullInstanceName(theEnv,core->solns[DOPToInteger(GetFirstArgument()->nextArg)])); */ + result->value = core->solns[ValueToInteger(GetpValue(GetFirstArgument()->nextArg))]; } /*************************************************************************** @@ -162,8 +171,8 @@ globle void GetQueryFactSlot( result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); - core = FindQueryCore(theEnv,DOPToInteger(GetFirstArgument())); - theFact = core->solns[DOPToInteger(GetFirstArgument()->nextArg)]; + core = FindQueryCore(theEnv,ValueToInteger(GetpValue(GetFirstArgument()))); + theFact = core->solns[ValueToInteger(GetpValue(GetFirstArgument()->nextArg))]; EvaluateExpression(theEnv,GetFirstArgument()->nextArg->nextArg,&temp); if (temp.type != SYMBOL) { @@ -171,7 +180,7 @@ globle void GetQueryFactSlot( SetEvaluationError(theEnv,TRUE); return; } - + /*==================================================*/ /* Make sure the slot exists (the symbol implied is */ /* used for the implied slot of an ordered fact). */ @@ -179,7 +188,7 @@ globle void GetQueryFactSlot( if (theFact->whichDeftemplate->implied) { - if (strcmp(ValueToString(temp.value),"implied") != 0) /* TBD - no str compare */ + if (strcmp(ValueToString(temp.value),"implied") != 0) { SlotExistError(theEnv,ValueToString(temp.value),"fact-set query"); return; @@ -193,7 +202,7 @@ globle void GetQueryFactSlot( SlotExistError(theEnv,ValueToString(temp.value),"fact-set query"); return; } - + result->type = theFact->theProposition.theFields[position-1].type; result->value = theFact->theProposition.theFields[position-1].value; if (result->type == MULTIFIELD) @@ -466,10 +475,12 @@ globle void QueryDoForAllFacts( result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); + qtemplates = DetermineQueryTemplates(theEnv,GetFirstArgument()->nextArg->nextArg, "do-for-all-facts",&rcnt); if (qtemplates == NULL) return; + PushQueryCore(theEnv); FactQueryData(theEnv)->QueryCore = get_struct(theEnv,query_core); FactQueryData(theEnv)->QueryCore->solns = (struct fact **) gm2(theEnv,(sizeof(struct fact *) * rcnt)); @@ -479,7 +490,7 @@ globle void QueryDoForAllFacts( ValueInstall(theEnv,FactQueryData(theEnv)->QueryCore->result); TestEntireChain(theEnv,qtemplates,0); ValueDeinstall(theEnv,FactQueryData(theEnv)->QueryCore->result); - PropagateReturnValue(theEnv,FactQueryData(theEnv)->QueryCore->result); + FactQueryData(theEnv)->AbortQuery = FALSE; ProcedureFunctionData(theEnv)->BreakFlag = FALSE; rm(theEnv,(void *) FactQueryData(theEnv)->QueryCore->solns,(sizeof(struct fact *) * rcnt)); @@ -512,6 +523,7 @@ globle void DelayedQueryDoForAllFacts( QUERY_TEMPLATE *qtemplates; unsigned rcnt; register unsigned i; + struct garbageFrame newGarbageFrame, *oldGarbageFrame; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); @@ -519,6 +531,7 @@ globle void DelayedQueryDoForAllFacts( "delayed-do-for-all-facts",&rcnt); if (qtemplates == NULL) return; + PushQueryCore(theEnv); FactQueryData(theEnv)->QueryCore = get_struct(theEnv,query_core); FactQueryData(theEnv)->QueryCore->solns = (struct fact **) gm2(theEnv,(sizeof(struct fact *) * rcnt)); @@ -530,24 +543,34 @@ globle void DelayedQueryDoForAllFacts( TestEntireChain(theEnv,qtemplates,0); FactQueryData(theEnv)->AbortQuery = FALSE; FactQueryData(theEnv)->QueryCore->action = GetFirstArgument()->nextArg; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + while (FactQueryData(theEnv)->QueryCore->soln_set != NULL) { for (i = 0 ; i < rcnt ; i++) FactQueryData(theEnv)->QueryCore->solns[i] = FactQueryData(theEnv)->QueryCore->soln_set->soln[i]; PopQuerySoln(theEnv); - EvaluationData(theEnv)->CurrentEvaluationDepth++; + EvaluateExpression(theEnv,FactQueryData(theEnv)->QueryCore->action,result); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - if (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE) - { PropagateReturnValue(theEnv,result); } - PeriodicCleanup(theEnv,FALSE,TRUE); + if (EvaluationData(theEnv)->HaltExecution || ProcedureFunctionData(theEnv)->BreakFlag || ProcedureFunctionData(theEnv)->ReturnFlag) { while (FactQueryData(theEnv)->QueryCore->soln_set != NULL) PopQuerySoln(theEnv); break; } + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + ProcedureFunctionData(theEnv)->BreakFlag = FALSE; rm(theEnv,(void *) FactQueryData(theEnv)->QueryCore->solns,(sizeof(struct fact *) * rcnt)); rtn_struct(theEnv,query_core,FactQueryData(theEnv)->QueryCore); @@ -652,7 +675,7 @@ static QUERY_CORE *FindQueryCore( static QUERY_TEMPLATE *DetermineQueryTemplates( void *theEnv, EXPRESSION *templateExp, - char *func, + const char *func, unsigned *rcnt) { QUERY_TEMPLATE *clist = NULL,*cnxt = NULL,*cchain = NULL,*tmp; @@ -714,13 +737,13 @@ static QUERY_TEMPLATE *DetermineQueryTemplates( *************************************************************/ static QUERY_TEMPLATE *FormChain( void *theEnv, - char *func, + const char *func, DATA_OBJECT *val) { struct deftemplate *templatePtr; QUERY_TEMPLATE *head,*bot,*tmp; register long i,end; /* 6.04 Bug Fix */ - char *templateName; + const char *templateName; int count; if (val->type == DEFTEMPLATE_PTR) @@ -741,7 +764,7 @@ static QUERY_TEMPLATE *FormChain( but search imported defclasses too if a module specifier is not given =============================================== */ - + templatePtr = (struct deftemplate *) FindImportedConstruct(theEnv,"deftemplate",NULL,DOPToString(val), &count,TRUE,NULL); @@ -767,7 +790,7 @@ static QUERY_TEMPLATE *FormChain( if (GetMFType(val->value,i) == SYMBOL) { templateName = ValueToString(GetMFValue(val->value,i)); - + templatePtr = (struct deftemplate *) FindImportedConstruct(theEnv,"deftemplate",NULL,templateName, &count,TRUE,NULL); @@ -858,7 +881,7 @@ static int TestForFirstInChain( if (TestForFirstFactInTemplate(theEnv,qptr->templatePtr,qchain,indx)) { return(TRUE); } - + if ((EvaluationData(theEnv)->HaltExecution == TRUE) || (FactQueryData(theEnv)->AbortQuery == TRUE)) return(FALSE); } @@ -884,6 +907,13 @@ static int TestForFirstFactInTemplate( { struct fact *theFact; DATA_OBJECT temp; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; theFact = templatePtr->factList; while (theFact != NULL) @@ -904,10 +934,11 @@ static int TestForFirstFactInTemplate( else { theFact->factHeader.busyCount++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; EvaluateExpression(theEnv,FactQueryData(theEnv)->QueryCore->query,&temp); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + theFact->factHeader.busyCount--; if (EvaluationData(theEnv)->HaltExecution == TRUE) break; @@ -920,6 +951,9 @@ static int TestForFirstFactInTemplate( theFact = theFact->nextTemplateFact; } + RestorePriorGarbageFrame(theEnv,&newGarbageFrame, oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + if (theFact != NULL) return(((EvaluationData(theEnv)->HaltExecution == TRUE) || (FactQueryData(theEnv)->AbortQuery == TRUE)) ? FALSE : TRUE); @@ -980,6 +1014,13 @@ static void TestEntireTemplate( { struct fact *theFact; DATA_OBJECT temp; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; theFact = templatePtr->factList; while (theFact != NULL) @@ -994,12 +1035,11 @@ static void TestEntireTemplate( break; } else - { + { theFact->factHeader.busyCount++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; + EvaluateExpression(theEnv,FactQueryData(theEnv)->QueryCore->query,&temp); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + theFact->factHeader.busyCount--; if (EvaluationData(theEnv)->HaltExecution == TRUE) break; @@ -1009,12 +1049,10 @@ static void TestEntireTemplate( if (FactQueryData(theEnv)->QueryCore->action != NULL) { theFact->factHeader.busyCount++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; ValueDeinstall(theEnv,FactQueryData(theEnv)->QueryCore->result); EvaluateExpression(theEnv,FactQueryData(theEnv)->QueryCore->action,FactQueryData(theEnv)->QueryCore->result); ValueInstall(theEnv,FactQueryData(theEnv)->QueryCore->result); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + theFact->factHeader.busyCount--; if (ProcedureFunctionData(theEnv)->BreakFlag || ProcedureFunctionData(theEnv)->ReturnFlag) { @@ -1028,11 +1066,17 @@ static void TestEntireTemplate( AddSolution(theEnv); } } - + theFact = theFact->nextTemplateFact; while ((theFact != NULL) ? (theFact->garbage == 1) : FALSE) theFact = theFact->nextTemplateFact; + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame, oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); } /*************************************************************************** @@ -1082,7 +1126,7 @@ static void PopQuerySoln( (sizeof(struct fact *) * FactQueryData(theEnv)->QueryCore->soln_size)); rm(theEnv,(void *) FactQueryData(theEnv)->QueryCore->soln_bottom,sizeof(QUERY_SOLN)); } - + #endif diff --git a/src/factqury.h b/src/factqury.h index c47efdf..fdae6d0 100644 --- a/src/factqury.h +++ b/src/factqury.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ +/* */ /* 6.23: Added fact-set queries. */ /* */ /* 6.24: Corrected errors when compiling as a C++ file. */ @@ -23,6 +24,12 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Fixes for run-time use of query functions. */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_factqury @@ -64,7 +71,7 @@ typedef struct query_stack #define FACT_QUERY_DATA 63 struct factQueryData - { + { SYMBOL_HN *QUERY_DELIMETER_SYMBOL; QUERY_CORE *QueryCore; QUERY_STACK *QueryCoreStack; @@ -85,21 +92,16 @@ struct factQueryData #define QUERY_DELIMETER_STRING "(QDS)" -LOCALE void SetupFactQuery(void *); -LOCALE void GetQueryFact(void *,DATA_OBJECT *); -LOCALE void GetQueryFactSlot(void *,DATA_OBJECT *); -LOCALE intBool AnyFacts(void *); -LOCALE void QueryFindFact(void *,DATA_OBJECT *); -LOCALE void QueryFindAllFacts(void *,DATA_OBJECT *); -LOCALE void QueryDoForFact(void *,DATA_OBJECT *); -LOCALE void QueryDoForAllFacts(void *,DATA_OBJECT *); -LOCALE void DelayedQueryDoForAllFacts(void *,DATA_OBJECT *); - -#endif - -#endif - - - + LOCALE void SetupFactQuery(void *); + LOCALE void GetQueryFact(void *,DATA_OBJECT *); + LOCALE void GetQueryFactSlot(void *,DATA_OBJECT *); + LOCALE intBool AnyFacts(void *); + LOCALE void QueryFindFact(void *,DATA_OBJECT *); + LOCALE void QueryFindAllFacts(void *,DATA_OBJECT *); + LOCALE void QueryDoForFact(void *,DATA_OBJECT *); + LOCALE void QueryDoForAllFacts(void *,DATA_OBJECT *); + LOCALE void DelayedQueryDoForAllFacts(void *,DATA_OBJECT *); +#endif /* FACT_SET_QUERIES */ +#endif /* _H_factqury */ diff --git a/src/factrete.c b/src/factrete.c index c607cde..43f93e3 100644 --- a/src/factrete.c +++ b/src/factrete.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE ACCESS FUNCTIONS MODULE */ /*******************************************************/ @@ -15,12 +15,19 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed INCREMENTAL_RESET compilation flag. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for hashing optimizations. */ +/* */ /*************************************************************/ #define _FACTRETE_SOURCE_ @@ -260,15 +267,12 @@ globle intBool FactPNGetVar3( /* comparing a value stored in a single field slot */ /* to a constant for either equality or inequality. */ /******************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool FactPNConstant1( void *theEnv, void *theValue, DATA_OBJECT_PTR returnValue) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(returnValue) #endif struct factConstantPN1Call *hack; @@ -304,15 +308,12 @@ globle intBool FactPNConstant1( /* no multifields to its right (thus it can be retrieved */ /* relative to the beginning). */ /****************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool FactPNConstant2( void *theEnv, void *theValue, DATA_OBJECT_PTR returnValue) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(returnValue) #endif struct factConstantPN2Call *hack; @@ -385,12 +386,22 @@ globle intBool FactJNGetVar1( /* Get the pointer to the fact from the partial match. */ /*=====================================================*/ - if (EngineData(theEnv)->GlobalRHSBinds == NULL) + if (hack->lhs) + { + factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; + marks = get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->markers; + } + else if (hack->rhs) + { + factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,hack->whichPattern)->matchingItem; + marks = get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,hack->whichPattern)->markers; + } + else if (EngineData(theEnv)->GlobalRHSBinds == NULL) { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; marks = get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->markers; } - else if ((EngineData(theEnv)->GlobalJoin->depth - 1) == hack->whichPattern) + else if ((((unsigned short) (EngineData(theEnv)->GlobalJoin->depth - 1))) == hack->whichPattern) { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; marks = get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->markers; @@ -512,10 +523,14 @@ globle intBool FactJNGetVar2( /* Get the pointer to the fact from the partial match. */ /*=====================================================*/ - if (EngineData(theEnv)->GlobalRHSBinds == NULL) + if (hack->lhs) { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } - else if ((EngineData(theEnv)->GlobalJoin->depth - 1) == hack->whichPattern) - { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; } + else if (hack->rhs) + { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,hack->whichPattern)->matchingItem; } + else if (EngineData(theEnv)->GlobalRHSBinds == NULL) + { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } + else if (((unsigned short) (EngineData(theEnv)->GlobalJoin->depth - 1)) == hack->whichPattern) + { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; } else { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } @@ -556,9 +571,13 @@ globle intBool FactJNGetVar3( /* Get the pointer to the fact from the partial match. */ /*=====================================================*/ - if (EngineData(theEnv)->GlobalRHSBinds == NULL) + if (hack->lhs) + { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } + else if (hack->rhs) + { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,hack->whichPattern)->matchingItem; } + else if (EngineData(theEnv)->GlobalRHSBinds == NULL) { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } - else if ((EngineData(theEnv)->GlobalJoin->depth - 1) == hack->whichPattern) + else if (((unsigned short) (EngineData(theEnv)->GlobalJoin->depth - 1)) == hack->whichPattern) { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; } else { factPtr = (struct fact *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,hack->whichPattern)->matchingItem; } @@ -609,7 +628,7 @@ globle intBool FactSlotLength( { struct factCheckLengthPNCall *hack; struct multifield *segmentPtr; - int extraOffset = 0; + long extraOffset = 0; struct multifieldMarker *tempMark; returnValue->type = SYMBOL; @@ -627,10 +646,10 @@ globle intBool FactSlotLength( segmentPtr = (struct multifield *) FactData(theEnv)->CurrentPatternFact->theProposition.theFields[hack->whichSlot].value; - if (segmentPtr->multifieldLength < (unsigned) (hack->minLength + extraOffset)) + if (segmentPtr->multifieldLength < (hack->minLength + extraOffset)) { return(FALSE); } - if (hack->exactly && (segmentPtr->multifieldLength > (unsigned) (hack->minLength + extraOffset))) + if (hack->exactly && (segmentPtr->multifieldLength > (hack->minLength + extraOffset))) { return(FALSE); } returnValue->value = EnvTrueSymbol(theEnv); @@ -641,15 +660,12 @@ globle intBool FactSlotLength( /* FactJNCompVars1: Fact join network routine for comparing */ /* the values of two single field slots. */ /************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int FactJNCompVars1( void *theEnv, void *theValue, DATA_OBJECT *theResult) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theResult) #endif int p1, e1, p2, e2; @@ -666,14 +682,15 @@ globle int FactJNCompVars1( /* Extract the fact pointers for the two patterns. */ /*=================================================*/ - p1 = EngineData(theEnv)->GlobalJoin->depth - 1; - p2 = ((int) hack->pattern2) - 1; + p1 = (int) hack->pattern1; + p2 = (int) hack->pattern2; - fact1 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[0].gm.theMatch->matchingItem; - if (p1 != p2) - { fact2 = (struct fact *) EngineData(theEnv)->GlobalLHSBinds->binds[p2].gm.theMatch->matchingItem; } + fact1 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[p1].gm.theMatch->matchingItem; + + if (hack->p2rhs) + { fact2 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[p2].gm.theMatch->matchingItem; } else - { fact2 = fact1; } + { fact2 = (struct fact *) EngineData(theEnv)->GlobalLHSBinds->binds[p2].gm.theMatch->matchingItem; } /*=====================*/ /* Compare the values. */ @@ -700,15 +717,12 @@ globle int FactJNCompVars1( /* This function is provided so that variable comparisons of */ /* implied deftemplates will be faster. */ /*****************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int FactJNCompVars2( void *theEnv, void *theValue, DATA_OBJECT *theResult) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theResult) #endif int p1, s1, p2, s2; @@ -727,16 +741,17 @@ globle int FactJNCompVars2( /* Extract the fact pointers for the two patterns. */ /*=================================================*/ - p1 = EngineData(theEnv)->GlobalJoin->depth - 1; - p2 = ((int) hack->pattern2) - 1; + p1 = (int) hack->pattern1; + p2 = (int) hack->pattern2; s1 = (int) hack->slot1; s2 = (int) hack->slot2; - fact1 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[0].gm.theMatch->matchingItem; - if (p1 != p2) - { fact2 = (struct fact *) EngineData(theEnv)->GlobalLHSBinds->binds[p2].gm.theMatch->matchingItem; } + fact1 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[p1].gm.theMatch->matchingItem; + + if (hack->p2rhs) + { fact2 = (struct fact *) EngineData(theEnv)->GlobalRHSBinds->binds[p2].gm.theMatch->matchingItem; } else - { fact2 = fact1; } + { fact2 = (struct fact *) EngineData(theEnv)->GlobalLHSBinds->binds[p2].gm.theMatch->matchingItem; } /*======================*/ /* Retrieve the values. */ @@ -831,9 +846,6 @@ globle int FactPNCompVars1( /* variable ?z) would be 8 since $?x binds to 2 fields and $?y binds */ /* to 3 fields. */ /*************************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned short AdjustFieldPosition( void *theEnv, struct multifieldMarker *markList, @@ -842,7 +854,7 @@ globle unsigned short AdjustFieldPosition( int *extent) { unsigned short actualIndex; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -899,15 +911,12 @@ globle unsigned short AdjustFieldPosition( /* number of multifield functions for grouping a */ /* series of valuesinto a single multifield value. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int FactStoreMultifield( void *theEnv, void *theValue, DATA_OBJECT *theResult) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theValue) #endif diff --git a/src/factrete.h b/src/factrete.h index 04e8aca..183402c 100644 --- a/src/factrete.h +++ b/src/factrete.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FACT RETE ACCESS FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -16,7 +16,17 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for hashing optimizations. */ /* */ /*************************************************************/ diff --git a/src/factrhs.c b/src/factrhs.c index 285dbc6..9da8215 100644 --- a/src/factrhs.c +++ b/src/factrhs.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* FACT RHS PATTERN PARSER MODULE */ /*******************************************************/ @@ -18,10 +18,21 @@ /* */ /* Contributing Programmer(s): */ /* Chris Culbert */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ #define _FACTRHS_SOURCE_ @@ -61,7 +72,7 @@ /***************************************/ #if RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE - static void NoSuchTemplateError(void *,char *); + static void NoSuchTemplateError(void *,const char *); #endif #if (! RUN_TIME) @@ -75,12 +86,12 @@ /**********************************************************************/ globle struct expr *BuildRHSAssert( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken, int *error, int atLeastOne, int readFirstParen, - char *whereParsed) + const char *whereParsed) { struct expr *lastOne, *nextOne, *assertList, *stub; @@ -196,7 +207,7 @@ globle struct expr *BuildRHSAssert( /***************************************************************/ globle struct expr *GetRHSPattern( void *theEnv, - char *readSource, + const char *readSource, struct token *tempToken, int *error, int constantsOnly, @@ -209,6 +220,7 @@ globle struct expr *GetRHSPattern( int printError, count; struct deftemplate *theDeftemplate; struct symbolHashNode *templateName; + const char *nullBitMap = "\0"; /*=================================================*/ /* Get the opening parenthesis of the RHS pattern. */ @@ -338,6 +350,12 @@ globle struct expr *GetRHSPattern( firstOne->nextArg = ParseAssertTemplate(theEnv,readSource,tempToken, error,endType, constantsOnly,theDeftemplate); + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif + if (*error) { ReturnExpression(theEnv,firstOne); @@ -354,6 +372,11 @@ globle struct expr *GetRHSPattern( firstOne = GenConstant(theEnv,DEFTEMPLATE_PTR,theDeftemplate); #if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif + +#if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(theEnv," "); #endif @@ -397,7 +420,7 @@ globle struct expr *GetRHSPattern( /* single multifield slot. */ /*==========================================================*/ - firstOne->nextArg = GenConstant(theEnv,FACT_STORE_MULTIFIELD,AddBitMap(theEnv,(void *) "\0",1)); + firstOne->nextArg = GenConstant(theEnv,FACT_STORE_MULTIFIELD,EnvAddBitMap(theEnv,(void *) nullBitMap,1)); firstOne->nextArg->argList = argHead; /*==============================*/ @@ -417,7 +440,7 @@ globle struct expr *GetRHSPattern( /********************************************************************/ globle struct expr *GetAssertArgument( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken, int *error, int endType, @@ -528,7 +551,7 @@ globle struct expr *GetAssertArgument( /****************************************************/ globle struct fact *StringToFact( void *theEnv, - char *str) + const char *str) { struct token theToken; struct fact *factPtr; @@ -541,7 +564,7 @@ globle struct fact *StringToFact( /* Open a string router and parse the fact */ /* using the router as an input source. */ /*=========================================*/ - + SetEvaluationError(theEnv,FALSE); OpenStringSource(theEnv,"assert_str",str,0); @@ -555,7 +578,7 @@ globle struct fact *StringToFact( /*===========================================*/ /* Check for errors or the use of variables. */ /*===========================================*/ - + if ((assertArgs == NULL) && (! error)) { SyntaxErrorMessage(theEnv,"RHS patterns"); @@ -592,6 +615,7 @@ globle struct fact *StringToFact( /* Copy the fields to the fact data structure. */ /*=============================================*/ + EnvIncrementClearReadyLocks(theEnv); ExpressionInstall(theEnv,assertArgs); /* DR0836 */ whichField = 0; for (tempPtr = assertArgs->nextArg; tempPtr != NULL; tempPtr = tempPtr->nextArg) @@ -603,6 +627,7 @@ globle struct fact *StringToFact( } ExpressionDeinstall(theEnv,assertArgs); /* DR0836 */ ReturnExpression(theEnv,assertArgs); + EnvDecrementClearReadyLocks(theEnv); /*==================*/ /* Return the fact. */ @@ -621,7 +646,7 @@ globle struct fact *StringToFact( /*********************************************************/ static void NoSuchTemplateError( void *theEnv, - char *templateName) + const char *templateName) { PrintErrorID(theEnv,"FACTRHS",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Template "); diff --git a/src/factrhs.h b/src/factrhs.h index 134a86e..39d6a82 100644 --- a/src/factrhs.h +++ b/src/factrhs.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/20/14 */ /* */ /* FACT RHS PATTERN PARSER HEADER MODULE */ /*******************************************************/ @@ -16,6 +16,13 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ /*************************************************************/ #ifndef _H_factrhs @@ -44,11 +51,11 @@ #define LOCALE extern #endif - LOCALE struct expr *BuildRHSAssert(void *,char *,struct token *,int *,int,int,char *); - LOCALE struct expr *GetAssertArgument(void *,char *,struct token *,int *,int,int,int *); - LOCALE struct expr *GetRHSPattern(void *,char *,struct token *,int *,int, + LOCALE struct expr *BuildRHSAssert(void *,const char *,struct token *,int *,int,int,const char *); + LOCALE struct expr *GetAssertArgument(void *,const char *,struct token *,int *,int,int,int *); + LOCALE struct expr *GetRHSPattern(void *,const char *,struct token *,int *,int, int,int,int); - LOCALE struct fact *StringToFact(void *,char *); + LOCALE struct fact *StringToFact(void *,const char *); -#endif +#endif /* _H_factrhs */ diff --git a/src/filecom.c b/src/filecom.c index ca7fe9d..bc6b47b 100644 --- a/src/filecom.c +++ b/src/filecom.c @@ -1,8 +1,7 @@ - /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* FILE COMMANDS MODULE */ /*******************************************************/ @@ -14,7 +13,7 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Bebe Ly */ @@ -26,6 +25,25 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added code for capturing errors/warnings. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ #define _FILECOM_SOURCE_ @@ -65,7 +83,9 @@ struct batchEntry { int batchType; void *inputSource; - char *theString; + const char *theString; + const char *fileName; + long lineNumber; struct batchEntry *next; }; @@ -81,21 +101,22 @@ struct batchEntry #define FILECOM_DATA 14 struct fileCommandData - { + { #if DEBUGGING_FUNCTIONS FILE *DribbleFP; char *DribbleBuffer; - int DribbleCurrentPosition; - unsigned DribbleMaximumPosition; + size_t DribbleCurrentPosition; + size_t DribbleMaximumPosition; int (*DribbleStatusFunction)(void *,int); #endif int BatchType; void *BatchSource; char *BatchBuffer; - int BatchCurrentPosition; - unsigned BatchMaximumPosition; + size_t BatchCurrentPosition; + size_t BatchMaximumPosition; struct batchEntry *TopOfBatchList; struct batchEntry *BottomOfBatchList; + char *batchPriorParsingFile; }; #define FileCommandData(theEnv) ((struct fileCommandData *) GetEnvironmentData(theEnv,FILECOM_DATA)) @@ -105,18 +126,18 @@ struct fileCommandData /***************************************/ #if DEBUGGING_FUNCTIONS - static int FindDribble(void *,char *); - static int GetcDribble(void *,char *); - static int UngetcDribble(void *,int,char *); + static int FindDribble(void *,const char *); + static int GetcDribble(void *,const char *); + static int UngetcDribble(void *,int,const char *); static int ExitDribble(void *,int); - static int PrintDribble(void *,char *,char *); + static int PrintDribble(void *,const char *,const char *); static void PutcDribbleBuffer(void *,int); #endif - static int FindBatch(void *,char *); - static int GetcBatch(void *,char *); - static int UngetcBatch(void *,int,char *); + static int FindBatch(void *,const char *); + static int GetcBatch(void *,const char *); + static int UngetcBatch(void *,int,const char *); static int ExitBatch(void *,int); - static void AddBatch(void *,int,void *,int,char *); + static void AddBatch(void *,int,void *,int,const char *,const char *); static void DeallocateFileCommandData(void *); /***************************************/ @@ -139,16 +160,16 @@ globle void FileCommandDefinitions( EnvDefineFunction2(theEnv,"load",'b',PTIEF LoadCommand,"LoadCommand","11k"); EnvDefineFunction2(theEnv,"load*",'b',PTIEF LoadStarCommand,"LoadStarCommand","11k"); #if BLOAD_AND_BSAVE - InitializeBsaveData(theEnv); EnvDefineFunction2(theEnv,"bsave",'b', PTIEF BsaveCommand,"BsaveCommand","11k"); #endif #if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE + InitializeBsaveData(theEnv); InitializeBloadData(theEnv); EnvDefineFunction2(theEnv,"bload",'b',PTIEF BloadCommand,"BloadCommand","11k"); #endif #endif } - + /******************************************************/ /* DeallocateFileCommandData: Deallocates environment */ /* data for file commands. */ @@ -157,7 +178,7 @@ static void DeallocateFileCommandData( void *theEnv) { struct batchEntry *theEntry, *nextEntry; - + theEntry = FileCommandData(theEnv)->TopOfBatchList; while (theEntry != NULL) { @@ -166,42 +187,42 @@ static void DeallocateFileCommandData( if (theEntry->batchType == FILE_BATCH) { GenClose(theEnv,(FILE *) FileCommandData(theEnv)->TopOfBatchList->inputSource); } else - { rm(theEnv,theEntry->theString,strlen(theEntry->theString) + 1); } + { rm(theEnv,(void *) theEntry->theString,strlen(theEntry->theString) + 1); } rtn_struct(theEnv,batchEntry,theEntry); - + theEntry = nextEntry; } - + if (FileCommandData(theEnv)->BatchBuffer != NULL) { rm(theEnv,FileCommandData(theEnv)->BatchBuffer,FileCommandData(theEnv)->BatchMaximumPosition); } + DeleteString(theEnv,FileCommandData(theEnv)->batchPriorParsingFile); + FileCommandData(theEnv)->batchPriorParsingFile = NULL; + #if DEBUGGING_FUNCTIONS if (FileCommandData(theEnv)->DribbleBuffer != NULL) { rm(theEnv,FileCommandData(theEnv)->DribbleBuffer,FileCommandData(theEnv)->DribbleMaximumPosition); } - - if (FileCommandData(theEnv)->DribbleFP != NULL) + + if (FileCommandData(theEnv)->DribbleFP != NULL) { GenClose(theEnv,FileCommandData(theEnv)->DribbleFP); } #endif } - + #if DEBUGGING_FUNCTIONS /*****************************************************/ /* FindDribble: Find routine for the dribble router. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int FindDribble( void *theEnv, - char *logicalName) + const char *logicalName) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif - if ( (strcmp(logicalName,"stdout") == 0) || - (strcmp(logicalName,"stdin") == 0) || + if ( (strcmp(logicalName,STDOUT) == 0) || + (strcmp(logicalName,STDIN) == 0) || (strcmp(logicalName,WPROMPT) == 0) || (strcmp(logicalName,WTRACE) == 0) || (strcmp(logicalName,WERROR) == 0) || @@ -218,8 +239,8 @@ static int FindDribble( /*******************************************************/ static int PrintDribble( void *theEnv, - char *logicalName, - char *str) + const char *logicalName, + const char *str) { int i; @@ -246,7 +267,7 @@ static int PrintDribble( /*****************************************************/ static int GetcDribble( void *theEnv, - char *logicalName) + const char *logicalName) { int rv; @@ -300,13 +321,12 @@ static void PutcDribbleBuffer( /* just received doesn't need to be placed in the dribble */ /* buffer--It can be written directly to the file. This will */ /* occur for example when the command prompt is being */ - /* printed (the CommandBufferInputCount variable will be -1 */ - /* because command input has not been receivied yet). Before */ - /* writing the character to the file, the dribble buffer is */ - /* flushed. */ + /* printed (the AwaitingInput variable will be FALSE because */ + /* command input has not been receivied yet). Before writing */ + /* the character to the file, the dribble buffer is flushed. */ /*===========================================================*/ - else if (RouterData(theEnv)->CommandBufferInputCount < 0) + else if (RouterData(theEnv)->AwaitingInput == FALSE) { if (FileCommandData(theEnv)->DribbleCurrentPosition > 0) { @@ -337,7 +357,7 @@ static void PutcDribbleBuffer( static int UngetcDribble( void *theEnv, int ch, - char *logicalName) + const char *logicalName) { int rv; @@ -367,20 +387,17 @@ static int UngetcDribble( /*****************************************************/ /* ExitDribble: Exit routine for the dribble router. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int ExitDribble( void *theEnv, int num) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(num) #endif if (FileCommandData(theEnv)->DribbleCurrentPosition > 0) { fprintf(FileCommandData(theEnv)->DribbleFP,"%s",FileCommandData(theEnv)->DribbleBuffer); } - + if (FileCommandData(theEnv)->DribbleFP != NULL) GenClose(theEnv,FileCommandData(theEnv)->DribbleFP); return(1); } @@ -392,7 +409,7 @@ static int ExitDribble( globle int DribbleOnCommand( void *theEnv) { - char *fileName; + const char *fileName; if (EnvArgCountCheck(theEnv,"dribble-on",EXACTLY,1) == -1) return(FALSE); if ((fileName = GetFileName(theEnv,"dribble-on",1)) == NULL) return(FALSE); @@ -406,7 +423,7 @@ globle int DribbleOnCommand( /**********************************/ globle intBool EnvDribbleOn( void *theEnv, - char *fileName) + const char *fileName) { /*==============================*/ /* If a dribble file is already */ @@ -549,23 +566,21 @@ globle void SetDribbleStatusFunction( { FileCommandData(theEnv)->DribbleStatusFunction = fnptr; } -#endif + +#endif /* DEBUGGING_FUNCTIONS */ /*************************************************/ /* FindBatch: Find routine for the batch router. */ /*************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int FindBatch( void *theEnv, - char *logicalName) + const char *logicalName) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif - if (strcmp(logicalName,"stdin") == 0) + if (strcmp(logicalName,STDIN) == 0) { return(TRUE); } return(FALSE); @@ -576,7 +591,7 @@ static int FindBatch( /*************************************************/ static int GetcBatch( void *theEnv, - char *logicalName) + const char *logicalName) { return(LLGetcBatch(theEnv,logicalName,FALSE)); } @@ -587,7 +602,7 @@ static int GetcBatch( /***************************************************/ globle int LLGetcBatch( void *theEnv, - char *logicalName, + const char *logicalName, int returnOnEOF) { int rv = EOF, flag = 1; @@ -600,13 +615,13 @@ globle int LLGetcBatch( while ((rv == EOF) && (flag == 1)) { if (FileCommandData(theEnv)->BatchType == FILE_BATCH) - { rv = getc((FILE *) FileCommandData(theEnv)->BatchSource); } + { rv = getc((FILE *) FileCommandData(theEnv)->BatchSource); } else { rv = EnvGetcRouter(theEnv,(char *) FileCommandData(theEnv)->BatchSource); } if (rv == EOF) { - if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,"stdout",(char *) FileCommandData(theEnv)->BatchBuffer); + if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer); flag = RemoveBatch(theEnv); } } @@ -619,7 +634,7 @@ globle int LLGetcBatch( if (rv == EOF) { - if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,"stdout",(char *) FileCommandData(theEnv)->BatchBuffer); + if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer); EnvDeleteRouter(theEnv,"batch"); RemoveBatch(theEnv); if (returnOnEOF == TRUE) @@ -642,7 +657,7 @@ globle int LLGetcBatch( if ((char) rv == '\n') { - EnvPrintRouter(theEnv,"stdout",(char *) FileCommandData(theEnv)->BatchBuffer); + EnvPrintRouter(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer); FileCommandData(theEnv)->BatchCurrentPosition = 0; if ((FileCommandData(theEnv)->BatchBuffer != NULL) && (FileCommandData(theEnv)->BatchMaximumPosition > BUFFER_SIZE)) { @@ -652,6 +667,13 @@ globle int LLGetcBatch( } } + /*=============================*/ + /* Increment the line counter. */ + /*=============================*/ + + if (((char) rv == '\r') || ((char) rv == '\n')) + { IncrementLineCount(theEnv); } + /*=====================================================*/ /* Return the character retrieved from the batch file. */ /*=====================================================*/ @@ -662,15 +684,12 @@ globle int LLGetcBatch( /*****************************************************/ /* UngetcBatch: Ungetc routine for the batch router. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int UngetcBatch( void *theEnv, int ch, - char *logicalName) + const char *logicalName) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(logicalName) #endif @@ -685,14 +704,11 @@ static int UngetcBatch( /*************************************************/ /* ExitBatch: Exit routine for the batch router. */ /*************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int ExitBatch( void *theEnv, int num) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(num) #endif CloseAllBatchSources(theEnv); @@ -706,7 +722,7 @@ static int ExitBatch( globle int BatchCommand( void *theEnv) { - char *fileName; + const char *fileName; if (EnvArgCountCheck(theEnv,"batch",EXACTLY,1) == -1) return(FALSE); if ((fileName = GetFileName(theEnv,"batch",1)) == NULL) return(FALSE); @@ -719,7 +735,7 @@ globle int BatchCommand( /**************************************************/ globle int Batch( void *theEnv, - char *fileName) + const char *fileName) { return(OpenBatch(theEnv,fileName,FALSE)); } /***********************************************/ @@ -728,7 +744,7 @@ globle int Batch( /***********************************************/ globle int OpenBatch( void *theEnv, - char *fileName, + const char *fileName, int placeAtEnd) { FILE *theFile; @@ -758,12 +774,38 @@ globle int OpenBatch( ExitBatch); } + /*===============================================================*/ + /* If a batch file is already open, save its current line count. */ + /*===============================================================*/ + + if (FileCommandData(theEnv)->TopOfBatchList != NULL) + { FileCommandData(theEnv)->TopOfBatchList->lineNumber = GetLineCount(theEnv); } + +#if (! RUN_TIME) && (! BLOAD_ONLY) + + /*========================================================================*/ + /* If this is the first batch file, remember the prior parsing file name. */ + /*========================================================================*/ + + if (FileCommandData(theEnv)->TopOfBatchList == NULL) + { FileCommandData(theEnv)->batchPriorParsingFile = CopyString(theEnv,EnvGetParsingFileName(theEnv)); } + + /*=======================================================*/ + /* Create the error capture router if it does not exist. */ + /*=======================================================*/ + + EnvSetParsingFileName(theEnv,fileName); + SetLineCount(theEnv,0); + + CreateErrorCaptureRouter(theEnv); +#endif + /*====================================*/ /* Add the newly opened batch file to */ /* the list of batch files opened. */ /*====================================*/ - AddBatch(theEnv,placeAtEnd,(void *) theFile,FILE_BATCH,NULL); + AddBatch(theEnv,placeAtEnd,(void *) theFile,FILE_BATCH,NULL,fileName); /*===================================*/ /* Return TRUE to indicate the batch */ @@ -782,8 +824,8 @@ globle int OpenBatch( /*****************************************************************/ globle int OpenStringBatch( void *theEnv, - char *stringName, - char *theString, + const char *stringName, + const char *theString, int placeAtEnd) { if (OpenStringSource(theEnv,stringName,theString,0) == 0) @@ -797,7 +839,7 @@ globle int OpenStringBatch( ExitBatch); } - AddBatch(theEnv,placeAtEnd,(void *) stringName,STRING_BATCH,theString); + AddBatch(theEnv,placeAtEnd,(void *) stringName,STRING_BATCH,theString,NULL); return(1); } @@ -811,7 +853,8 @@ static void AddBatch( int placeAtEnd, void *theSource, int type, - char *theString) + const char *theString, + const char *theFileName) { struct batchEntry *bptr; @@ -823,6 +866,8 @@ static void AddBatch( bptr->batchType = type; bptr->inputSource = theSource; bptr->theString = theString; + bptr->fileName = CopyString(theEnv,theFileName); + bptr->lineNumber = 0; bptr->next = NULL; /*============================*/ @@ -859,7 +904,7 @@ globle int RemoveBatch( void *theEnv) { struct batchEntry *bptr; - int rv; + int rv, fileBatch = FALSE; if (FileCommandData(theEnv)->TopOfBatchList == NULL) return(FALSE); @@ -868,17 +913,26 @@ globle int RemoveBatch( /*==================================================*/ if (FileCommandData(theEnv)->TopOfBatchList->batchType == FILE_BATCH) - { GenClose(theEnv,(FILE *) FileCommandData(theEnv)->TopOfBatchList->inputSource); } + { + fileBatch = TRUE; + GenClose(theEnv,(FILE *) FileCommandData(theEnv)->TopOfBatchList->inputSource); +#if (! RUN_TIME) && (! BLOAD_ONLY) + FlushParsingMessages(theEnv); + DeleteErrorCaptureRouter(theEnv); +#endif + } else { CloseStringSource(theEnv,(char *) FileCommandData(theEnv)->TopOfBatchList->inputSource); - rm(theEnv,FileCommandData(theEnv)->TopOfBatchList->theString,strlen(FileCommandData(theEnv)->TopOfBatchList->theString) + 1); + rm(theEnv,(void *) FileCommandData(theEnv)->TopOfBatchList->theString, + strlen(FileCommandData(theEnv)->TopOfBatchList->theString) + 1); } /*=================================*/ /* Remove the entry from the list. */ /*=================================*/ + DeleteString(theEnv,(char *) FileCommandData(theEnv)->TopOfBatchList->fileName); bptr = FileCommandData(theEnv)->TopOfBatchList; FileCommandData(theEnv)->TopOfBatchList = FileCommandData(theEnv)->TopOfBatchList->next; @@ -901,6 +955,15 @@ globle int RemoveBatch( FileCommandData(theEnv)->BatchCurrentPosition = 0; FileCommandData(theEnv)->BatchMaximumPosition = 0; rv = 0; + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (fileBatch) + { + EnvSetParsingFileName(theEnv,FileCommandData(theEnv)->batchPriorParsingFile); + DeleteString(theEnv,FileCommandData(theEnv)->batchPriorParsingFile); + FileCommandData(theEnv)->batchPriorParsingFile = NULL; + } +#endif } /*===========================================*/ @@ -913,6 +976,12 @@ globle int RemoveBatch( FileCommandData(theEnv)->BatchSource = FileCommandData(theEnv)->TopOfBatchList->inputSource; FileCommandData(theEnv)->BatchCurrentPosition = 0; rv = 1; +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (FileCommandData(theEnv)->TopOfBatchList->batchType == FILE_BATCH) + { EnvSetParsingFileName(theEnv,FileCommandData(theEnv)->TopOfBatchList->fileName); } + + SetLineCount(theEnv,FileCommandData(theEnv)->TopOfBatchList->lineNumber); +#endif } /*====================================================*/ @@ -940,14 +1009,14 @@ globle intBool BatchActive( /******************************************************/ globle void CloseAllBatchSources( void *theEnv) - { + { /*================================================*/ /* Free the batch buffer if it contains anything. */ /*================================================*/ if (FileCommandData(theEnv)->BatchBuffer != NULL) { - if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,"stdout",(char *) FileCommandData(theEnv)->BatchBuffer); + if (FileCommandData(theEnv)->BatchCurrentPosition > 0) EnvPrintRouter(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer); rm(theEnv,FileCommandData(theEnv)->BatchBuffer,FileCommandData(theEnv)->BatchMaximumPosition); FileCommandData(theEnv)->BatchBuffer = NULL; FileCommandData(theEnv)->BatchCurrentPosition = 0; @@ -975,7 +1044,7 @@ globle void CloseAllBatchSources( globle int BatchStarCommand( void *theEnv) { - char *fileName; + const char *fileName; if (EnvArgCountCheck(theEnv,"batch*",EXACTLY,1) == -1) return(FALSE); if ((fileName = GetFileName(theEnv,"batch*",1)) == NULL) return(FALSE); @@ -990,14 +1059,17 @@ globle int BatchStarCommand( /**********************************************************/ globle int EnvBatchStar( void *theEnv, - char *fileName) + const char *fileName) { int inchar; FILE *theFile; char *theString = NULL; - int position = 0; - unsigned maxChars = 0; - + size_t position = 0; + size_t maxChars = 0; +#if (! RUN_TIME) && (! BLOAD_ONLY) + char *oldParsingFileName; + long oldLineCountValue; +#endif /*======================*/ /* Open the batch file. */ /*======================*/ @@ -1010,6 +1082,19 @@ globle int EnvBatchStar( return(FALSE); } + /*======================================*/ + /* Setup for capturing errors/warnings. */ + /*======================================*/ + +#if (! RUN_TIME) && (! BLOAD_ONLY) + oldParsingFileName = CopyString(theEnv,EnvGetParsingFileName(theEnv)); + EnvSetParsingFileName(theEnv,fileName); + + CreateErrorCaptureRouter(theEnv); + + oldLineCountValue = SetLineCount(theEnv,1); +#endif + /*========================*/ /* Reset the error state. */ /*========================*/ @@ -1034,22 +1119,43 @@ globle int EnvBatchStar( FlushPPBuffer(theEnv); SetHaltExecution(theEnv,FALSE); SetEvaluationError(theEnv,FALSE); - FlushBindList(theEnv); + FlushBindList(theEnv); genfree(theEnv,theString,(unsigned) maxChars); theString = NULL; maxChars = 0; position = 0; - } +#if (! RUN_TIME) && (! BLOAD_ONLY) + FlushParsingMessages(theEnv); +#endif + } + + if ((inchar == '\r') || (inchar == '\n')) + { IncrementLineCount(theEnv); } } if (theString != NULL) { genfree(theEnv,theString,(unsigned) maxChars); } - + /*=======================*/ /* Close the batch file. */ /*=======================*/ GenClose(theEnv,theFile); + + /*========================================*/ + /* Cleanup for capturing errors/warnings. */ + /*========================================*/ + +#if (! RUN_TIME) && (! BLOAD_ONLY) + FlushParsingMessages(theEnv); + DeleteErrorCaptureRouter(theEnv); + + SetLineCount(theEnv,oldLineCountValue); + + EnvSetParsingFileName(theEnv,oldParsingFileName); + DeleteString(theEnv,oldParsingFileName); +#endif + return(TRUE); } @@ -1061,12 +1167,8 @@ globle int EnvBatchStar( /**************************************************/ globle int EnvBatchStar( void *theEnv, - char *fileName) + const char *fileName) { -#if (MAC_MCW || IBM_MCW) && RUN_TIME -#pragma unused(fileName) -#endif - PrintErrorID(theEnv,"FILECOM",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Function batch* does not work in run time modules.\n"); return(FALSE); @@ -1081,7 +1183,7 @@ globle int LoadCommand( void *theEnv) { #if (! BLOAD_ONLY) && (! RUN_TIME) - char *theFileName; + const char *theFileName; int rv; if (EnvArgCountCheck(theEnv,"load",EXACTLY,1) == -1) return(FALSE); @@ -1112,7 +1214,7 @@ globle int LoadStarCommand( void *theEnv) { #if (! BLOAD_ONLY) && (! RUN_TIME) - char *theFileName; + const char *theFileName; int rv; if (EnvArgCountCheck(theEnv,"load*",EXACTLY,1) == -1) return(FALSE); @@ -1140,7 +1242,7 @@ globle int SaveCommand( void *theEnv) { #if (! BLOAD_ONLY) && (! RUN_TIME) - char *theFileName; + const char *theFileName; if (EnvArgCountCheck(theEnv,"save",EXACTLY,1) == -1) return(FALSE); if ((theFileName = GetFileName(theEnv,"save",1)) == NULL) return(FALSE); @@ -1159,5 +1261,38 @@ globle int SaveCommand( } #endif +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + +globle intBool DribbleActive() + { + return EnvDribbleActive(GetCurrentEnvironment()); + } + +globle intBool DribbleOn( + const char *fileName) + { + return EnvDribbleOn(GetCurrentEnvironment(),fileName); + } + +globle intBool DribbleOff() + { + return EnvDribbleOff(GetCurrentEnvironment()); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +globle int BatchStar( + const char *fileName) + { + return EnvBatchStar(GetCurrentEnvironment(),fileName); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ diff --git a/src/filecom.h b/src/filecom.h index 6dc7902..6b10374 100644 --- a/src/filecom.h +++ b/src/filecom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FILE COMMANDS HEADER FILE */ /*******************************************************/ @@ -18,7 +18,26 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added code for capturing errors/warnings. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ /* */ /*************************************************************/ @@ -36,40 +55,37 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DribbleActive(theEnv) EnvDribbleActive(theEnv) -#define DribbleOn(theEnv,a) EnvDribbleOn(theEnv,a) -#define DribbleOff(theEnv) EnvDribbleOff(theEnv) -#define BatchStar(theEnv,a) EnvBatchStar(theEnv,a) -#else -#define DribbleActive() EnvDribbleActive(GetCurrentEnvironment()) -#define DribbleOn(a) EnvDribbleOn(GetCurrentEnvironment(),a) -#define DribbleOff() EnvDribbleOff(GetCurrentEnvironment()) -#define BatchStar(a) EnvBatchStar(GetCurrentEnvironment(),a) -#endif - LOCALE void FileCommandDefinitions(void *); - LOCALE intBool EnvDribbleOn(void *,char *); + LOCALE intBool EnvDribbleOn(void *,const char *); LOCALE intBool EnvDribbleActive(void *); LOCALE intBool EnvDribbleOff(void *); LOCALE void SetDribbleStatusFunction(void *,int (*)(void *,int)); - LOCALE int LLGetcBatch(void *,char *,int); - LOCALE int Batch(void *,char *); - LOCALE int OpenBatch(void *,char *,int); - LOCALE int OpenStringBatch(void *,char *,char *,int); + LOCALE int LLGetcBatch(void *,const char *,int); + LOCALE int Batch(void *,const char *); + LOCALE int OpenBatch(void *,const char *,int); + LOCALE int OpenStringBatch(void *,const char *,const char *,int); LOCALE int RemoveBatch(void *); LOCALE intBool BatchActive(void *); LOCALE void CloseAllBatchSources(void *); LOCALE int BatchCommand(void *); LOCALE int BatchStarCommand(void *); - LOCALE int EnvBatchStar(void *,char *); + LOCALE int EnvBatchStar(void *,const char *); LOCALE int LoadCommand(void *); LOCALE int LoadStarCommand(void *); LOCALE int SaveCommand(void *); LOCALE int DribbleOnCommand(void *); LOCALE int DribbleOffCommand(void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool DribbleActive(void); + LOCALE intBool DribbleOn(const char *); + LOCALE intBool DribbleOff(void); + LOCALE int BatchStar(const char *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_filecom */ diff --git a/src/filertr.c b/src/filertr.c index 0ff2965..2112d73 100644 --- a/src/filertr.c +++ b/src/filertr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* FILE I/O ROUTER MODULE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -23,6 +23,23 @@ /* */ /* Added pragmas to remove compilation warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Used gengetc and genungetchar rather than */ +/* getc and ungetc. */ +/* */ +/* Replaced BASIC_IO and ADVANCED_IO compiler */ +/* flags with the single IO_FUNCTIONS compiler */ +/* flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ #define _FILERTR_SOURCE_ @@ -46,9 +63,9 @@ /***************************************/ static int ExitFile(void *,int); - static int PrintFile(void *,char *,char *); - static int GetcFile(void *,char *); - static int UngetcFile(void *,int,char *); + static int PrintFile(void *,const char *,const char *); + static int GetcFile(void *,const char *); + static int UngetcFile(void *,int,const char *); static void DeallocateFileRouterData(void *); /***************************************************************/ @@ -78,6 +95,7 @@ static void DeallocateFileRouterData( { nextPtr = tmpPtr->next; GenClose(theEnv,tmpPtr->stream); + rm(theEnv,(void *) tmpPtr->logicalName,strlen(tmpPtr->logicalName) + 1); rtn_struct(theEnv,fileRouter,tmpPtr); tmpPtr = nextPtr; } @@ -89,7 +107,7 @@ static void DeallocateFileRouterData( /*****************************************/ globle FILE *FindFptr( void *theEnv, - char *logicalName) + const char *logicalName) { struct fileRouter *fptr; @@ -97,9 +115,9 @@ globle FILE *FindFptr( /* Check to see if standard input or output is requested. */ /*========================================================*/ - if (strcmp(logicalName,"stdout") == 0) + if (strcmp(logicalName,STDOUT) == 0) { return(stdout); } - else if (strcmp(logicalName,"stdin") == 0) + else if (strcmp(logicalName,STDIN) == 0) { return(stdin); } else if (strcmp(logicalName,WTRACE) == 0) { return(stdout); } @@ -136,7 +154,7 @@ globle FILE *FindFptr( /*****************************************************/ globle int FindFile( void *theEnv, - char *logicalName) + const char *logicalName) { if (FindFptr(theEnv,logicalName) != NULL) return(TRUE); @@ -146,20 +164,17 @@ globle int FindFile( /********************************************/ /* ExitFile: Exit routine for file router. */ /********************************************/ -#if IBM_TBC -#pragma argsused -#endif static int ExitFile( void *theEnv, int num) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(num) #endif -#if BASIC_IO +#if IO_FUNCTIONS CloseAllFiles(theEnv); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -171,14 +186,15 @@ static int ExitFile( /*********************************************/ static int PrintFile( void *theEnv, - char *logicalName, - char *str) + const char *logicalName, + const char *str) { FILE *fptr; fptr = FindFptr(theEnv,logicalName); - fprintf(fptr,"%s",str); - fflush(fptr); + + genprintfile(theEnv,fptr,str); + return(1); } @@ -187,14 +203,17 @@ static int PrintFile( /*******************************************/ static int GetcFile( void *theEnv, - char *logicalName) + const char *logicalName) { FILE *fptr; int theChar; fptr = FindFptr(theEnv,logicalName); - theChar = getc(fptr); + if (fptr == stdin) + { theChar = gengetchar(theEnv); } + else + { theChar = getc(fptr); } /*=================================================*/ /* The following code prevents Control-D on UNIX */ @@ -212,12 +231,16 @@ static int GetcFile( static int UngetcFile( void *theEnv, int ch, - char *logicalName) + const char *logicalName) { FILE *fptr; fptr = FindFptr(theEnv,logicalName); - return(ungetc(ch,fptr)); + + if (fptr == stdin) + { return(genungetchar(theEnv,ch)); } + else + { return(ungetc(ch,fptr)); } } /*********************************************************/ @@ -228,12 +251,13 @@ static int UngetcFile( /*********************************************************/ globle int OpenAFile( void *theEnv, - char *fileName, - char *accessMode, - char *logicalName) + const char *fileName, + const char *accessMode, + const char *logicalName) { FILE *newstream; struct fileRouter *newRouter; + char *theName; /*==================================*/ /* Make sure the file can be opened */ @@ -248,8 +272,9 @@ globle int OpenAFile( /*===========================*/ newRouter = get_struct(theEnv,fileRouter); - newRouter->logicalName = (char *) gm2(theEnv,strlen(logicalName) + 1); - strcpy(newRouter->logicalName,logicalName); + theName = (char *) gm2(theEnv,strlen(logicalName) + 1); + genstrcpy(theName,logicalName); + newRouter->logicalName = theName; newRouter->stream = newstream; /*==========================================*/ @@ -275,7 +300,7 @@ globle int OpenAFile( /*************************************************************/ globle int CloseFile( void *theEnv, - char *fid) + const char *fid) { struct fileRouter *fptr, *prev; @@ -286,7 +311,7 @@ globle int CloseFile( if (strcmp(fptr->logicalName,fid) == 0) { GenClose(theEnv,fptr->stream); - rm(theEnv,fptr->logicalName,strlen(fptr->logicalName) + 1); + rm(theEnv,(void *) fptr->logicalName,strlen(fptr->logicalName) + 1); if (prev == NULL) { FileRouterData(theEnv)->ListOfFileRouters = fptr->next; } else @@ -320,7 +345,7 @@ globle int CloseAllFiles( { GenClose(theEnv,fptr->stream); prev = fptr; - rm(theEnv,fptr->logicalName,strlen(fptr->logicalName) + 1); + rm(theEnv,(void *) fptr->logicalName,strlen(fptr->logicalName) + 1); fptr = fptr->next; rm(theEnv,prev,(int) sizeof(struct fileRouter)); } diff --git a/src/filertr.h b/src/filertr.h index 9b03138..eb56031 100644 --- a/src/filertr.h +++ b/src/filertr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* FILE I/O ROUTER HEADER FILE */ /*******************************************************/ @@ -17,6 +17,25 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Added pragmas to remove compilation warnings. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Used gengetc and genungetchar rather than */ +/* getc and ungetc. */ +/* */ +/* Replaced BASIC_IO and ADVANCED_IO compiler */ +/* flags with the single IO_FUNCTIONS compiler */ +/* flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_filertr @@ -28,16 +47,16 @@ #endif #define FILE_ROUTER_DATA 47 - + struct fileRouter { - char *logicalName; + const char *logicalName; FILE *stream; struct fileRouter *next; }; struct fileRouterData - { + { struct fileRouter *ListOfFileRouters; }; @@ -54,13 +73,13 @@ struct fileRouterData #endif LOCALE void InitializeFileRouter(void *); - LOCALE FILE *FindFptr(void *,char *); - LOCALE int OpenAFile(void *,char *,char *,char *); + LOCALE FILE *FindFptr(void *,const char *); + LOCALE int OpenAFile(void *,const char *,const char *,const char *); LOCALE int CloseAllFiles(void *); - LOCALE int CloseFile(void *,char *); - LOCALE int FindFile(void *,char *); + LOCALE int CloseFile(void *,const char *); + LOCALE int FindFile(void *,const char *); -#endif +#endif /* _H_filertr */ diff --git a/src/generate.c b/src/generate.c index fba98b7..ddc039f 100644 --- a/src/generate.c +++ b/src/generate.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* GENERATE MODULE */ /*******************************************************/ @@ -18,6 +18,14 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Reimplemented algorithm for comparisons to */ +/* variables contained within not/and CEs. */ +/* */ /*************************************************************/ #define _GENERATE_SOURCE_ @@ -51,18 +59,20 @@ /***************************************/ static void ExtractAnds(void *,struct lhsParseNode *,int, - struct expr **,struct expr **); + struct expr **,struct expr **,struct expr **, + struct expr **,struct nandFrame *); static void ExtractFieldTest(void *,struct lhsParseNode *,int, - struct expr **,struct expr **); + struct expr **,struct expr **,struct expr **, + struct expr **,struct nandFrame *); static struct expr *GetfieldReplace(void *,struct lhsParseNode *); static struct expr *GenPNConstant(void *,struct lhsParseNode *); - static struct expr *GenJNConstant(void *,struct lhsParseNode *); - static struct expr *GenJNColon(void *,struct lhsParseNode *); + static struct expr *GenJNConstant(void *,struct lhsParseNode *,int); + static struct expr *GenJNColon(void *,struct lhsParseNode *,int,struct nandFrame *); static struct expr *GenPNColon(void *,struct lhsParseNode *); - static struct expr *GenJNEq(void *,struct lhsParseNode *); + static struct expr *GenJNEq(void *,struct lhsParseNode *,int,struct nandFrame *); static struct expr *GenPNEq(void *,struct lhsParseNode *); static struct expr *GenJNVariableComparison(void *,struct lhsParseNode *, - struct lhsParseNode *); + struct lhsParseNode *,int); static struct expr *GenPNVariableComparison(void *,struct lhsParseNode *, struct lhsParseNode *); static int AllVariablesInPattern(struct lhsParseNode *, @@ -77,7 +87,8 @@ globle void FieldConversion( void *theEnv, struct lhsParseNode *theField, - struct lhsParseNode *thePattern) + struct lhsParseNode *thePattern, + struct nandFrame *theNandFrames) { int testInPatternNetwork = TRUE; struct lhsParseNode *patternPtr; @@ -86,6 +97,8 @@ globle void FieldConversion( struct expr *tempExpression; struct expr *patternNetTest = NULL; struct expr *joinNetTest = NULL; + struct expr *constantSelector = NULL; + struct expr *constantValue = NULL; /*==================================================*/ /* Consider a NULL pointer to be an internal error. */ @@ -128,7 +141,33 @@ globle void FieldConversion( /* the or'ed constraint being examined. */ /*=============================================*/ - ExtractAnds(theEnv,patternPtr,testInPatternNetwork,&patternNetTest,&joinNetTest); + ExtractAnds(theEnv,patternPtr,testInPatternNetwork,&patternNetTest,&joinNetTest, + &constantSelector,&constantValue,theNandFrames); + + /*=============================================================*/ + /* Constant hashing is only used in the pattern network if the */ + /* field doesn't contain an or'ed constraint. For example, the */ + /* constaint "red | blue" can not use hashing. */ + /*=============================================================*/ + + if (constantSelector != NULL) + { + if ((patternPtr == theField->bottom) && + (patternPtr->bottom == NULL)) + { + theField->constantSelector = constantSelector; + theField->constantValue = constantValue; + } + else + { + ReturnExpression(theEnv,constantSelector); + ReturnExpression(theEnv,constantValue); + ReturnExpression(theEnv,theField->constantSelector); + ReturnExpression(theEnv,theField->constantValue); + theField->constantSelector = NULL; + theField->constantValue = NULL; + } + } /*=====================================================*/ /* Add the new pattern network expressions to the list */ @@ -213,8 +252,31 @@ globle void FieldConversion( else if (theField->referringNode->pattern > 0) { - tempExpression = GenJNVariableComparison(theEnv,theField,theField->referringNode); + AddNandUnification(theEnv,theField,theNandFrames); + + /*====================================*/ + /* Generate an expression to test the */ + /* variable in a non-nand join. */ + /*====================================*/ + + tempExpression = GenJNVariableComparison(theEnv,theField,theField->referringNode,FALSE); headOfJNExpression = CombineExpressions(theEnv,tempExpression,headOfJNExpression); + + /*==========================*/ + /* Generate the hash index. */ + /*==========================*/ + + if (theField->patternType->genGetPNValueFunction != NULL) + { + tempExpression = (*theField->patternType->genGetPNValueFunction)(theEnv,theField); + thePattern->rightHash = AppendExpressions(tempExpression,thePattern->rightHash); + } + + if (theField->referringNode->patternType->genGetJNValueFunction) + { + tempExpression = (*theField->referringNode->patternType->genGetJNValueFunction)(theEnv,theField->referringNode,LHS); + thePattern->leftHash = AppendExpressions(tempExpression,thePattern->leftHash); + } } } @@ -241,9 +303,12 @@ static void ExtractAnds( struct lhsParseNode *andField, int testInPatternNetwork, struct expr **patternNetTest, - struct expr **joinNetTest) + struct expr **joinNetTest, + struct expr **constantSelector, + struct expr **constantValue, + struct nandFrame *theNandFrames) { - struct expr *newPNTest, *newJNTest; + struct expr *newPNTest, *newJNTest, *newConstantSelector, *newConstantValue; /*=================================================*/ /* Before starting, the subfield has no pattern or */ @@ -252,6 +317,8 @@ static void ExtractAnds( *patternNetTest = NULL; *joinNetTest = NULL; + *constantSelector = NULL; + *constantValue = NULL; /*=========================================*/ /* Loop through each of the subfields tied */ @@ -267,7 +334,8 @@ static void ExtractAnds( /* expressions from the subfield. */ /*======================================*/ - ExtractFieldTest(theEnv,andField,testInPatternNetwork,&newPNTest,&newJNTest); + ExtractFieldTest(theEnv,andField,testInPatternNetwork,&newPNTest,&newJNTest, + &newConstantSelector,&newConstantValue,theNandFrames); /*=================================================*/ /* Add the new expressions to the list of pattern */ @@ -276,6 +344,8 @@ static void ExtractAnds( *patternNetTest = CombineExpressions(theEnv,*patternNetTest,newPNTest); *joinNetTest = CombineExpressions(theEnv,*joinNetTest,newJNTest); + *constantSelector = CombineExpressions(theEnv,*constantSelector,newConstantSelector); + *constantValue = CombineExpressions(theEnv,*constantValue,newConstantValue); } } @@ -300,10 +370,15 @@ static void ExtractFieldTest( struct lhsParseNode *theField, int testInPatternNetwork, struct expr **patternNetTest, - struct expr **joinNetTest) + struct expr **joinNetTest, + struct expr **constantSelector, + struct expr **constantValue, + struct nandFrame *theNandFrames) { *patternNetTest = NULL; *joinNetTest = NULL; + *constantSelector = NULL; + *constantValue = NULL; /*==========================================================*/ /* Generate a network expression for a constant constraint. */ @@ -316,9 +391,17 @@ static void ExtractFieldTest( (theField->type == FLOAT) || (theField->type == INTEGER)) { if (testInPatternNetwork == TRUE) - { *patternNetTest = GenPNConstant(theEnv,theField); } + { + *patternNetTest = GenPNConstant(theEnv,theField); + + if (! theField->negated) + { + *constantSelector = (*theField->patternType->genGetPNValueFunction)(theEnv,theField); + *constantValue = GenConstant(theEnv,theField->type,theField->value); + } + } else - { *joinNetTest = GenJNConstant(theEnv,theField); } + { *joinNetTest = GenJNConstant(theEnv,theField,FALSE); } // TBD Remove FALSE } /*===========================================================*/ @@ -331,7 +414,7 @@ static void ExtractFieldTest( (AllVariablesInExpression(theField->expression,theField->pattern) == TRUE)) { *patternNetTest = GenPNColon(theEnv,theField); } else - { *joinNetTest = GenJNColon(theEnv,theField); } + { *joinNetTest = GenJNColon(theEnv,theField,FALSE,theNandFrames); } // TBD Remove FALSE } /*==============================================================*/ @@ -344,7 +427,7 @@ static void ExtractFieldTest( (AllVariablesInExpression(theField->expression,theField->pattern) == TRUE)) { *patternNetTest = GenPNEq(theEnv,theField); } else - { *joinNetTest = GenJNEq(theEnv,theField); } + { *joinNetTest = GenJNEq(theEnv,theField,FALSE,theNandFrames); } // TBD Remove FALSE } /*=====================================================================*/ @@ -359,7 +442,10 @@ static void ExtractFieldTest( FALSE)) { *patternNetTest = GenPNVariableComparison(theEnv,theField,theField->referringNode); } else - { *joinNetTest = GenJNVariableComparison(theEnv,theField,theField->referringNode); } + { + *joinNetTest = GenJNVariableComparison(theEnv,theField,theField->referringNode,FALSE); + AddNandUnification(theEnv,theField,theNandFrames); + } } } @@ -411,7 +497,8 @@ static struct expr *GenPNConstant( /************************************************************/ static struct expr *GenJNConstant( void *theEnv, - struct lhsParseNode *theField) + struct lhsParseNode *theField, + int isNand) { struct expr *top; @@ -423,7 +510,12 @@ static struct expr *GenJNConstant( /*===============================================*/ if (theField->patternType->genJNConstantFunction != NULL) - { return (*theField->patternType->genJNConstantFunction)(theEnv,theField); } + { + if (isNand) + { return (*theField->patternType->genJNConstantFunction)(theEnv,theField,NESTED_RHS); } + else + { return (*theField->patternType->genJNConstantFunction)(theEnv,theField,RHS); } + } /*===================================================*/ /* Otherwise, generate a test which uses the eq/neq */ @@ -436,7 +528,11 @@ static struct expr *GenJNConstant( else { top = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_EQ); } - top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField); + if (isNand) + { top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField,NESTED_RHS); } + else + { top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField,RHS); } + top->argList->nextArg = GenConstant(theEnv,theField->type,theField->value); return(top); @@ -449,7 +545,9 @@ static struct expr *GenJNConstant( /******************************************************/ static struct expr *GenJNColon( void *theEnv, - struct lhsParseNode *theField) + struct lhsParseNode *theField, + int isNand, + struct nandFrame *theNandFrames) { struct expr *top, *conversion; @@ -458,7 +556,10 @@ static struct expr *GenJNColon( /* the appropriate value from the data entity. */ /*==================================================*/ - conversion = GetvarReplace(theEnv,theField->expression); + if (isNand) + { conversion = GetvarReplace(theEnv,theField->expression,TRUE,theNandFrames); } + else + { conversion = GetvarReplace(theEnv,theField->expression,FALSE,theNandFrames); } /*================================================*/ /* If the predicate constraint is negated by a ~, */ @@ -521,7 +622,9 @@ static struct expr *GenPNColon( /******************************************************/ static struct expr *GenJNEq( void *theEnv, - struct lhsParseNode *theField) + struct lhsParseNode *theField, + int isNand, + struct nandFrame *theNandFrames) { struct expr *top, *conversion; @@ -530,7 +633,10 @@ static struct expr *GenJNEq( /* the appropriate value from the data entity. */ /*==================================================*/ - conversion = GetvarReplace(theEnv,theField->expression); + if (isNand) + { conversion = GetvarReplace(theEnv,theField->expression,TRUE,theNandFrames); } + else + { conversion = GetvarReplace(theEnv,theField->expression,FALSE,theNandFrames); } /*============================================================*/ /* If the return value constraint is negated by a ~, then use */ @@ -544,7 +650,11 @@ static struct expr *GenJNEq( else { top = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_EQ); } - top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField); + if (isNand) + { top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField,NESTED_RHS); } + else + { top->argList = (*theField->patternType->genGetJNValueFunction)(theEnv,theField,RHS); } + top->argList->nextArg = conversion; return(top); @@ -586,15 +696,72 @@ static struct expr *GenPNEq( return(top); } -/******************************************************************/ +/************************************************************************/ +/* AddNandUnification: Adds expressions to the nand joins to unify the */ +/* variable bindings that need to match from the left and right paths */ +/* taken through the join network for not/and CE group. */ +/************************************************************************/ +globle void AddNandUnification( + void *theEnv, + struct lhsParseNode *nodeList, + struct nandFrame *theNandFrames) + { + struct nandFrame *theFrame; + struct expr *tempExpression; + + /*====================================================*/ + /* If the reference is to a prior variable within the */ + /* same nand group, then there's no need to create an */ + /* external network test. */ + /*====================================================*/ + + if (nodeList->beginNandDepth == nodeList->referringNode->beginNandDepth) + { return; } + + /*=========================================*/ + /* Don't generate an external network test */ + /* if one has already been generated. */ + /*=========================================*/ + + if (nodeList->referringNode->marked) + { return; } + + /*======================================================*/ + /* Find the frame to which the test should be attached. */ + /*======================================================*/ + + for (theFrame = theNandFrames; + theFrame != NULL; + theFrame = theFrame->next) + { + if (theFrame->depth >= nodeList->referringNode->beginNandDepth) + { + nodeList->referringNode->marked = TRUE; + + tempExpression = GenJNVariableComparison(theEnv,nodeList->referringNode,nodeList->referringNode,TRUE); + + theFrame->nandCE->externalNetworkTest = CombineExpressions(theEnv,theFrame->nandCE->externalNetworkTest,tempExpression); + + tempExpression = (*nodeList->referringNode->patternType->genGetJNValueFunction)(theEnv,nodeList->referringNode,LHS); + theFrame->nandCE->externalRightHash = AppendExpressions(theFrame->nandCE->externalRightHash,tempExpression); + + tempExpression = (*nodeList->referringNode->patternType->genGetJNValueFunction)(theEnv,nodeList->referringNode,LHS); + theFrame->nandCE->externalLeftHash = AppendExpressions(theFrame->nandCE->externalLeftHash,tempExpression); + } + } + } + +/*******************************************************************/ /* GetvarReplace: Replaces occurences of variables in expressions */ -/* with function calls that will extract the variable's value */ -/* from a partial match (i.e. from information stored in the */ -/* join network or the activation of the rule). */ -/******************************************************************/ +/* with function calls that will extract the variable's value */ +/* from a partial match (i.e. from information stored in the */ +/* join network or the activation of the rule). */ +/*******************************************************************/ globle struct expr *GetvarReplace( void *theEnv, - struct lhsParseNode *nodeList) + struct lhsParseNode *nodeList, + int isNand, + struct nandFrame *theNandFrames) { struct expr *newList; @@ -614,8 +781,8 @@ globle struct expr *GetvarReplace( newList = get_struct(theEnv,expr); newList->type = nodeList->type; newList->value = nodeList->value; - newList->nextArg = GetvarReplace(theEnv,nodeList->right); - newList->argList = GetvarReplace(theEnv,nodeList->bottom); + newList->nextArg = GetvarReplace(theEnv,nodeList->right,isNand,theNandFrames); + newList->argList = GetvarReplace(theEnv,nodeList->bottom,isNand,theNandFrames); /*=========================================================*/ /* If the present node being examined is either a local or */ @@ -625,9 +792,40 @@ globle struct expr *GetvarReplace( if ((nodeList->type == SF_VARIABLE) || (nodeList->type == MF_VARIABLE)) { + AddNandUnification(theEnv,nodeList,theNandFrames); + + /*=============================================================*/ + /* Referencing a variable outside the scope of the immediately */ + /* enclosing not/and CE requires that the test be performed in */ + /* the "join from the right" join. */ + /*=============================================================*/ - (*nodeList->referringNode->patternType->replaceGetJNValueFunction) - (theEnv,newList,nodeList->referringNode); + if (isNand) + { + if (nodeList->beginNandDepth > nodeList->referringNode->beginNandDepth) + { + (*nodeList->referringNode->patternType->replaceGetJNValueFunction) + (theEnv,newList,nodeList->referringNode,LHS); + } + else + { + (*nodeList->referringNode->patternType->replaceGetJNValueFunction) + (theEnv,newList,nodeList->referringNode,NESTED_RHS); + } + } + else + { + if (nodeList->joinDepth != nodeList->referringNode->joinDepth) + { + (*nodeList->referringNode->patternType->replaceGetJNValueFunction) + (theEnv,newList,nodeList->referringNode,LHS); + } + else + { + (*nodeList->referringNode->patternType->replaceGetJNValueFunction) + (theEnv,newList,nodeList->referringNode,RHS); + } + } } #if DEFGLOBAL_CONSTRUCT else if (newList->type == GBL_VARIABLE) @@ -702,7 +900,8 @@ static struct expr *GetfieldReplace( static struct expr *GenJNVariableComparison( void *theEnv, struct lhsParseNode *selfNode, - struct lhsParseNode *referringNode) + struct lhsParseNode *referringNode, + int isNand) { struct expr *top; @@ -725,7 +924,7 @@ static struct expr *GenJNVariableComparison( { return (*selfNode->patternType->genCompareJNValuesFunction)(theEnv,selfNode, - referringNode); + referringNode,isNand); } /*===========================================================*/ @@ -738,8 +937,8 @@ static struct expr *GenJNVariableComparison( if (selfNode->negated) top = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_NEQ); else top = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_EQ); - top->argList = (*selfNode->patternType->genGetJNValueFunction)(theEnv,selfNode); - top->argList->nextArg = (*referringNode->patternType->genGetJNValueFunction)(theEnv,referringNode); + top->argList = (*selfNode->patternType->genGetJNValueFunction)(theEnv,selfNode,RHS); + top->argList->nextArg = (*referringNode->patternType->genGetJNValueFunction)(theEnv,referringNode,LHS); return(top); } diff --git a/src/generate.h b/src/generate.h index cb881ba..9b2cc13 100644 --- a/src/generate.h +++ b/src/generate.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* GENERATE HEADER FILE */ /*******************************************************/ @@ -18,6 +18,14 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Reimplemented algorithm for comparisons to */ +/* variables contained within not/and CEs. */ +/* */ /*************************************************************/ #ifndef _H_generate @@ -30,6 +38,9 @@ #ifndef _H_reorder #include "reorder.h" #endif +#ifndef _H_analysis +#include "analysis.h" +#endif #ifdef LOCALE #undef LOCALE @@ -41,10 +52,11 @@ #define LOCALE extern #endif - LOCALE void FieldConversion(void *,struct lhsParseNode *,struct lhsParseNode *); - LOCALE struct expr *GetvarReplace(void *,struct lhsParseNode *); + LOCALE void FieldConversion(void *,struct lhsParseNode *,struct lhsParseNode *,struct nandFrame *); + LOCALE struct expr *GetvarReplace(void *,struct lhsParseNode *,int,struct nandFrame *); + LOCALE void AddNandUnification(void *,struct lhsParseNode *,struct nandFrame *); -#endif +#endif /* _H_generate */ diff --git a/src/genrcbin.c b/src/genrcbin.c index 38ae9db..feeb6bb 100644 --- a/src/genrcbin.c +++ b/src/genrcbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: Binary Load/Save Functions for Generic Functions */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ /* ========================================= @@ -60,13 +66,13 @@ typedef struct bsaveRestriction { long types,query; - unsigned tcnt; + short tcnt; } BSAVE_RESTRICTION; typedef struct bsaveMethod { - unsigned index; - int restrictionCount, + short index; + short restrictionCount, minRestrictions,maxRestrictions, localVarCount; int system; @@ -77,7 +83,7 @@ typedef struct bsaveGenericFunc { struct bsaveConstructHeader header; long methods; - unsigned mcnt; + short mcnt; } BSAVE_GENERIC; typedef struct bsaveGenericModule @@ -149,7 +155,7 @@ globle void SetupGenericsBload( ClearBloadGenerics); #endif } - + /***********************************************************/ /* DeallocateDefgenericBinaryData: Deallocates environment */ /* data for the defgeneric binary functionality. */ @@ -158,22 +164,22 @@ static void DeallocateDefgenericBinaryData( void *theEnv) { #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) - unsigned long space; + size_t space; space = DefgenericBinaryData(theEnv)->GenericCount * sizeof(struct defgeneric); - if (space != 0) genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->DefgenericArray,space); + if (space != 0) genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->DefgenericArray,space); space = DefgenericBinaryData(theEnv)->MethodCount * sizeof(struct method); - if (space != 0) genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->MethodArray,space); + if (space != 0) genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->MethodArray,space); space = DefgenericBinaryData(theEnv)->RestrictionCount * sizeof(struct restriction); - if (space != 0) genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->RestrictionArray,space); + if (space != 0) genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->RestrictionArray,space); space = DefgenericBinaryData(theEnv)->TypeCount * sizeof(void *); - if (space != 0) genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->TypeArray,space); + if (space != 0) genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->TypeArray,space); space = DefgenericBinaryData(theEnv)->ModuleCount * sizeof(struct defgenericModule); - if (space != 0) genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->ModuleArray,space); #endif } @@ -232,7 +238,7 @@ static void BsaveGenericsFind( DefgenericBinaryData(theEnv)->RestrictionCount = 0L; DefgenericBinaryData(theEnv)->TypeCount = 0L; - DefgenericBinaryData(theEnv)->ModuleCount = + DefgenericBinaryData(theEnv)->ModuleCount = DoForAllConstructs(theEnv,MarkDefgenericItems,DefgenericData(theEnv)->DefgenericModuleIndex, FALSE,NULL); } @@ -247,19 +253,16 @@ static void BsaveGenericsFind( SIDE EFFECTS : Needed items marked NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkDefgenericItems( void *theEnv, struct constructHeader *theDefgeneric, void *userBuffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(userBuffer) #endif DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; - register unsigned i,j; + long i,j; DEFMETHOD *meth; RESTRICTION *rptr; @@ -271,12 +274,12 @@ static void MarkDefgenericItems( ExpressionData(theEnv)->ExpressionCount += ExpressionSize(meth->actions); MarkNeededItems(theEnv,meth->actions); DefgenericBinaryData(theEnv)->RestrictionCount += meth->restrictionCount; - for (j = 0 ; j < (unsigned) meth->restrictionCount ; j++) + for (j = 0 ; j < meth->restrictionCount ; j++) { rptr = &meth->restrictions[j]; ExpressionData(theEnv)->ExpressionCount += ExpressionSize(rptr->query); MarkNeededItems(theEnv,rptr->query); - DefgenericBinaryData(theEnv)->TypeCount += (long) rptr->tcnt; + DefgenericBinaryData(theEnv)->TypeCount += rptr->tcnt; } } } @@ -321,7 +324,7 @@ static void BsaveMethodExpressions( void *userBuffer) { DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; - register unsigned i; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) BsaveExpression(theEnv,gfunc->methods[i].actions,(FILE *) userBuffer); @@ -345,13 +348,13 @@ static void BsaveRestrictionExpressions( void *userBuffer) { DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; - register unsigned i,j; + long i,j; DEFMETHOD *meth; for (i = 0 ; i < gfunc->mcnt ; i++) { meth = &gfunc->methods[i]; - for (j = 0 ; j < (unsigned) meth->restrictionCount ; j++) + for (j = 0 ; j < meth->restrictionCount ; j++) BsaveExpression(theEnv,meth->restrictions[j].query,(FILE *) userBuffer); } } @@ -370,15 +373,15 @@ static void BsaveStorageGenerics( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; space = sizeof(long) * 5; - GenWrite((void *) &space,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefgenericBinaryData(theEnv)->ModuleCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefgenericBinaryData(theEnv)->GenericCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefgenericBinaryData(theEnv)->MethodCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefgenericBinaryData(theEnv)->RestrictionCount,(unsigned long) sizeof(long),fp); - GenWrite((void *) &DefgenericBinaryData(theEnv)->TypeCount,(unsigned long) sizeof(long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); + GenWrite((void *) &DefgenericBinaryData(theEnv)->ModuleCount,sizeof(long),fp); + GenWrite((void *) &DefgenericBinaryData(theEnv)->GenericCount,sizeof(long),fp); + GenWrite((void *) &DefgenericBinaryData(theEnv)->MethodCount,sizeof(long),fp); + GenWrite((void *) &DefgenericBinaryData(theEnv)->RestrictionCount,sizeof(long),fp); + GenWrite((void *) &DefgenericBinaryData(theEnv)->TypeCount,sizeof(long),fp); } /**************************************************************************************** @@ -401,23 +404,23 @@ static void BsaveGenerics( { struct defmodule *theModule; DEFGENERIC_MODULE *theModuleItem; - unsigned long space; + size_t space; BSAVE_DEFGENERIC_MODULE dummy_generic_module; /* ===================================================================== Space is: Sum over all structures(sizeof(structure) * structure-cnt)) ===================================================================== */ - space = ((unsigned long) DefgenericBinaryData(theEnv)->ModuleCount * (unsigned long) sizeof(BSAVE_DEFGENERIC_MODULE)) + - ((unsigned long) DefgenericBinaryData(theEnv)->GenericCount * (unsigned long) sizeof(BSAVE_GENERIC)) + - ((unsigned long) DefgenericBinaryData(theEnv)->MethodCount * (unsigned long) sizeof(BSAVE_METHOD)) + - ((unsigned long) DefgenericBinaryData(theEnv)->RestrictionCount * (unsigned long) sizeof(BSAVE_RESTRICTION)) + - ((unsigned long) DefgenericBinaryData(theEnv)->TypeCount * (unsigned long) sizeof(unsigned long)); + space = ((unsigned long) DefgenericBinaryData(theEnv)->ModuleCount * sizeof(BSAVE_DEFGENERIC_MODULE)) + + ((unsigned long) DefgenericBinaryData(theEnv)->GenericCount * sizeof(BSAVE_GENERIC)) + + ((unsigned long) DefgenericBinaryData(theEnv)->MethodCount * sizeof(BSAVE_METHOD)) + + ((unsigned long) DefgenericBinaryData(theEnv)->RestrictionCount * sizeof(BSAVE_RESTRICTION)) + + ((unsigned long) DefgenericBinaryData(theEnv)->TypeCount * sizeof(unsigned long)); /* ================================================================ Write out the total amount of space required: modules,headers, methods, restrictions, types ================================================================ */ - GenWrite((void *) &space,(unsigned long) sizeof(unsigned long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); /* ====================================== Write out the generic function modules @@ -431,7 +434,7 @@ static void BsaveGenerics( AssignBsaveDefmdlItemHdrVals(&dummy_generic_module.header, &theModuleItem->header); GenWrite((void *) &dummy_generic_module, - (unsigned long) sizeof(BSAVE_DEFGENERIC_MODULE),fp); + sizeof(BSAVE_DEFGENERIC_MODULE),fp); theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule); } @@ -516,7 +519,7 @@ static void BsaveMethods( DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; DEFMETHOD *meth; BSAVE_METHOD dummy_method; - register unsigned i; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) { @@ -541,7 +544,7 @@ static void BsaveMethods( } else dummy_method.actions = -1L; - GenWrite((void *) &dummy_method,(unsigned long) sizeof(BSAVE_METHOD),(FILE *) userBuffer); + GenWrite((void *) &dummy_method,sizeof(BSAVE_METHOD),(FILE *) userBuffer); } } @@ -562,18 +565,18 @@ static void BsaveMethodRestrictions( DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; BSAVE_RESTRICTION dummy_restriction; RESTRICTION *rptr; - register unsigned i,j; + short i,j; for (i = 0 ; i < gfunc->mcnt ; i++) { - for (j = 0 ; j < (unsigned) gfunc->methods[i].restrictionCount ; j++) + for (j = 0 ; j < gfunc->methods[i].restrictionCount ; j++) { rptr = &gfunc->methods[i].restrictions[j]; dummy_restriction.tcnt = rptr->tcnt; if (rptr->types != NULL) { dummy_restriction.types = DefgenericBinaryData(theEnv)->TypeCount; - DefgenericBinaryData(theEnv)->TypeCount += (long) rptr->tcnt; + DefgenericBinaryData(theEnv)->TypeCount += rptr->tcnt; } else dummy_restriction.types = -1L; @@ -585,7 +588,7 @@ static void BsaveMethodRestrictions( else dummy_restriction.query = -1L; GenWrite((void *) &dummy_restriction, - (unsigned long) sizeof(BSAVE_RESTRICTION),(FILE *) userBuffer); + sizeof(BSAVE_RESTRICTION),(FILE *) userBuffer); } } } @@ -599,9 +602,6 @@ static void BsaveMethodRestrictions( SIDE EFFECTS : Defgeneric methods' restrictions' types saved NOTES : None *************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void BsaveRestrictionTypes( void *theEnv, struct constructHeader *theDefgeneric, @@ -610,14 +610,14 @@ static void BsaveRestrictionTypes( DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; long dummy_type; RESTRICTION *rptr; - register unsigned i,j,k; -#if MAC_MCW || IBM_MCW || MAC_XCD + short i,j,k; +#if MAC_XCD #pragma unused(theEnv) #endif for (i = 0 ; i < gfunc->mcnt ; i++) { - for (j = 0 ; j < (unsigned) gfunc->methods[i].restrictionCount ; j++) + for (j = 0 ; j < gfunc->methods[i].restrictionCount ; j++) { rptr = &gfunc->methods[i].restrictions[j]; for (k = 0 ; k < rptr->tcnt ; k++) @@ -627,7 +627,7 @@ static void BsaveRestrictionTypes( #else dummy_type = (long) ((INTEGER_HN *) rptr->types[k])->contents; #endif - GenWrite(&dummy_type,(unsigned long) sizeof(long),(FILE *) userBuffer); + GenWrite(&dummy_type,sizeof(long),(FILE *) userBuffer); } } } @@ -648,10 +648,10 @@ static void BsaveRestrictionTypes( static void BloadStorageGenerics( void *theEnv) { - unsigned long space; + size_t space; long counts[5]; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) return; GenReadBinary(theEnv,(void *) counts,space); @@ -662,36 +662,36 @@ static void BloadStorageGenerics( DefgenericBinaryData(theEnv)->TypeCount = counts[4]; if (DefgenericBinaryData(theEnv)->ModuleCount != 0L) { - space = (unsigned long) (sizeof(DEFGENERIC_MODULE) * DefgenericBinaryData(theEnv)->ModuleCount); - DefgenericBinaryData(theEnv)->ModuleArray = (DEFGENERIC_MODULE *) genlongalloc(theEnv,space); + space = (sizeof(DEFGENERIC_MODULE) * DefgenericBinaryData(theEnv)->ModuleCount); + DefgenericBinaryData(theEnv)->ModuleArray = (DEFGENERIC_MODULE *) genalloc(theEnv,space); } else return; if (DefgenericBinaryData(theEnv)->GenericCount != 0L) { - space = (unsigned long) (sizeof(DEFGENERIC) * DefgenericBinaryData(theEnv)->GenericCount); - DefgenericBinaryData(theEnv)->DefgenericArray = (DEFGENERIC *) genlongalloc(theEnv,space); + space = (sizeof(DEFGENERIC) * DefgenericBinaryData(theEnv)->GenericCount); + DefgenericBinaryData(theEnv)->DefgenericArray = (DEFGENERIC *) genalloc(theEnv,space); } else return; if (DefgenericBinaryData(theEnv)->MethodCount != 0L) { - space = (unsigned long) (sizeof(DEFMETHOD) * DefgenericBinaryData(theEnv)->MethodCount); - DefgenericBinaryData(theEnv)->MethodArray = (DEFMETHOD *) genlongalloc(theEnv,space); + space = (sizeof(DEFMETHOD) * DefgenericBinaryData(theEnv)->MethodCount); + DefgenericBinaryData(theEnv)->MethodArray = (DEFMETHOD *) genalloc(theEnv,space); } else return; if (DefgenericBinaryData(theEnv)->RestrictionCount != 0L) { - space = (unsigned long) (sizeof(RESTRICTION) * DefgenericBinaryData(theEnv)->RestrictionCount); - DefgenericBinaryData(theEnv)->RestrictionArray = (RESTRICTION *) genlongalloc(theEnv,space); + space = (sizeof(RESTRICTION) * DefgenericBinaryData(theEnv)->RestrictionCount); + DefgenericBinaryData(theEnv)->RestrictionArray = (RESTRICTION *) genalloc(theEnv,space); } else return; if (DefgenericBinaryData(theEnv)->TypeCount != 0L) { - space = (unsigned long) (sizeof(void *) * DefgenericBinaryData(theEnv)->TypeCount); - DefgenericBinaryData(theEnv)->TypeArray = (void * *) genlongalloc(theEnv,space); + space = (sizeof(void *) * DefgenericBinaryData(theEnv)->TypeCount); + DefgenericBinaryData(theEnv)->TypeArray = (void * *) genalloc(theEnv,space); } } @@ -714,18 +714,18 @@ static void BloadStorageGenerics( static void BloadGenerics( void *theEnv) { - unsigned long space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(unsigned long) sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (DefgenericBinaryData(theEnv)->ModuleCount == 0L) return; - BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->ModuleCount,(unsigned) sizeof(BSAVE_DEFGENERIC_MODULE),UpdateGenericModule); + BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->ModuleCount,sizeof(BSAVE_DEFGENERIC_MODULE),UpdateGenericModule); if (DefgenericBinaryData(theEnv)->GenericCount == 0L) return; - BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->GenericCount,(unsigned) sizeof(BSAVE_GENERIC),UpdateGeneric); - BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->MethodCount,(unsigned) sizeof(BSAVE_METHOD),UpdateMethod); - BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->RestrictionCount,(unsigned) sizeof(BSAVE_RESTRICTION),UpdateRestriction); - BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->TypeCount,(unsigned) sizeof(long),UpdateType); + BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->GenericCount,sizeof(BSAVE_GENERIC),UpdateGeneric); + BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->MethodCount,sizeof(BSAVE_METHOD),UpdateMethod); + BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->RestrictionCount,sizeof(BSAVE_RESTRICTION),UpdateRestriction); + BloadandRefresh(theEnv,DefgenericBinaryData(theEnv)->TypeCount,sizeof(long),UpdateType); } /********************************************* @@ -816,7 +816,7 @@ static void UpdateType( PrintWarningID(theEnv,"GENRCBIN",1,FALSE); EnvPrintRouter(theEnv,WWARNING,"COOL not installed! User-defined class\n"); EnvPrintRouter(theEnv,WWARNING," in method restriction substituted with OBJECT.\n"); - DefgenericBinaryData(theEnv)->TypeArray[obji] = (void *) EnvAddLong(theEnv,(long) OBJECT_TYPE_CODE); + DefgenericBinaryData(theEnv)->TypeArray[obji] = (void *) EnvAddLong(theEnv,(long long) OBJECT_TYPE_CODE); } else DefgenericBinaryData(theEnv)->TypeArray[obji] = (void *) EnvAddLong(theEnv,* (long *) buf); @@ -838,36 +838,36 @@ static void ClearBloadGenerics( void *theEnv) { register long i; - unsigned long space; + size_t space; - space = (unsigned long) (sizeof(DEFGENERIC_MODULE) * DefgenericBinaryData(theEnv)->ModuleCount); + space = (sizeof(DEFGENERIC_MODULE) * DefgenericBinaryData(theEnv)->ModuleCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->ModuleArray,space); + genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->ModuleArray,space); DefgenericBinaryData(theEnv)->ModuleArray = NULL; DefgenericBinaryData(theEnv)->ModuleCount = 0L; for (i = 0 ; i < DefgenericBinaryData(theEnv)->GenericCount ; i++) UnmarkConstructHeader(theEnv,&DefgenericBinaryData(theEnv)->DefgenericArray[i].header); - space = (unsigned long) (sizeof(DEFGENERIC) * DefgenericBinaryData(theEnv)->GenericCount); + space = (sizeof(DEFGENERIC) * DefgenericBinaryData(theEnv)->GenericCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->DefgenericArray,space); + genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->DefgenericArray,space); DefgenericBinaryData(theEnv)->DefgenericArray = NULL; DefgenericBinaryData(theEnv)->GenericCount = 0L; - space = (unsigned long) (sizeof(DEFMETHOD) * DefgenericBinaryData(theEnv)->MethodCount); + space = (sizeof(DEFMETHOD) * DefgenericBinaryData(theEnv)->MethodCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->MethodArray,space); + genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->MethodArray,space); DefgenericBinaryData(theEnv)->MethodArray = NULL; DefgenericBinaryData(theEnv)->MethodCount = 0L; - space = (unsigned long) (sizeof(RESTRICTION) * DefgenericBinaryData(theEnv)->RestrictionCount); + space = (sizeof(RESTRICTION) * DefgenericBinaryData(theEnv)->RestrictionCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->RestrictionArray,space); + genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->RestrictionArray,space); DefgenericBinaryData(theEnv)->RestrictionArray = NULL; DefgenericBinaryData(theEnv)->RestrictionCount = 0L; @@ -875,10 +875,10 @@ static void ClearBloadGenerics( for (i = 0 ; i < DefgenericBinaryData(theEnv)->TypeCount ; i++) DecrementIntegerCount(theEnv,(INTEGER_HN *) DefgenericBinaryData(theEnv)->TypeArray[i]); #endif - space = (unsigned long) (sizeof(void *) * DefgenericBinaryData(theEnv)->TypeCount); + space = (sizeof(void *) * DefgenericBinaryData(theEnv)->TypeCount); if (space == 0L) return; - genlongfree(theEnv,(void *) DefgenericBinaryData(theEnv)->TypeArray,space); + genfree(theEnv,(void *) DefgenericBinaryData(theEnv)->TypeArray,space); DefgenericBinaryData(theEnv)->TypeArray = NULL; DefgenericBinaryData(theEnv)->TypeCount = 0L; } diff --git a/src/genrcbin.h b/src/genrcbin.h index 3b7a3f7..c445661 100644 --- a/src/genrcbin.h +++ b/src/genrcbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,18 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_genrcbin @@ -26,7 +32,7 @@ #define GENRCBIN_DATA 28 struct defgenericBinaryData - { + { DEFGENERIC *DefgenericArray; long ModuleCount; long GenericCount; @@ -38,7 +44,7 @@ struct defgenericBinaryData RESTRICTION *RestrictionArray; void **TypeArray; }; - + #define DefgenericBinaryData(theEnv) ((struct defgenericBinaryData *) GetEnvironmentData(theEnv,GENRCBIN_DATA)) #define GenericPointer(i) (((i) == -1L) ? NULL : (DEFGENERIC *) &DefgenericBinaryData(theEnv)->DefgenericArray[i]) @@ -53,10 +59,10 @@ struct defgenericBinaryData #define LOCALE extern #endif -LOCALE void SetupGenericsBload(void *); -LOCALE void *BloadDefgenericModuleReference(void *,int); + LOCALE void SetupGenericsBload(void *); + LOCALE void *BloadDefgenericModuleReference(void *,int); -#endif +#endif /* _H_genrcbin */ diff --git a/src/genrccmp.c b/src/genrccmp.c index 25e665c..68130fe 100644 --- a/src/genrccmp.c +++ b/src/genrccmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Generic Function Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,18 @@ /* 6.24: Added pragmas to remove unused parameter */ /* warnings. */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -74,7 +86,7 @@ ***************************************** */ static void ReadyDefgenericsForCode(void *); -static int DefgenericsToCode(void *,char *,int,FILE *,int,int); +static int DefgenericsToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void CloseDefgenericFiles(void *,FILE *[SAVE_ITEMS],int [SAVE_ITEMS], struct CodeGeneratorFile [SAVE_ITEMS],int); static void DefgenericModuleToCode(void *,FILE *,struct defmodule *,int,int); @@ -199,7 +211,9 @@ static void ReadyDefgenericsForCode( *******************************************************/ static int DefgenericsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -210,7 +224,7 @@ static int DefgenericsToCode( DEFGENERIC *theDefgeneric; DEFMETHOD *theMethod; RESTRICTION *theRestriction; - register unsigned i,j,k; + short i,j,k; int moduleCount = 0; int itemArrayCounts[SAVE_ITEMS]; int itemArrayVersions[SAVE_ITEMS]; @@ -225,6 +239,8 @@ static int DefgenericsToCode( itemFiles[i] = NULL; itemReopenFlags[i] = FALSE; itemCodeFiles[i].filePrefix = NULL; + itemCodeFiles[i].pathName = pathName; + itemCodeFiles[i].fileNameBuffer = fileNameBuffer; } /* =========================================== @@ -243,7 +259,7 @@ static int DefgenericsToCode( EnvSetCurrentModule(theEnv,(void *) theModule); itemFiles[MODULEI] = - OpenFileIfNeeded(theEnv,itemFiles[MODULEI],fileName,fileID,imageID,&fileCount, + OpenFileIfNeeded(theEnv,itemFiles[MODULEI],fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, itemArrayVersions[MODULEI],headerFP, "DEFGENERIC_MODULE",ModulePrefix(DefgenericData(theEnv)->DefgenericCodeItem), itemReopenFlags[MODULEI],&itemCodeFiles[MODULEI]); @@ -261,7 +277,7 @@ static int DefgenericsToCode( while (theDefgeneric != NULL) { itemFiles[GENERICI] = - OpenFileIfNeeded(theEnv,itemFiles[GENERICI],fileName,fileID,imageID,&fileCount, + OpenFileIfNeeded(theEnv,itemFiles[GENERICI],fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, itemArrayVersions[GENERICI],headerFP, "DEFGENERIC",ConstructPrefix(DefgenericData(theEnv)->DefgenericCodeItem), itemReopenFlags[GENERICI],&itemCodeFiles[GENERICI]); @@ -284,7 +300,7 @@ static int DefgenericsToCode( generic function go into the same array =========================================== */ itemFiles[METHODI] = - OpenFileIfNeeded(theEnv,itemFiles[METHODI],fileName,fileID,imageID,&fileCount, + OpenFileIfNeeded(theEnv,itemFiles[METHODI],fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, itemArrayVersions[METHODI],headerFP, "DEFMETHOD",MethodPrefix(), itemReopenFlags[METHODI],&itemCodeFiles[METHODI]); @@ -305,14 +321,14 @@ static int DefgenericsToCode( particular method go into the same array ======================================== */ itemFiles[RESTRICTIONI] = - OpenFileIfNeeded(theEnv,itemFiles[RESTRICTIONI],fileName,fileID, + OpenFileIfNeeded(theEnv,itemFiles[RESTRICTIONI],fileName,pathName,fileNameBuffer,fileID, imageID,&fileCount, itemArrayVersions[RESTRICTIONI],headerFP, "RESTRICTION",RestrictionPrefix(), itemReopenFlags[RESTRICTIONI],&itemCodeFiles[RESTRICTIONI]); if (itemFiles[RESTRICTIONI] == NULL) goto GenericCodeError; - for (j = 0 ; j < (unsigned) theMethod->restrictionCount ; j++) + for (j = 0 ; j < theMethod->restrictionCount ; j++) { theRestriction = &theMethod->restrictions[j]; if (j > 0) @@ -327,7 +343,7 @@ static int DefgenericsToCode( restriction go into the same array ========================================= */ itemFiles[TYPEI] = - OpenFileIfNeeded(theEnv,itemFiles[TYPEI],fileName,fileID, + OpenFileIfNeeded(theEnv,itemFiles[TYPEI],fileName,pathName,fileNameBuffer,fileID, imageID,&fileCount, itemArrayVersions[TYPEI],headerFP, "void *",TypePrefix(), @@ -485,7 +501,7 @@ static void SingleDefgenericToCode( fprintf(theFile,"&%s%d_%d[%d]",MethodPrefix(),imageID, methodArrayVersion,methodArrayCount); } - fprintf(theFile,",%u,0}",theDefgeneric->mcnt); + fprintf(theFile,",%hd,0}",theDefgeneric->mcnt); } /**************************************************************** @@ -511,7 +527,7 @@ static void MethodToCode( int restrictionArrayVersion, int restrictionArrayCount) { - fprintf(theFile,"{%u,0,%d,%d,%d,%d,%u,0,", + fprintf(theFile,"{%hd,0,%hd,%hd,%hd,%hd,%u,0,", theMethod->index,theMethod->restrictionCount, theMethod->minRestrictions,theMethod->maxRestrictions, theMethod->localVarCount,theMethod->system); @@ -554,7 +570,7 @@ static void RestrictionToCode( fprintf(theFile,"&%s%d_%d[%d],",TypePrefix(),imageID, typeArrayVersion,typeArrayCount); ExpressionToCode(theEnv,theFile,theRestriction->query); - fprintf(theFile,",%u}",theRestriction->tcnt); + fprintf(theFile,",%hd}",theRestriction->tcnt); } /**************************************************************** @@ -580,7 +596,7 @@ static void TypeToCode( PrintClassReference(theEnv,theFile,(DEFCLASS *) theType,imageID,maxIndices); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(imageID) #pragma unused(maxIndices) #endif diff --git a/src/genrccmp.h b/src/genrccmp.h index 5cf1c17..bb2f34b 100644 --- a/src/genrccmp.h +++ b/src/genrccmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,27 @@ /* Purpose: Generic Function Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.24: Added pragmas to remove unused parameter */ +/* warnings. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_genrccmp @@ -38,9 +53,9 @@ #include "genrcfun.h" -LOCALE void SetupGenericsCompiler(void *); -LOCALE void PrintGenericFunctionReference(void *,FILE *,DEFGENERIC *,int,int); -LOCALE void DefgenericCModuleReference(void *,FILE *,int,int,int); + LOCALE void SetupGenericsCompiler(void *); + LOCALE void PrintGenericFunctionReference(void *,FILE *,DEFGENERIC *,int,int); + LOCALE void DefgenericCModuleReference(void *,FILE *,int,int,int); -#endif +#endif /* _H_genrccmp */ diff --git a/src/genrccom.c b/src/genrccom.c index 6ac6de1..eb0ddb3 100644 --- a/src/genrccom.c +++ b/src/genrccom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Generic Functions Interface Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -31,6 +31,29 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when DEBUGGING_FUNCTIONS */ +/* is set to 0 and PROFILING_FUNCTIONS is set to */ +/* 1. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ /* ========================================= @@ -93,7 +116,7 @@ ========================================= ***************************************** */ -static void PrintGenericCall(void *,char *,void *); +static void PrintGenericCall(void *,const char *,void *); static intBool EvaluateGenericCall(void *,void *,DATA_OBJECT *); static void DecrementGenericBusyCount(void *,void *); static void IncrementGenericBusyCount(void *,void *); @@ -104,24 +127,24 @@ static void DestroyDefgenericAction(void *,struct constructHeader *,void *); #if (! BLOAD_ONLY) && (! RUN_TIME) -static void SaveDefgenerics(void *,void *,char *); -static void SaveDefmethods(void *,void *,char *); +static void SaveDefgenerics(void *,void *,const char *); +static void SaveDefmethods(void *,void *,const char *); static void SaveDefmethodsForDefgeneric(void *,struct constructHeader *,void *); -static void RemoveDefgenericMethod(void *,DEFGENERIC *,int); +static void RemoveDefgenericMethod(void *,DEFGENERIC *,long); #endif #if DEBUGGING_FUNCTIONS -static long ListMethodsForGeneric(void *,char *,DEFGENERIC *); +static long ListMethodsForGeneric(void *,const char *,DEFGENERIC *); static unsigned DefgenericWatchAccess(void *,int,unsigned,EXPRESSION *); -static unsigned DefgenericWatchPrint(void *,char *,int,EXPRESSION *); +static unsigned DefgenericWatchPrint(void *,const char *,int,EXPRESSION *); static unsigned DefmethodWatchAccess(void *,int,unsigned,EXPRESSION *); -static unsigned DefmethodWatchPrint(void *,char *,int,EXPRESSION *); -static unsigned DefmethodWatchSupport(void *,char *,char *,unsigned, - void (*)(void *,char *,void *,unsigned), - void (*)(void *,unsigned,void *,unsigned), +static unsigned DefmethodWatchPrint(void *,const char *,int,EXPRESSION *); +static unsigned DefmethodWatchSupport(void *,const char *,const char *,unsigned, + void (*)(void *,const char *,void *,long), + void (*)(void *,unsigned,void *,long), EXPRESSION *); -static void PrintMethodWatchFlag(void *,char *,void *,unsigned); +static void PrintMethodWatchFlag(void *,const char *,void *,long); #endif /* ========================================= @@ -147,10 +170,10 @@ globle void SetupGenericFunctions( PrintGenericCall,PrintGenericCall, NULL,EvaluateGenericCall,NULL, DecrementGenericBusyCount,IncrementGenericBusyCount, - NULL,NULL,NULL,NULL }; - + NULL,NULL,NULL,NULL,NULL }; + AllocateEnvironmentData(theEnv,DEFGENERIC_DATA,sizeof(struct defgenericData),DeallocateDefgenericData); - memcpy(&DefgenericData(theEnv)->GenericEntityRecord,&genericEntityRecord,sizeof(struct entityRecord)); + memcpy(&DefgenericData(theEnv)->GenericEntityRecord,&genericEntityRecord,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&DefgenericData(theEnv)->GenericEntityRecord,GCALL); @@ -171,7 +194,7 @@ globle void SetupGenericFunctions( #else NULL, #endif - EnvFindDefgeneric); + EnvFindDefgenericInModule); DefgenericData(theEnv)->DefgenericConstruct = AddConstruct(theEnv,"defgeneric","defgenerics", #if (! BLOAD_ONLY) && (! RUN_TIME) @@ -268,7 +291,7 @@ globle void SetupGenericFunctions( DefmethodWatchAccess,DefmethodWatchPrint); #endif } - + /*****************************************************/ /* DeallocateDefgenericData: Deallocates environment */ /* data for the defgeneric construct. */ @@ -284,7 +307,7 @@ static void DeallocateDefgenericData( if (Bloaded(theEnv)) return; #endif - DoForAllConstructs(theEnv,DestroyDefgenericAction,DefgenericData(theEnv)->DefgenericModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDefgenericAction,DefgenericData(theEnv)->DefgenericModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; @@ -297,32 +320,29 @@ static void DeallocateDefgenericData( rtn_struct(theEnv,defgenericModule,theModuleItem); } #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } - + #if ! RUN_TIME /****************************************************/ /* DestroyDefgenericAction: Action used to remove */ /* defgenerics as a result of DestroyEnvironment. */ /****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDefgenericAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif #if (! BLOAD_ONLY) && (! RUN_TIME) struct defgeneric *theDefgeneric = (struct defgeneric *) theConstruct; - unsigned i; - + long i; + if (theDefgeneric == NULL) return; for (i = 0 ; i < theDefgeneric->mcnt ; i++) @@ -335,7 +355,7 @@ static void DestroyDefgenericAction( rtn_struct(theEnv,defgeneric,theDefgeneric); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,theConstruct) #endif #endif @@ -354,9 +374,26 @@ static void DestroyDefgenericAction( ***************************************************/ globle void *EnvFindDefgeneric( void *theEnv, - char *genericModuleAndName) + const char *genericModuleAndName) + { + return(FindNamedConstructInModuleOrImports(theEnv,genericModuleAndName,DefgenericData(theEnv)->DefgenericConstruct)); + } + +/*************************************************** + NAME : EnvFindDefgenericInModule + DESCRIPTION : Searches for a generic + INPUTS : The name of the generic + (possibly including a module name) + RETURNS : Pointer to the generic if + found, otherwise NULL + SIDE EFFECTS : None + NOTES : None + ***************************************************/ +globle void *EnvFindDefgenericInModule( + void *theEnv, + const char *genericModuleAndName) { - return(FindNamedConstruct(theEnv,genericModuleAndName,DefgenericData(theEnv)->DefgenericConstruct)); + return(FindNamedConstructInModule(theEnv,genericModuleAndName,DefgenericData(theEnv)->DefgenericConstruct)); } /*************************************************** @@ -372,7 +409,7 @@ globle void *EnvFindDefgeneric( ***************************************************/ globle DEFGENERIC *LookupDefgenericByMdlOrScope( void *theEnv, - char *defgenericName) + const char *defgenericName) { return((DEFGENERIC *) LookupConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,defgenericName,TRUE)); } @@ -390,7 +427,7 @@ globle DEFGENERIC *LookupDefgenericByMdlOrScope( ***************************************************/ globle DEFGENERIC *LookupDefgenericInScope( void *theEnv, - char *defgenericName) + const char *defgenericName) { return((DEFGENERIC *) LookupConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,defgenericName,FALSE)); } @@ -423,17 +460,14 @@ globle void *EnvGetNextDefgeneric( NOTES : If index == 0, the index of the first method is returned ***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle unsigned EnvGetNextDefmethod( +globle long EnvGetNextDefmethod( void *theEnv, void *ptr, - unsigned theIndex) + long theIndex) { DEFGENERIC *gfunc; - int mi; -#if MAC_MCW || IBM_MCW || MAC_XCD + long mi; +#if MAC_XCD #pragma unused(theEnv) #endif @@ -445,7 +479,7 @@ globle unsigned EnvGetNextDefmethod( return(0); } mi = FindMethodByIndex(gfunc,theIndex); - if ((mi+1) == (int) gfunc->mcnt) + if ((mi+1) == gfunc->mcnt) return(0); return(gfunc->methods[mi+1].index); } @@ -462,7 +496,7 @@ globle unsigned EnvGetNextDefmethod( *****************************************************/ globle DEFMETHOD *GetDefmethodPointer( void *ptr, - unsigned theIndex) + long theIndex) { return(&((DEFGENERIC *) ptr)->methods[theIndex-1]); } @@ -499,14 +533,14 @@ globle int EnvIsDefgenericDeletable( globle int EnvIsDefmethodDeletable( void *theEnv, void *ptr, - unsigned theIndex) + long theIndex) { if (! ConstructsDeletable(theEnv)) { return FALSE; } if (((DEFGENERIC *) ptr)->methods[FindMethodByIndex((DEFGENERIC *) ptr,theIndex)].system) return(FALSE); - + #if (! BLOAD_ONLY) && (! RUN_TIME) return((MethodsExecuting((DEFGENERIC *) ptr) == FALSE) ? TRUE : FALSE); #else @@ -555,7 +589,7 @@ globle void UndefmethodCommand( { DATA_OBJECT temp; DEFGENERIC *gfunc; - unsigned mi; + long mi; if (EnvArgTypeCheck(theEnv,"undefmethod",1,SYMBOL,&temp) == FALSE) return; @@ -581,7 +615,7 @@ globle void UndefmethodCommand( } else if (temp.type == INTEGER) { - mi = (unsigned) DOToInteger(temp); + mi = (long) DOToLong(temp); if (mi == 0) { PrintErrorID(theEnv,"GENRCCOM",2,FALSE); @@ -611,10 +645,6 @@ globle intBool EnvUndefgeneric( void *theEnv, void *vptr) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vptr) -#endif - #if RUN_TIME || BLOAD_ONLY return(FALSE); #else @@ -651,7 +681,7 @@ globle intBool EnvUndefgeneric( globle intBool EnvUndefmethod( void *theEnv, void *vptr, - unsigned mi) + long mi) { DEFGENERIC *gfunc; @@ -663,14 +693,14 @@ globle intBool EnvUndefmethod( { PrintGenericName(theEnv,WERROR,gfunc); EnvPrintRouter(theEnv,WERROR," #"); - PrintLongInteger(theEnv,WERROR,(long) mi); + PrintLongInteger(theEnv,WERROR,(long long) mi); } else EnvPrintRouter(theEnv,WERROR,"*"); EnvPrintRouter(theEnv,WERROR,".\n"); return(FALSE); #else - int nmi; + long nmi; gfunc = (DEFGENERIC *) vptr; #if BLOAD || BLOAD_AND_BSAVE @@ -682,7 +712,7 @@ globle intBool EnvUndefmethod( { EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc)); EnvPrintRouter(theEnv,WERROR," #"); - PrintLongInteger(theEnv,WERROR,(long) mi); + PrintLongInteger(theEnv,WERROR,(long long) mi); } else EnvPrintRouter(theEnv,WERROR,"*"); @@ -709,7 +739,7 @@ globle intBool EnvUndefmethod( RemoveAllExplicitMethods(theEnv,gfunc); else { - nmi = CheckMethodExists(theEnv,"undefmethod",gfunc,(int) mi); + nmi = CheckMethodExists(theEnv,"undefmethod",gfunc,mi); if (nmi == -1) return(FALSE); RemoveDefgenericMethod(theEnv,gfunc,nmi); @@ -718,7 +748,7 @@ globle intBool EnvUndefmethod( #endif } -#if DEBUGGING_FUNCTIONS +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS /***************************************************** NAME : EnvGetDefmethodDescription @@ -736,13 +766,13 @@ globle intBool EnvUndefmethod( globle void EnvGetDefmethodDescription( void *theEnv, char *buf, - int buflen, + size_t buflen, void *ptr, - unsigned theIndex) + long theIndex) { DEFGENERIC *gfunc; - int mi; -#if MAC_MCW || IBM_MCW || MAC_XCD + long mi; +#if MAC_XCD #pragma unused(theEnv) #endif @@ -750,6 +780,9 @@ globle void EnvGetDefmethodDescription( mi = FindMethodByIndex(gfunc,theIndex); PrintMethod(theEnv,buf,buflen,&gfunc->methods[mi]); } +#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */ + +#if DEBUGGING_FUNCTIONS /********************************************************* NAME : EnvGetDefgenericWatch @@ -761,14 +794,11 @@ globle void EnvGetDefmethodDescription( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefgenericWatch( void *theEnv, void *theGeneric) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -786,15 +816,12 @@ globle unsigned EnvGetDefgenericWatch( SIDE EFFECTS : Watch flag for the generic set NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefgenericWatch( void *theEnv, unsigned newState, void *theGeneric) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -812,17 +839,14 @@ globle void EnvSetDefgenericWatch( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefmethodWatch( void *theEnv, void *theGeneric, - unsigned theIndex) + long theIndex) { DEFGENERIC *gfunc; - int mi; -#if MAC_MCW || IBM_MCW || MAC_XCD + long mi; +#if MAC_XCD #pragma unused(theEnv) #endif @@ -843,18 +867,15 @@ globle unsigned EnvGetDefmethodWatch( SIDE EFFECTS : Watch flag for the method set NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefmethodWatch( void *theEnv, unsigned newState, void *theGeneric, - unsigned theIndex) + long theIndex) { DEFGENERIC *gfunc; - int mi; -#if MAC_MCW || IBM_MCW || MAC_XCD + long mi; +#if MAC_XCD #pragma unused(theEnv) #endif @@ -892,10 +913,10 @@ globle void PPDefmethodCommand( void *theEnv) { DATA_OBJECT temp; - char *gname; + const char *gname; DEFGENERIC *gfunc; int gi; - + if (EnvArgTypeCheck(theEnv,"ppdefmethod",1,SYMBOL,&temp) == FALSE) return; gname = DOToString(temp); @@ -904,7 +925,7 @@ globle void PPDefmethodCommand( gfunc = CheckGenericExists(theEnv,"ppdefmethod",gname); if (gfunc == NULL) return; - gi = CheckMethodExists(theEnv,"ppdefmethod",gfunc,DOToInteger(temp)); + gi = CheckMethodExists(theEnv,"ppdefmethod",gfunc,(long) DOToLong(temp)); if (gi == -1) return; if (gfunc->methods[gi].ppForm != NULL) @@ -925,7 +946,7 @@ globle void ListDefmethodsCommand( { DATA_OBJECT temp; DEFGENERIC *gfunc; - + if (EnvRtnArgCount(theEnv) == 0) EnvListDefmethods(theEnv,WDISPLAY,NULL); else @@ -947,17 +968,14 @@ globle void ListDefmethodsCommand( SIDE EFFECTS : None NOTES : None ***************************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetDefmethodPPForm( +globle const char *EnvGetDefmethodPPForm( void *theEnv, void *ptr, - unsigned theIndex) + long theIndex) { DEFGENERIC *gfunc; int mi; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -991,7 +1009,7 @@ globle void ListDefgenericsCommand( ***************************************************/ globle void EnvListDefgenerics( void *theEnv, - char *logicalName, + const char *logicalName, struct defmodule *theModule) { ListConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,logicalName,theModule); @@ -1010,7 +1028,7 @@ globle void EnvListDefgenerics( ******************************************************/ globle void EnvListDefmethods( void *theEnv, - char *logicalName, + const char *logicalName, void *vptr) { DEFGENERIC *gfunc; @@ -1032,7 +1050,7 @@ globle void EnvListDefmethods( PrintTally(theEnv,logicalName,count,"method","methods"); } -#endif +#endif /* DEBUGGING_FUNCTIONS */ /*************************************************************** NAME : GetDefgenericListFunction @@ -1086,7 +1104,7 @@ globle void GetDefmethodListCommand( { DATA_OBJECT temp; DEFGENERIC *gfunc; - + if (EnvRtnArgCount(theEnv) == 0) EnvGetDefmethodList(theEnv,NULL,returnValue); else @@ -1121,7 +1139,7 @@ globle void EnvGetDefmethodList( DATA_OBJECT_PTR returnValue) { DEFGENERIC *gfunc,*svg,*svnxt; - unsigned i,j; + long i,j; unsigned long count; MULTIFIELD_PTR theList; @@ -1156,7 +1174,7 @@ globle void EnvGetDefmethodList( SetMFType(theList,i,SYMBOL); SetMFValue(theList,i++,GetDefgenericNamePointer((void *) gfunc)); SetMFType(theList,i,INTEGER); - SetMFValue(theList,i++,EnvAddLong(theEnv,(long) gfunc->methods[j].index)); + SetMFValue(theList,i++,EnvAddLong(theEnv,(long long) gfunc->methods[j].index)); } } if (svg != NULL) @@ -1194,12 +1212,12 @@ globle void GetMethodRestrictionsCommand( EnvSetMultifieldErrorValue(theEnv,result); return; } - if (CheckMethodExists(theEnv,"get-method-restrictions",gfunc,DOToInteger(temp)) == -1) + if (CheckMethodExists(theEnv,"get-method-restrictions",gfunc,(long) DOToLong(temp)) == -1) { EnvSetMultifieldErrorValue(theEnv,result); return; } - EnvGetMethodRestrictions(theEnv,(void *) gfunc,(unsigned) DOToInteger(temp),result); + EnvGetMethodRestrictions(theEnv,(void *) gfunc,(unsigned) DOToLong(temp),result); } /*********************************************************************** @@ -1241,19 +1259,19 @@ globle void GetMethodRestrictionsCommand( globle void EnvGetMethodRestrictions( void *theEnv, void *vgfunc, - unsigned mi, + long mi, DATA_OBJECT *result) { - register unsigned i,j; + short i,j; register DEFMETHOD *meth; register RESTRICTION *rptr; - unsigned count; + long count; int roffset,rstrctIndex; MULTIFIELD_PTR theList; meth = ((DEFGENERIC *) vgfunc)->methods + FindMethodByIndex((DEFGENERIC *) vgfunc,mi); count = 3; - for (i = 0 ; i < (unsigned) meth->restrictionCount ; i++) + for (i = 0 ; i < meth->restrictionCount ; i++) count += meth->restrictions[i].tcnt + 3; theList = (MULTIFIELD_PTR) EnvCreateMultifield(theEnv,count); SetpType(result,MULTIFIELD); @@ -1261,22 +1279,22 @@ globle void EnvGetMethodRestrictions( SetpDOBegin(result,1); SetpDOEnd(result,count); SetMFType(theList,1,INTEGER); - SetMFValue(theList,1,EnvAddLong(theEnv,(long) meth->minRestrictions)); + SetMFValue(theList,1,EnvAddLong(theEnv,(long long) meth->minRestrictions)); SetMFType(theList,2,INTEGER); - SetMFValue(theList,2,EnvAddLong(theEnv,(long) meth->maxRestrictions)); + SetMFValue(theList,2,EnvAddLong(theEnv,(long long) meth->maxRestrictions)); SetMFType(theList,3,INTEGER); - SetMFValue(theList,3,EnvAddLong(theEnv,(long) meth->restrictionCount)); + SetMFValue(theList,3,EnvAddLong(theEnv,(long long) meth->restrictionCount)); roffset = 3 + meth->restrictionCount + 1; rstrctIndex = 4; - for (i = 0 ; i < (unsigned) meth->restrictionCount ; i++) + for (i = 0 ; i < meth->restrictionCount ; i++) { rptr = meth->restrictions + i; SetMFType(theList,rstrctIndex,INTEGER); - SetMFValue(theList,rstrctIndex++,EnvAddLong(theEnv,(long) roffset)); + SetMFValue(theList,rstrctIndex++,EnvAddLong(theEnv,(long long) roffset)); SetMFType(theList,roffset,SYMBOL); SetMFValue(theList,roffset++,(rptr->query != NULL) ? EnvTrueSymbol(theEnv) : EnvFalseSymbol(theEnv)); SetMFType(theList,roffset,INTEGER); - SetMFValue(theList,roffset++,EnvAddLong(theEnv,(long) rptr->tcnt)); + SetMFValue(theList,roffset++,EnvAddLong(theEnv,(long long) rptr->tcnt)); for (j = 0 ; j < rptr->tcnt ; j++) { SetMFType(theList,roffset,SYMBOL); @@ -1305,12 +1323,9 @@ globle void EnvGetMethodRestrictions( SIDE EFFECTS : Call expression printed NOTES : None ***************************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintGenericCall( void *theEnv, - char *logName, + const char *logName, void *value) { #if DEVELOPER @@ -1324,7 +1339,7 @@ static void PrintGenericCall( } EnvPrintRouter(theEnv,logName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logName) #pragma unused(value) @@ -1391,16 +1406,18 @@ static void DecrementGenericBusyCount( SIDE EFFECTS : Busy count incremented NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void IncrementGenericBusyCount( void *theEnv, void *value) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif + ((DEFGENERIC *) value)->busy++; } @@ -1417,7 +1434,7 @@ static void IncrementGenericBusyCount( static void SaveDefgenerics( void *theEnv, void *theModule, - char *logName) + const char *logName) { SaveConstruct(theEnv,theModule,logName,DefgenericData(theEnv)->DefgenericConstruct); } @@ -1433,7 +1450,7 @@ static void SaveDefgenerics( static void SaveDefmethods( void *theEnv, void *theModule, - char *logName) + const char *logName) { DoForAllConstructsInModule(theEnv,theModule,SaveDefmethodsForDefgeneric, DefgenericData(theEnv)->DefgenericModuleIndex, @@ -1457,8 +1474,8 @@ static void SaveDefmethodsForDefgeneric( void *userBuffer) { DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric; - char *logName = (char *) userBuffer; - register unsigned i; + const char *logName = (const char *) userBuffer; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) { @@ -1485,10 +1502,10 @@ static void SaveDefmethodsForDefgeneric( static void RemoveDefgenericMethod( void *theEnv, DEFGENERIC *gfunc, - int gi) + long gi) { DEFMETHOD *narr; - register unsigned b,e; + long b,e; if (gfunc->methods[gi].system) { @@ -1537,10 +1554,10 @@ static void RemoveDefgenericMethod( ******************************************************/ static long ListMethodsForGeneric( void *theEnv, - char *logicalName, + const char *logicalName, DEFGENERIC *gfunc) { - unsigned gi; + long gi; char buf[256]; for (gi = 0 ; gi < gfunc->mcnt ; gi++) @@ -1567,16 +1584,13 @@ static long ListMethodsForGeneric( SIDE EFFECTS : Watch flags set in specified generics NOTES : Accessory function for AddWatchItem() ******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefgenericWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -1597,16 +1611,13 @@ static unsigned DefgenericWatchAccess( SIDE EFFECTS : Watch flags displayed for specified generics NOTES : Accessory function for AddWatchItem() ***********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefgenericWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -1627,20 +1638,19 @@ static unsigned DefgenericWatchPrint( SIDE EFFECTS : Watch flags set in specified methods NOTES : Accessory function for AddWatchItem() ******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefmethodWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif - return(DefmethodWatchSupport(theEnv,(char *) (newState ? "watch" : "unwatch"),NULL, - newState,NULL,EnvSetDefmethodWatch,argExprs)); + if (newState) + return(DefmethodWatchSupport(theEnv,"watch",NULL,newState,NULL,EnvSetDefmethodWatch,argExprs)); + else + return(DefmethodWatchSupport(theEnv,"unwatch",NULL,newState,NULL,EnvSetDefmethodWatch,argExprs)); } /*********************************************************************** @@ -1656,16 +1666,13 @@ static unsigned DefmethodWatchAccess( SIDE EFFECTS : Watch flags displayed for specified methods NOTES : Accessory function for AddWatchItem() ***********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefmethodWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif return(DefmethodWatchSupport(theEnv,"list-watch-items",logName,0, @@ -1689,15 +1696,15 @@ static unsigned DefmethodWatchPrint( *******************************************************/ static unsigned DefmethodWatchSupport( void *theEnv, - char *funcName, - char *logName, + const char *funcName, + const char *logName, unsigned newState, - void (*printFunc)(void *,char *,void *,unsigned), - void (*traceFunc)(void *,unsigned,void *,unsigned), + void (*printFunc)(void *,const char *,void *,long), + void (*traceFunc)(void *,unsigned,void *,long), EXPRESSION *argExprs) { void *theGeneric; - unsigned theMethod = 0; + unsigned long theMethod = 0; int argIndex = 2; DATA_OBJECT genericName,methodIndex; struct defmodule *theModule; @@ -1765,9 +1772,9 @@ static unsigned DefmethodWatchSupport( if (EvaluateExpression(theEnv,argExprs,&methodIndex)) return(FALSE); if ((methodIndex.type != INTEGER) ? FALSE : - ((DOToInteger(methodIndex) <= 0) ? FALSE : + ((DOToLong(methodIndex) <= 0) ? FALSE : (FindMethodByIndex((DEFGENERIC *) theGeneric,theMethod) != -1))) - theMethod = (unsigned) DOToInteger(methodIndex); + theMethod = (long) DOToLong(methodIndex); else { ExpectedTypeError1(theEnv,funcName,argIndex,"method index"); @@ -1811,9 +1818,9 @@ static unsigned DefmethodWatchSupport( ***************************************************/ static void PrintMethodWatchFlag( void *theEnv, - char *logName, + const char *logName, void *theGeneric, - unsigned theMethod) + long theMethod) { char buf[60]; @@ -1821,7 +1828,10 @@ static void PrintMethodWatchFlag( EnvPrintRouter(theEnv,logName," "); EnvGetDefmethodDescription(theEnv,buf,59,theGeneric,theMethod); EnvPrintRouter(theEnv,logName,buf); - EnvPrintRouter(theEnv,logName,(char *) (EnvGetDefmethodWatch(theEnv,theGeneric,theMethod) ? " = on\n" : " = off\n")); + if (EnvGetDefmethodWatch(theEnv,theGeneric,theMethod)) + EnvPrintRouter(theEnv,logName," = on\n"); + else + EnvPrintRouter(theEnv,logName," = off\n"); } #endif @@ -1847,5 +1857,229 @@ globle void TypeCommand( #endif -#endif +/*#############################*/ +/* Additional Access Functions */ +/*#############################*/ + +globle SYMBOL_HN *GetDefgenericNamePointer( + void *theDefgeneric) + { + return GetConstructNamePointer((struct constructHeader *) theDefgeneric); + } + +globle void SetNextDefgeneric( + void *theDefgeneric, + void *targetDefgeneric) + { + SetNextConstruct((struct constructHeader *) theDefgeneric, + (struct constructHeader *) targetDefgeneric); + } + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDefgenericModule( + void *theEnv, + void *theDefgeneric) + { + return GetConstructModuleName((struct constructHeader *) theDefgeneric); + } + +globle const char *EnvGetDefgenericName( + void *theEnv, + void *theDefgeneric) + { + return GetConstructNameString((struct constructHeader *) theDefgeneric); + } + +globle const char *EnvGetDefgenericPPForm( + void *theEnv, + void *theDefgeneric) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDefgeneric); + } + +globle SYMBOL_HN *EnvGetDefgenericNamePointer( + void *theEnv, + void *theDefgeneric) + { + return GetConstructNamePointer((struct constructHeader *) theDefgeneric); + } + +globle void EnvSetDefgenericPPForm( + void *theEnv, + void *theDefgeneric, + const char *thePPForm) + { + SetConstructPPForm(theEnv,(struct constructHeader *) theDefgeneric,thePPForm); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void SetDefgenericPPForm( + void *theDefgeneric, + const char *thePPForm) + { + EnvSetDefgenericPPForm(GetCurrentEnvironment(),theDefgeneric,thePPForm); + } + +globle const char *DefgenericModule( + void *theDefgeneric) + { + return EnvDefgenericModule(GetCurrentEnvironment(),theDefgeneric); + } + +globle void *FindDefgeneric( + const char *genericModuleAndName) + { + return EnvFindDefgeneric(GetCurrentEnvironment(),genericModuleAndName); + } + +globle void GetDefgenericList( + DATA_OBJECT *returnValue, + struct defmodule *theModule) + { + EnvGetDefgenericList(GetCurrentEnvironment(),returnValue,theModule); + } + +globle const char *GetDefgenericName( + void *theDefgeneric) + { + return EnvGetDefgenericName(GetCurrentEnvironment(),theDefgeneric); + } + +globle const char *GetDefgenericPPForm( + void *theDefgeneric) + { + return EnvGetDefgenericPPForm(GetCurrentEnvironment(),theDefgeneric); + } + +globle void *GetNextDefgeneric( + void *ptr) + { + return EnvGetNextDefgeneric(GetCurrentEnvironment(),ptr); + } + +globle int IsDefgenericDeletable( + void *ptr) + { + return EnvIsDefgenericDeletable(GetCurrentEnvironment(),ptr); + } + +globle intBool Undefgeneric( + void *vptr) + { + return EnvUndefgeneric(GetCurrentEnvironment(),vptr); + } + +globle void GetDefmethodList( + void *vgfunc, + DATA_OBJECT_PTR returnValue) + { + EnvGetDefmethodList(GetCurrentEnvironment(),vgfunc,returnValue); + } + +globle void GetMethodRestrictions( + void *vgfunc, + long mi, + DATA_OBJECT *result) + { + EnvGetMethodRestrictions(GetCurrentEnvironment(),vgfunc,mi,result); + } + +globle long GetNextDefmethod( + void *ptr, + long theIndex) + { + return EnvGetNextDefmethod(GetCurrentEnvironment(),ptr,theIndex); + } + +globle int IsDefmethodDeletable( + void *ptr, + long theIndex) + { + return EnvIsDefmethodDeletable(GetCurrentEnvironment(),ptr,theIndex); + } + +globle intBool Undefmethod( + void *vptr, + long mi) + { + return EnvUndefmethod(GetCurrentEnvironment(),vptr,mi); + } + +#if DEBUGGING_FUNCTIONS + +globle unsigned GetDefgenericWatch( + void *theGeneric) + { + return EnvGetDefgenericWatch(GetCurrentEnvironment(),theGeneric); + } + +globle void ListDefgenerics( + const char *logicalName, + struct defmodule *theModule) + { + EnvListDefgenerics(GetCurrentEnvironment(),logicalName,theModule); + } + +globle void SetDefgenericWatch( + unsigned newState, + void *theGeneric) + { + EnvSetDefgenericWatch(GetCurrentEnvironment(),newState,theGeneric); + } + +globle const char *GetDefmethodPPForm( + void *ptr, + long theIndex) + { + return EnvGetDefmethodPPForm(GetCurrentEnvironment(),ptr,theIndex); + } + +globle unsigned GetDefmethodWatch( + void *theGeneric, + long theIndex) + { + return EnvGetDefmethodWatch(GetCurrentEnvironment(),theGeneric,theIndex); + } + +globle void ListDefmethods( + const char *logicalName, + void *vptr) + { + EnvListDefmethods(GetCurrentEnvironment(),logicalName,vptr); + } + +globle void SetDefmethodWatch( + unsigned newState, + void *theGeneric, + long theIndex) + { + EnvSetDefmethodWatch(GetCurrentEnvironment(),newState,theGeneric,theIndex); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS + +globle void GetDefmethodDescription( + char *buf, + int buflen, + void *ptr, + long theIndex) + { + EnvGetDefmethodDescription(GetCurrentEnvironment(),buf,buflen,ptr,theIndex); + } + +#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* DEFGENERIC_CONSTRUCT */ diff --git a/src/genrccom.h b/src/genrccom.h index e580e7b..27a3b21 100644 --- a/src/genrccom.h +++ b/src/genrccom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -20,21 +20,30 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when DEBUGGING_FUNCTIONS */ +/* is set to 0 and PROFILING_FUNCTIONS is set to */ +/* 1. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_genrccom #define _H_genrccom -#define EnvGetDefgenericName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDefgenericPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) - -#define SetNextDefgeneric(g,t) SetNextConstruct((struct constructHeader *) g, \ - (struct constructHeader *) t) -#define GetDefgenericNamePointer(x) GetConstructNamePointer((struct constructHeader *) x) -#define SetDefgenericPPForm(g,ppf) SetConstructPPForm(theEnv,(struct constructHeader *) g,ppf) - -#define EnvDefgenericModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - #ifndef _H_constrct #include "constrct.h" #endif @@ -64,95 +73,86 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DefgenericModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefgeneric(theEnv,a) EnvFindDefgeneric(theEnv,a) -#define GetDefgenericList(theEnv,a,b) EnvGetDefgenericList(theEnv,a,b) -#define GetDefgenericName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDefgenericPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetDefgenericWatch(theEnv,a) EnvGetDefgenericWatch(theEnv,a) -#define GetNextDefgeneric(theEnv,a) EnvGetNextDefgeneric(theEnv,a) -#define IsDefgenericDeletable(theEnv,a) EnvIsDefgenericDeletable(theEnv,a) -#define ListDefgenerics(theEnv,a,b) EnvListDefgenerics(theEnv,a,b) -#define SetDefgenericWatch(theEnv,a,b) EnvSetDefgenericWatch(theEnv,a,b) -#define Undefgeneric(theEnv,a) EnvUndefgeneric(theEnv,a) -#define GetDefmethodDescription(theEnv,a,b,c,d) EnvGetDefmethodDescription(theEnv,a,b,c,d) -#define GetDefmethodList(theEnv,a,b) EnvGetDefmethodList(theEnv,a,b) -#define GetDefmethodPPForm(theEnv,a,b) EnvGetDefmethodPPForm(theEnv,a,b) -#define GetDefmethodWatch(theEnv,a,b) EnvGetDefmethodWatch(theEnv,a,b) -#define GetMethodRestrictions(theEnv,a,b,c) EnvGetMethodRestrictions(theEnv,a,b,c) -#define GetNextDefmethod(theEnv,a,b) EnvGetNextDefmethod(theEnv,a,b) -#define IsDefmethodDeletable(theEnv,a,b) EnvIsDefmethodDeletable(theEnv,a,b) -#define ListDefmethods(theEnv,a,b) EnvListDefmethods(theEnv,a,b) -#define SetDefmethodWatch(theEnv,a,b,c) EnvSetDefmethodWatch(theEnv,a,b,c) -#define Undefmethod(theEnv,a,b) EnvUndefmethod(theEnv,a,b) -#else -#define DefgenericModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefgeneric(a) EnvFindDefgeneric(GetCurrentEnvironment(),a) -#define GetDefgenericList(a,b) EnvGetDefgenericList(GetCurrentEnvironment(),a,b) -#define GetDefgenericName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDefgenericPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetDefgenericWatch(a) EnvGetDefgenericWatch(GetCurrentEnvironment(),a) -#define GetNextDefgeneric(a) EnvGetNextDefgeneric(GetCurrentEnvironment(),a) -#define IsDefgenericDeletable(a) EnvIsDefgenericDeletable(GetCurrentEnvironment(),a) -#define ListDefgenerics(a,b) EnvListDefgenerics(GetCurrentEnvironment(),a,b) -#define SetDefgenericWatch(a,b) EnvSetDefgenericWatch(GetCurrentEnvironment(),a,b) -#define Undefgeneric(a) EnvUndefgeneric(GetCurrentEnvironment(),a) -#define GetDefmethodDescription(a,b,c,d) EnvGetDefmethodDescription(GetCurrentEnvironment(),a,b,c,d) -#define GetDefmethodList(a,b) EnvGetDefmethodList(GetCurrentEnvironment(),a,b) -#define GetDefmethodPPForm(a,b) EnvGetDefmethodPPForm(GetCurrentEnvironment(),a,b) -#define GetDefmethodWatch(a,b) EnvGetDefmethodWatch(GetCurrentEnvironment(),a,b) -#define GetMethodRestrictions(a,b,c) EnvGetMethodRestrictions(GetCurrentEnvironment(),a,b,c) -#define GetNextDefmethod(a,b) EnvGetNextDefmethod(GetCurrentEnvironment(),a,b) -#define IsDefmethodDeletable(a,b) EnvIsDefmethodDeletable(GetCurrentEnvironment(),a,b) -#define ListDefmethods(a,b) EnvListDefmethods(GetCurrentEnvironment(),a,b) -#define SetDefmethodWatch(a,b,c) EnvSetDefmethodWatch(GetCurrentEnvironment(),a,b,c) -#define Undefmethod(a,b) EnvUndefmethod(GetCurrentEnvironment(),a,b) -#endif - -LOCALE void SetupGenericFunctions(void *); -LOCALE void *EnvFindDefgeneric(void *,char *); -LOCALE DEFGENERIC *LookupDefgenericByMdlOrScope(void *,char *); -LOCALE DEFGENERIC *LookupDefgenericInScope(void *,char *); -LOCALE void *EnvGetNextDefgeneric(void *,void *); -LOCALE unsigned EnvGetNextDefmethod(void *,void *,unsigned); -LOCALE int EnvIsDefgenericDeletable(void *,void *); -LOCALE int EnvIsDefmethodDeletable(void *,void *,unsigned); -LOCALE void UndefgenericCommand(void *); -LOCALE void *GetDefgenericModuleCommand(void *); -LOCALE void UndefmethodCommand(void *); -LOCALE DEFMETHOD *GetDefmethodPointer(void *,unsigned); - -LOCALE intBool EnvUndefgeneric(void *,void *); -LOCALE intBool EnvUndefmethod(void *,void *,unsigned); - + LOCALE void SetupGenericFunctions(void *); + LOCALE void *EnvFindDefgeneric(void *,const char *); + LOCALE void *EnvFindDefgenericInModule(void *,const char *); + LOCALE DEFGENERIC *LookupDefgenericByMdlOrScope(void *,const char *); + LOCALE DEFGENERIC *LookupDefgenericInScope(void *,const char *); + LOCALE void *EnvGetNextDefgeneric(void *,void *); + LOCALE long EnvGetNextDefmethod(void *,void *,long); + LOCALE int EnvIsDefgenericDeletable(void *,void *); + LOCALE int EnvIsDefmethodDeletable(void *,void *,long); + LOCALE void UndefgenericCommand(void *); + LOCALE void *GetDefgenericModuleCommand(void *); + LOCALE void UndefmethodCommand(void *); + LOCALE DEFMETHOD *GetDefmethodPointer(void *,long); + LOCALE intBool EnvUndefgeneric(void *,void *); + LOCALE intBool EnvUndefmethod(void *,void *,long); #if ! OBJECT_SYSTEM -LOCALE void TypeCommand(void *,DATA_OBJECT *); + LOCALE void TypeCommand(void *,DATA_OBJECT *); #endif - -#if DEBUGGING_FUNCTIONS -LOCALE void EnvGetDefmethodDescription(void *,char *,int,void *,unsigned); -LOCALE unsigned EnvGetDefgenericWatch(void *,void *); -LOCALE void EnvSetDefgenericWatch(void *,unsigned,void *); -LOCALE unsigned EnvGetDefmethodWatch(void *,void *,unsigned); -LOCALE void EnvSetDefmethodWatch(void *,unsigned,void *,unsigned); -LOCALE void PPDefgenericCommand(void *); -LOCALE void PPDefmethodCommand(void *); -LOCALE void ListDefmethodsCommand(void *); -LOCALE char *EnvGetDefmethodPPForm(void *,void *,unsigned); -LOCALE void ListDefgenericsCommand(void *); -LOCALE void EnvListDefgenerics(void *,char *,struct defmodule *); -LOCALE void EnvListDefmethods(void *,char *,void *); +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS + LOCALE void EnvGetDefmethodDescription(void *,char *,size_t,void *,long); #endif - -LOCALE void GetDefgenericListFunction(void *,DATA_OBJECT *); -globle void EnvGetDefgenericList(void *,DATA_OBJECT *,struct defmodule *); -LOCALE void GetDefmethodListCommand(void *,DATA_OBJECT *); -LOCALE void EnvGetDefmethodList(void *,void *,DATA_OBJECT *); -LOCALE void GetMethodRestrictionsCommand(void *,DATA_OBJECT *); -LOCALE void EnvGetMethodRestrictions(void *,void *,unsigned,DATA_OBJECT *); - +#if DEBUGGING_FUNCTIONS + LOCALE unsigned EnvGetDefgenericWatch(void *,void *); + LOCALE void EnvSetDefgenericWatch(void *,unsigned,void *); + LOCALE unsigned EnvGetDefmethodWatch(void *,void *,long); + LOCALE void EnvSetDefmethodWatch(void *,unsigned,void *,long); + LOCALE void PPDefgenericCommand(void *); + LOCALE void PPDefmethodCommand(void *); + LOCALE void ListDefmethodsCommand(void *); + LOCALE const char *EnvGetDefmethodPPForm(void *,void *,long); + LOCALE void ListDefgenericsCommand(void *); + LOCALE void EnvListDefgenerics(void *,const char *,struct defmodule *); + LOCALE void EnvListDefmethods(void *,const char *,void *); #endif + LOCALE void GetDefgenericListFunction(void *,DATA_OBJECT *); + LOCALE void EnvGetDefgenericList(void *,DATA_OBJECT *,struct defmodule *); + LOCALE void GetDefmethodListCommand(void *,DATA_OBJECT *); + LOCALE void EnvGetDefmethodList(void *,void *,DATA_OBJECT *); + LOCALE void GetMethodRestrictionsCommand(void *,DATA_OBJECT *); + LOCALE void EnvGetMethodRestrictions(void *,void *,long,DATA_OBJECT *); + LOCALE SYMBOL_HN *GetDefgenericNamePointer(void *); + LOCALE void SetNextDefgeneric(void *,void *); + LOCALE const char *EnvDefgenericModule(void *,void *); + LOCALE const char *EnvGetDefgenericName(void *,void *); + LOCALE const char *EnvGetDefgenericPPForm(void *,void *); + LOCALE SYMBOL_HN *EnvGetDefgenericNamePointer(void *,void *); + LOCALE void EnvSetDefgenericPPForm(void *,void *,const char *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void SetDefgenericPPForm(void *,const char *); + LOCALE const char *DefgenericModule(void *); + LOCALE void *FindDefgeneric(const char *); + LOCALE void GetDefgenericList(DATA_OBJECT *,struct defmodule *); + LOCALE const char *GetDefgenericName(void *); + LOCALE const char *GetDefgenericPPForm(void *); + LOCALE void *GetNextDefgeneric(void *); + LOCALE int IsDefgenericDeletable(void *); + LOCALE intBool Undefgeneric(void *); + LOCALE void GetDefmethodList(void *,DATA_OBJECT_PTR); + LOCALE void GetMethodRestrictions(void *,long,DATA_OBJECT *); + LOCALE long GetNextDefmethod(void *,long ); + LOCALE int IsDefmethodDeletable(void *,long ); + LOCALE intBool Undefmethod(void *,long ); +#if DEBUGGING_FUNCTIONS + LOCALE unsigned GetDefgenericWatch(void *); + LOCALE void ListDefgenerics(const char *,struct defmodule *); + LOCALE void SetDefgenericWatch(unsigned,void *); + LOCALE const char *GetDefmethodPPForm(void *,long); + LOCALE unsigned GetDefmethodWatch(void *,long); + LOCALE void ListDefmethods(const char *,void *); + LOCALE void SetDefmethodWatch(unsigned,void *,long); +#endif /* DEBUGGING_FUNCTIONS */ +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS + LOCALE void GetDefmethodDescription(char *,int,void *,long ); +#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_genrccom */ diff --git a/src/genrcexe.c b/src/genrcexe.c index 986fe4b..8d8998a 100644 --- a/src/genrcexe.c +++ b/src/genrcexe.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Generic Function Execution Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,15 @@ /* */ /* 6.24: Removed IMPERATIVE_METHODS compilation flag. */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -30,6 +39,8 @@ #if DEFGENERIC_CONSTRUCT +#include <string.h> + #if OBJECT_SYSTEM #include "classcom.h" #include "classfun.h" @@ -67,8 +78,8 @@ static DEFMETHOD *FindApplicableMethod(void *,DEFGENERIC *,DEFMETHOD *); #if DEBUGGING_FUNCTIONS -static void WatchGeneric(void *,char *); -static void WatchMethod(void *,char *); +static void WatchGeneric(void *,const char *); +static void WatchMethod(void *,const char *); #endif #if OBJECT_SYSTEM @@ -124,12 +135,20 @@ globle void GenericDispatch( #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; #endif + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); EvaluationData(theEnv)->EvaluationError = FALSE; if (EvaluationData(theEnv)->HaltExecution) return; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + oldce = ExecutingConstruct(theEnv); SetExecutingConstruct(theEnv,TRUE); previousGeneric = DefgenericData(theEnv)->CurrentGeneric; @@ -146,7 +165,10 @@ globle void GenericDispatch( DefgenericData(theEnv)->CurrentGeneric = previousGeneric; DefgenericData(theEnv)->CurrentMethod = previousMethod; EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); return; } @@ -165,7 +187,7 @@ globle void GenericDispatch( EnvPrintRouter(theEnv,WERROR,"Generic function "); EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc)); EnvPrintRouter(theEnv,WERROR," method #"); - PrintLongInteger(theEnv,WERROR,(long) meth->index); + PrintLongInteger(theEnv,WERROR,(long long) meth->index); EnvPrintRouter(theEnv,WERROR," is not applicable to the given arguments.\n"); } } @@ -227,8 +249,10 @@ globle void GenericDispatch( DefgenericData(theEnv)->CurrentGeneric = previousGeneric; DefgenericData(theEnv)->CurrentMethod = previousMethod; EvaluationData(theEnv)->CurrentEvaluationDepth--; - PropagateReturnValue(theEnv,result); - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); } @@ -248,7 +272,7 @@ globle void UnboundMethodErr( EnvPrintRouter(theEnv,WERROR,"generic function "); EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) DefgenericData(theEnv)->CurrentGeneric)); EnvPrintRouter(theEnv,WERROR," method #"); - PrintLongInteger(theEnv,WERROR,(long) DefgenericData(theEnv)->CurrentMethod->index); + PrintLongInteger(theEnv,WERROR,(long long) DefgenericData(theEnv)->CurrentMethod->index); EnvPrintRouter(theEnv,WERROR,".\n"); } @@ -268,7 +292,7 @@ globle intBool IsMethodApplicable( DEFMETHOD *meth) { DATA_OBJECT temp; - register unsigned i,j,k; + short i,j,k; register RESTRICTION *rp; #if OBJECT_SYSTEM void *type; @@ -279,7 +303,7 @@ globle intBool IsMethodApplicable( if ((ProceduralPrimitiveData(theEnv)->ProcParamArraySize < meth->minRestrictions) || ((ProceduralPrimitiveData(theEnv)->ProcParamArraySize > meth->minRestrictions) && (meth->maxRestrictions != -1))) return(FALSE); - for (i = 0 , k = 0 ; i < (unsigned) ProceduralPrimitiveData(theEnv)->ProcParamArraySize ; i++) + for (i = 0 , k = 0 ; i < ProceduralPrimitiveData(theEnv)->ProcParamArraySize ; i++) { rp = &meth->restrictions[k]; if (rp->tcnt != 0) @@ -471,7 +495,7 @@ globle void CallSpecificMethod( return; if (EnvArgTypeCheck(theEnv,"call-specific-method",2,INTEGER,&temp) == FALSE) return; - mi = CheckMethodExists(theEnv,"call-specific-method",gfunc,DOToInteger(temp)); + mi = CheckMethodExists(theEnv,"call-specific-method",gfunc,(long) DOToLong(temp)); if (mi == -1) return; gfunc->methods[mi].busy++; @@ -580,7 +604,7 @@ static DEFMETHOD *FindApplicableMethod( **********************************************************************/ static void WatchGeneric( void *theEnv, - char *tstring) + const char *tstring) { EnvPrintRouter(theEnv,WTRACE,"GNC "); EnvPrintRouter(theEnv,WTRACE,tstring); @@ -594,7 +618,7 @@ static void WatchGeneric( EnvPrintRouter(theEnv,WTRACE,ValueToString((void *) DefgenericData(theEnv)->CurrentGeneric->header.name)); EnvPrintRouter(theEnv,WTRACE," "); EnvPrintRouter(theEnv,WTRACE," ED:"); - PrintLongInteger(theEnv,WTRACE,(long) EvaluationData(theEnv)->CurrentEvaluationDepth); + PrintLongInteger(theEnv,WTRACE,(long long) EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,WTRACE); } @@ -612,7 +636,7 @@ static void WatchGeneric( **********************************************************************/ static void WatchMethod( void *theEnv, - char *tstring) + const char *tstring) { EnvPrintRouter(theEnv,WTRACE,"MTH "); EnvPrintRouter(theEnv,WTRACE,tstring); @@ -627,10 +651,10 @@ static void WatchMethod( EnvPrintRouter(theEnv,WTRACE,":#"); if (DefgenericData(theEnv)->CurrentMethod->system) EnvPrintRouter(theEnv,WTRACE,"SYS"); - PrintLongInteger(theEnv,WTRACE,(long) DefgenericData(theEnv)->CurrentMethod->index); + PrintLongInteger(theEnv,WTRACE,(long long) DefgenericData(theEnv)->CurrentMethod->index); EnvPrintRouter(theEnv,WTRACE," "); EnvPrintRouter(theEnv,WTRACE," ED:"); - PrintLongInteger(theEnv,WTRACE,(long) EvaluationData(theEnv)->CurrentEvaluationDepth); + PrintLongInteger(theEnv,WTRACE,(long long) EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,WTRACE); } diff --git a/src/genrcexe.h b/src/genrcexe.h index 682586d..2ff293e 100644 --- a/src/genrcexe.h +++ b/src/genrcexe.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -18,6 +18,15 @@ /* */ /* 6.24: Removed IMPERATIVE_METHODS compilation flag. */ /* */ +/* 6.30: Changed garbage collection algorithm. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_genrcexe @@ -43,23 +52,20 @@ #define LOCALE extern #endif -LOCALE void GenericDispatch(void *,DEFGENERIC *,DEFMETHOD *,DEFMETHOD *,EXPRESSION *,DATA_OBJECT *); -LOCALE void UnboundMethodErr(void *); -LOCALE intBool IsMethodApplicable(void *,DEFMETHOD *); + LOCALE void GenericDispatch(void *,DEFGENERIC *,DEFMETHOD *,DEFMETHOD *,EXPRESSION *,DATA_OBJECT *); + LOCALE void UnboundMethodErr(void *); + LOCALE intBool IsMethodApplicable(void *,DEFMETHOD *); -LOCALE int NextMethodP(void *); -LOCALE void CallNextMethod(void *,DATA_OBJECT *); -LOCALE void CallSpecificMethod(void *,DATA_OBJECT *); -LOCALE void OverrideNextMethod(void *,DATA_OBJECT *); + LOCALE int NextMethodP(void *); + LOCALE void CallNextMethod(void *,DATA_OBJECT *); + LOCALE void CallSpecificMethod(void *,DATA_OBJECT *); + LOCALE void OverrideNextMethod(void *,DATA_OBJECT *); -LOCALE void GetGenericCurrentArgument(void *,DATA_OBJECT *); + LOCALE void GetGenericCurrentArgument(void *,DATA_OBJECT *); -#ifndef _GENRCEXE_SOURCE_ -#endif - -#endif +#endif /* DEFGENERIC_CONSTRUCT */ -#endif +#endif /* _H_genrcexe */ diff --git a/src/genrcfun.c b/src/genrcfun.c index 0758a2a..6380d7e 100644 --- a/src/genrcfun.c +++ b/src/genrcfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Generic Functions Internal Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable log to logName */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -23,6 +24,24 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when DEBUGGING_FUNCTIONS */ +/* is set to 0 and PROFILING_FUNCTIONS is set to */ +/* 1. */ +/* */ +/* Fixed typing issue when OBJECT_SYSTEM */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ /* ========================================= @@ -52,6 +71,7 @@ #include "memalloc.h" #include "prccode.h" #include "router.h" +#include "sysdep.h" #define _GENRCFUN_SOURCE_ #include "genrcfun.h" @@ -184,7 +204,7 @@ globle int RemoveAllExplicitMethods( void *theEnv, DEFGENERIC *gfunc) { - register unsigned i,j; + long i,j; unsigned systemMethodCount = 0; DEFMETHOD *narr; @@ -209,7 +229,7 @@ globle int RemoveAllExplicitMethods( i++; } rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * gfunc->mcnt)); - gfunc->mcnt = systemMethodCount; + gfunc->mcnt = (short) systemMethodCount; gfunc->methods = narr; } else @@ -240,7 +260,7 @@ globle void RemoveDefgeneric( void *vgfunc) { DEFGENERIC *gfunc = (DEFGENERIC *) vgfunc; - register unsigned i; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) DeleteMethodInfo(theEnv,gfunc,&gfunc->methods[i]); @@ -248,7 +268,7 @@ globle void RemoveDefgeneric( if (gfunc->mcnt != 0) rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * gfunc->mcnt)); DecrementSymbolCount(theEnv,GetDefgenericNamePointer((void *) gfunc)); - SetDefgenericPPForm((void *) gfunc,NULL); + EnvSetDefgenericPPForm(theEnv,(void *) gfunc,NULL); ClearUserDataList(theEnv,gfunc->header.usrData); rtn_struct(theEnv,defgeneric,gfunc); } @@ -328,8 +348,8 @@ globle void DeleteMethodInfo( DEFGENERIC *gfunc, DEFMETHOD *meth) { - register unsigned j,k; - register RESTRICTION *rptr; + short j,k; + RESTRICTION *rptr; SaveBusyCount(gfunc); ExpressionDeinstall(theEnv,meth->actions); @@ -337,7 +357,7 @@ globle void DeleteMethodInfo( ClearUserDataList(theEnv,meth->usrData); if (meth->ppForm != NULL) rm(theEnv,(void *) meth->ppForm,(sizeof(char) * (strlen(meth->ppForm)+1))); - for (j = 0 ; j < (unsigned) meth->restrictionCount ; j++) + for (j = 0 ; j < meth->restrictionCount ; j++) { rptr = &meth->restrictions[j]; @@ -358,7 +378,7 @@ globle void DeleteMethodInfo( (sizeof(RESTRICTION) * meth->restrictionCount)); RestoreBusyCount(gfunc); } - + /*************************************************** NAME : DestroyMethodInfo DESCRIPTION : Deallocates all the data associated @@ -370,9 +390,6 @@ globle void DeleteMethodInfo( SIDE EFFECTS : Nodes deallocated NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void DestroyMethodInfo( void *theEnv, DEFGENERIC *gfunc, @@ -380,12 +397,12 @@ globle void DestroyMethodInfo( { register int j; register RESTRICTION *rptr; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(gfunc) #endif ReturnPackedExpression(theEnv,meth->actions); - + ClearUserDataList(theEnv,meth->usrData); if (meth->ppForm != NULL) rm(theEnv,(void *) meth->ppForm,(sizeof(char) * (strlen(meth->ppForm)+1))); @@ -417,14 +434,14 @@ globle void DestroyMethodInfo( globle int MethodsExecuting( DEFGENERIC *gfunc) { - register unsigned i; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) if (gfunc->methods[i].busy > 0) return(TRUE); return(FALSE); } - + #endif #if ! OBJECT_SYSTEM @@ -473,18 +490,86 @@ globle intBool SubsumeType( SIDE EFFECTS : None NOTES : None *****************************************************/ -globle int FindMethodByIndex( +globle long FindMethodByIndex( DEFGENERIC *gfunc, - unsigned theIndex) + long theIndex) { - register unsigned i; + long i; for (i = 0 ; i < gfunc->mcnt ; i++) if (gfunc->methods[i].index == theIndex) - return((int) i); + return(i); return(-1); } +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS + +/****************************************************************** + NAME : PrintMethod + DESCRIPTION : Lists a brief description of methods for a method + INPUTS : 1) Buffer for method info + 2) Size of buffer (not including space for '\0') + 3) The method address + RETURNS : Nothing useful + SIDE EFFECTS : None + NOTES : A terminating newline is NOT included + ******************************************************************/ +globle void PrintMethod( + void *theEnv, + char *buf, + size_t buflen, + DEFMETHOD *meth) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + long j,k; + register RESTRICTION *rptr; + char numbuf[15]; + + buf[0] = '\0'; + if (meth->system) + genstrncpy(buf,"SYS",(STD_SIZE) buflen); + gensprintf(numbuf,"%-2d ",meth->index); + genstrncat(buf,numbuf,(STD_SIZE) buflen-3); + for (j = 0 ; j < meth->restrictionCount ; j++) + { + rptr = &meth->restrictions[j]; + if ((((int) j) == meth->restrictionCount-1) && (meth->maxRestrictions == -1)) + { + if ((rptr->tcnt == 0) && (rptr->query == NULL)) + { + genstrncat(buf,"$?",buflen-strlen(buf)); + break; + } + genstrncat(buf,"($? ",buflen-strlen(buf)); + } + else + genstrncat(buf,"(",buflen-strlen(buf)); + for (k = 0 ; k < rptr->tcnt ; k++) + { +#if OBJECT_SYSTEM + genstrncat(buf,EnvGetDefclassName(theEnv,rptr->types[k]),buflen-strlen(buf)); +#else + genstrncat(buf,TypeName(theEnv,ValueToInteger(rptr->types[k])),buflen-strlen(buf)); +#endif + if (((int) k) < (((int) rptr->tcnt) - 1)) + genstrncat(buf," ",buflen-strlen(buf)); + } + if (rptr->query != NULL) + { + if (rptr->tcnt != 0) + genstrncat(buf," ",buflen-strlen(buf)); + genstrncat(buf,"<qry>",buflen-strlen(buf)); + } + genstrncat(buf,")",buflen-strlen(buf)); + if (((int) j) != (((int) meth->restrictionCount)-1)) + genstrncat(buf," ",buflen-strlen(buf)); + } + } + +#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */ + #if DEBUGGING_FUNCTIONS /************************************************************* @@ -546,74 +631,7 @@ globle void PreviewGeneric( SetExecutingConstruct(theEnv,oldce); } -/****************************************************************** - NAME : PrintMethod - DESCRIPTION : Lists a brief description of methods for a method - INPUTS : 1) Buffer for method info - 2) Size of buffer (not including space for '\0') - 3) The method address - RETURNS : Nothing useful - SIDE EFFECTS : None - NOTES : A terminating newline is NOT included - ******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle void PrintMethod( - void *theEnv, - char *buf, - int buflen, - DEFMETHOD *meth) - { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(theEnv) -#endif - register unsigned j,k; - register RESTRICTION *rptr; - char numbuf[15]; - - buf[0] = '\0'; - if (meth->system) - strncpy(buf,"SYS",(STD_SIZE) buflen); - sprintf(numbuf,"%-2d ",meth->index); - strncat(buf,numbuf,(STD_SIZE) buflen-3); - for (j = 0 ; j < (unsigned) meth->restrictionCount ; j++) - { - rptr = &meth->restrictions[j]; - if ((((int) j) == meth->restrictionCount-1) && (meth->maxRestrictions == -1)) - { - if ((rptr->tcnt == 0) && (rptr->query == NULL)) - { - strncat(buf,"$?",buflen-strlen(buf)); - break; - } - strncat(buf,"($? ",buflen-strlen(buf)); - } - else - strncat(buf,"(",buflen-strlen(buf)); - for (k = 0 ; k < rptr->tcnt ; k++) - { -#if OBJECT_SYSTEM - strncat(buf,EnvGetDefclassName(theEnv,rptr->types[k]),buflen-strlen(buf)); -#else - strncat(buf,TypeName(theEnv,ValueToInteger(rptr->types[k])),buflen-strlen(buf)); -#endif - if (((int) k) < (((int) rptr->tcnt) - 1)) - strncat(buf," ",buflen-strlen(buf)); - } - if (rptr->query != NULL) - { - if (rptr->tcnt != 0) - strncat(buf," ",buflen-strlen(buf)); - strncat(buf,"<qry>",buflen-strlen(buf)); - } - strncat(buf,")",buflen-strlen(buf)); - if (((int) j) != (((int) meth->restrictionCount)-1)) - strncat(buf," ",buflen-strlen(buf)); - } - } - -#endif +#endif /* DEBUGGING_FUNCTIONS */ /*************************************************** NAME : CheckGenericExists @@ -629,8 +647,8 @@ globle void PrintMethod( ***************************************************/ globle DEFGENERIC *CheckGenericExists( void *theEnv, - char *fname, - char *gname) + const char *fname, + const char *gname) { DEFGENERIC *gfunc; @@ -660,22 +678,22 @@ globle DEFGENERIC *CheckGenericExists( SIDE EFFECTS : None NOTES : None ***************************************************/ -globle int CheckMethodExists( +globle long CheckMethodExists( void *theEnv, - char *fname, + const char *fname, DEFGENERIC *gfunc, - int mi) + long mi) { - int fi; + long fi; - fi = FindMethodByIndex(gfunc,(unsigned) mi); + fi = FindMethodByIndex(gfunc,mi); if (fi == -1) { PrintErrorID(theEnv,"GENRCFUN",2,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to find method "); EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc)); EnvPrintRouter(theEnv,WERROR," #"); - PrintLongInteger(theEnv,WERROR,(long) mi); + PrintLongInteger(theEnv,WERROR,mi); EnvPrintRouter(theEnv,WERROR," in function "); EnvPrintRouter(theEnv,WERROR,fname); EnvPrintRouter(theEnv,WERROR,".\n"); @@ -699,7 +717,7 @@ globle int CheckMethodExists( printed for unrecognized types NOTES : Used only when COOL is not present *******************************************************/ -globle char *TypeName( +globle const char *TypeName( void *theEnv, int tcode) { @@ -742,7 +760,7 @@ globle char *TypeName( ******************************************************/ globle void PrintGenericName( void *theEnv, - char *logName, + const char *logName, DEFGENERIC *gfunc) { if (gfunc->header.whichModule->theModule != ((struct defmodule *) EnvGetCurrentModule(theEnv))) @@ -776,7 +794,7 @@ static void DisplayGenericCore( void *theEnv, DEFGENERIC *gfunc) { - register unsigned i; + long i; char buf[256]; int rtn = FALSE; diff --git a/src/genrcfun.h b/src/genrcfun.h index 69308ab..ed729ec 100644 --- a/src/genrcfun.h +++ b/src/genrcfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,13 +10,37 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.23: Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Removed IMPERATIVE_METHODS compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when DEBUGGING_FUNCTIONS */ +/* is set to 0 and PROFILING_FUNCTIONS is set to */ +/* 1. */ +/* */ +/* Fixed typing issue when OBJECT_SYSTEM */ +/* compiler flag is set to 0. */ /* */ /*************************************************************/ @@ -67,15 +91,17 @@ struct restriction { void **types; EXPRESSION *query; - unsigned tcnt; + short tcnt; }; struct method { - unsigned index,busy; - int restrictionCount, - minRestrictions,maxRestrictions, - localVarCount; + short index; + unsigned busy; + short restrictionCount; + short minRestrictions; + short maxRestrictions; + short localVarCount; unsigned system : 1; unsigned trace : 1; RESTRICTION *restrictions; @@ -89,13 +115,14 @@ struct defgeneric struct constructHeader header; unsigned busy,trace; DEFMETHOD *methods; - unsigned mcnt,new_index; + short mcnt; + short new_index; }; #define DEFGENERIC_DATA 27 struct defgenericData - { + { struct construct *DefgenericConstruct; int DefgenericModuleIndex; ENTITY_RECORD GenericEntityRecord; @@ -132,43 +159,41 @@ struct defgenericData #endif #if ! RUN_TIME -LOCALE intBool ClearDefgenericsReady(void *); -LOCALE void *AllocateDefgenericModule(void *); -LOCALE void FreeDefgenericModule(void *,void *); + LOCALE intBool ClearDefgenericsReady(void *); + LOCALE void *AllocateDefgenericModule(void *); + LOCALE void FreeDefgenericModule(void *,void *); #endif #if (! BLOAD_ONLY) && (! RUN_TIME) -LOCALE int ClearDefmethods(void *); -LOCALE int RemoveAllExplicitMethods(void *,DEFGENERIC *); -LOCALE void RemoveDefgeneric(void *,void *); -LOCALE int ClearDefgenerics(void *); -LOCALE void MethodAlterError(void *,DEFGENERIC *); -LOCALE void DeleteMethodInfo(void *,DEFGENERIC *,DEFMETHOD *); -LOCALE void DestroyMethodInfo(void *,DEFGENERIC *,DEFMETHOD *); -LOCALE int MethodsExecuting(DEFGENERIC *); + LOCALE int ClearDefmethods(void *); + LOCALE int RemoveAllExplicitMethods(void *,DEFGENERIC *); + LOCALE void RemoveDefgeneric(void *,void *); + LOCALE int ClearDefgenerics(void *); + LOCALE void MethodAlterError(void *,DEFGENERIC *); + LOCALE void DeleteMethodInfo(void *,DEFGENERIC *,DEFMETHOD *); + LOCALE void DestroyMethodInfo(void *,DEFGENERIC *,DEFMETHOD *); + LOCALE int MethodsExecuting(DEFGENERIC *); #endif #if ! OBJECT_SYSTEM -LOCALE intBool SubsumeType(int,int); + LOCALE intBool SubsumeType(int,int); #endif -LOCALE int FindMethodByIndex(DEFGENERIC *,unsigned); + LOCALE long FindMethodByIndex(DEFGENERIC *,long); +#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS + LOCALE void PrintMethod(void *,char *,size_t,DEFMETHOD *); +#endif #if DEBUGGING_FUNCTIONS -LOCALE void PreviewGeneric(void *); -LOCALE void PrintMethod(void *,char *,int,DEFMETHOD *); + LOCALE void PreviewGeneric(void *); #endif -LOCALE DEFGENERIC *CheckGenericExists(void *,char *,char *); -LOCALE int CheckMethodExists(void *,char *,DEFGENERIC *,int); + LOCALE DEFGENERIC *CheckGenericExists(void *,const char *,const char *); + LOCALE long CheckMethodExists(void *,const char *,DEFGENERIC *,long); #if ! OBJECT_SYSTEM -LOCALE char *TypeName(void *,int); + LOCALE const char *TypeName(void *,int); #endif -LOCALE void PrintGenericName(void *,char *,DEFGENERIC *); - -#endif - - - + LOCALE void PrintGenericName(void *,const char *,DEFGENERIC *); +#endif /* _H_genrcfun */ diff --git a/src/genrcpsr.c b/src/genrcpsr.c index b21c56a..2f76169 100644 --- a/src/genrcpsr.c +++ b/src/genrcpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Generic Functions Parsing Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -23,6 +23,29 @@ /* parenthesis, an error should be issued, but is */ /* not. DR0872 */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_AND_SAVE */ +/* compiler flag is set to 0. */ +/* */ +/* Fixed typing issue when OBJECT_SYSTEM */ +/* compiler flag is set to 0. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ /* ========================================= @@ -58,6 +81,7 @@ #include "prccode.h" #include "router.h" #include "scanner.h" +#include "sysdep.h" #define _GENRCPSR_SOURCE_ #include "genrcpsr.h" @@ -79,22 +103,22 @@ ========================================= ***************************************** */ -static intBool ValidGenericName(void *,char *); -static SYMBOL_HN *ParseMethodNameAndIndex(void *,char *,unsigned *); +static intBool ValidGenericName(void *,const char *); +static SYMBOL_HN *ParseMethodNameAndIndex(void *,const char *,int *); #if DEBUGGING_FUNCTIONS static void CreateDefaultGenericPPForm(void *,DEFGENERIC *); #endif -static int ParseMethodParameters(void *,char *,EXPRESSION **,SYMBOL_HN **); -static RESTRICTION *ParseRestriction(void *,char *); +static int ParseMethodParameters(void *,const char *,EXPRESSION **,SYMBOL_HN **); +static RESTRICTION *ParseRestriction(void *,const char *); static void ReplaceCurrentArgRefs(void *,EXPRESSION *); static int DuplicateParameters(void *,EXPRESSION *,EXPRESSION **,SYMBOL_HN *); static EXPRESSION *AddParameter(void *,EXPRESSION *,EXPRESSION *,SYMBOL_HN *,RESTRICTION *); static EXPRESSION *ValidType(void *,SYMBOL_HN *); static intBool RedundantClasses(void *,void *,void *); static DEFGENERIC *AddGeneric(void *,SYMBOL_HN *,int *); -static DEFMETHOD *AddGenericMethod(void *,DEFGENERIC *,int,unsigned); +static DEFMETHOD *AddGenericMethod(void *,DEFGENERIC *,int,short); static int RestrictionsCompare(EXPRESSION *,int,int,int,DEFMETHOD *); static int TypeListCompare(RESTRICTION *,RESTRICTION *); static DEFGENERIC *NewGeneric(void *,SYMBOL_HN *); @@ -116,7 +140,7 @@ static DEFGENERIC *NewGeneric(void *,SYMBOL_HN *); ***************************************************************************/ globle intBool ParseDefgeneric( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *gname; DEFGENERIC *gfunc; @@ -136,8 +160,8 @@ globle intBool ParseDefgeneric( #endif gname = GetConstructNameAndComment(theEnv,readSource,&DefgenericData(theEnv)->GenericInputToken,"defgeneric", - EnvFindDefgeneric,NULL,"^",TRUE, - TRUE,TRUE); + EnvFindDefgenericInModule,NULL,"^",TRUE, + TRUE,TRUE,FALSE); if (gname == NULL) return(TRUE); @@ -163,7 +187,7 @@ globle intBool ParseDefgeneric( gfunc = AddGeneric(theEnv,gname,&newGeneric); #if DEBUGGING_FUNCTIONS - SetDefgenericPPForm((void *) gfunc,EnvGetConserveMemory(theEnv) ? NULL : CopyPPBuffer(theEnv)); + EnvSetDefgenericPPForm(theEnv,(void *) gfunc,EnvGetConserveMemory(theEnv) ? NULL : CopyPPBuffer(theEnv)); #endif return(FALSE); } @@ -185,7 +209,7 @@ globle intBool ParseDefgeneric( ***************************************************************************/ globle intBool ParseDefmethod( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *gname; int rcnt,mposn,mi,newMethod,mnew = FALSE,lvars,error; @@ -193,7 +217,7 @@ globle intBool ParseDefmethod( SYMBOL_HN *wildcard; DEFMETHOD *meth; DEFGENERIC *gfunc; - unsigned theIndex; + int theIndex; SetPPBufferStatus(theEnv,ON); FlushPPBuffer(theEnv); @@ -250,7 +274,7 @@ globle intBool ParseDefmethod( { PrintErrorID(theEnv,"GENRCPSR",17,FALSE); EnvPrintRouter(theEnv,WERROR,"Cannot replace the implicit system method #"); - PrintLongInteger(theEnv,WERROR,(long) meth->index); + PrintLongInteger(theEnv,WERROR,(long long) meth->index); EnvPrintRouter(theEnv,WERROR,".\n"); error = TRUE; } @@ -258,9 +282,9 @@ globle intBool ParseDefmethod( { PrintErrorID(theEnv,"GENRCPSR",2,FALSE); EnvPrintRouter(theEnv,WERROR,"New method #"); - PrintLongInteger(theEnv,WERROR,(long) theIndex); + PrintLongInteger(theEnv,WERROR,(long long) theIndex); EnvPrintRouter(theEnv,WERROR," would be indistinguishable from method #"); - PrintLongInteger(theEnv,WERROR,(long) meth->index); + PrintLongInteger(theEnv,WERROR,(long long) meth->index); EnvPrintRouter(theEnv,WERROR,".\n"); error = TRUE; } @@ -274,7 +298,7 @@ globle intBool ParseDefmethod( { PrintErrorID(theEnv,"GENRCPSR",17,FALSE); EnvPrintRouter(theEnv,WERROR,"Cannot replace the implicit system method #"); - PrintLongInteger(theEnv,WERROR,(long) theIndex); + PrintLongInteger(theEnv,WERROR,(long long) theIndex); EnvPrintRouter(theEnv,WERROR,".\n"); error = TRUE; } @@ -290,7 +314,7 @@ globle intBool ParseDefmethod( actions = ParseProcActions(theEnv,"method",readSource, &DefgenericData(theEnv)->GenericInputToken,params,wildcard, NULL,NULL,&lvars,NULL); - + /*===========================================================*/ /* Check for the closing right parenthesis of the defmethod. */ /*===========================================================*/ @@ -298,6 +322,7 @@ globle intBool ParseDefmethod( if ((DefgenericData(theEnv)->GenericInputToken.type != RPAREN) && /* DR0872 */ (actions != NULL)) { + SyntaxErrorMessage(theEnv,"defmethod"); DeleteTempRestricts(theEnv,params); ReturnPackedExpression(theEnv,actions); goto DefmethodParseError; @@ -332,17 +357,31 @@ globle intBool ParseDefmethod( SavePPBuffer(theEnv,"\n"); #if DEBUGGING_FUNCTIONS - meth = AddMethod(theEnv,gfunc,meth,mposn,theIndex,params,rcnt,lvars,wildcard,actions, + meth = AddMethod(theEnv,gfunc,meth,mposn,(short) theIndex,params,rcnt,lvars,wildcard,actions, EnvGetConserveMemory(theEnv) ? NULL : CopyPPBuffer(theEnv),FALSE); #else meth = AddMethod(theEnv,gfunc,meth,mposn,theIndex,params,rcnt,lvars,wildcard,actions,NULL,FALSE); #endif DeleteTempRestricts(theEnv,params); - if (GetPrintWhileLoading(theEnv) && GetCompilationsWatch(theEnv)) + if (GetPrintWhileLoading(theEnv) && GetCompilationsWatch(theEnv) && + (! ConstructData(theEnv)->CheckSyntaxMode)) { - EnvPrintRouter(theEnv,WDIALOG," Method #"); - PrintLongInteger(theEnv,WDIALOG,(long) meth->index); - EnvPrintRouter(theEnv,WDIALOG,(char *) (mnew ? " defined.\n" : " redefined.\n")); + const char *outRouter = WDIALOG; + + if (mnew) + { + EnvPrintRouter(theEnv,outRouter," Method #"); + PrintLongInteger(theEnv,outRouter,(long long) meth->index); + EnvPrintRouter(theEnv,outRouter," defined.\n"); + } + else + { + outRouter = WWARNING; + PrintWarningID(theEnv,"CSTRCPSR",1,TRUE); + EnvPrintRouter(theEnv,outRouter,"Method #"); + PrintLongInteger(theEnv,outRouter,(long long) meth->index); + EnvPrintRouter(theEnv,outRouter," redefined.\n"); + } } return(FALSE); @@ -389,7 +428,7 @@ globle DEFMETHOD *AddMethod( DEFGENERIC *gfunc, DEFMETHOD *meth, int mposn, - unsigned mi, + short mi, EXPRESSION *params, int rcnt, int lvars, @@ -446,15 +485,15 @@ globle DEFMETHOD *AddMethod( return(meth); } - meth->localVarCount = lvars; - meth->restrictionCount = rcnt; + meth->localVarCount = (short) lvars; + meth->restrictionCount = (short) rcnt; if (wildcard != NULL) { - meth->minRestrictions = rcnt-1; + meth->minRestrictions = (short) (rcnt-1); meth->maxRestrictions = -1; } else - meth->minRestrictions = meth->maxRestrictions = rcnt; + meth->minRestrictions = meth->maxRestrictions = (short) rcnt; if (rcnt != 0) meth->restrictions = (RESTRICTION *) gm2(theEnv,(sizeof(RESTRICTION) * rcnt)); @@ -488,7 +527,7 @@ globle DEFMETHOD *AddMethod( rtmp->types = NULL; } ExpressionInstall(theEnv,rptr->query); - for (j = 0 ; (unsigned) j < rptr->tcnt ; j++) + for (j = 0 ; j < rptr->tcnt ; j++) #if OBJECT_SYSTEM IncrementDefclassBusyCount(theEnv,rptr->types[j]); #else @@ -517,7 +556,7 @@ globle void PackRestrictionTypes( EXPRESSION *types) { EXPRESSION *tmp; - register unsigned i; + long i; rptr->tcnt = 0; for (tmp = types ; tmp != NULL ; tmp = tmp->nextArg) @@ -595,7 +634,7 @@ globle DEFMETHOD *FindMethodByRestrictions( } else min = max = rcnt; - for (i = 0 ; (unsigned) i < gfunc->mcnt ; i++) + for (i = 0 ; i < gfunc->mcnt ; i++) { cmp = RestrictionsCompare(params,rcnt,min,max,&gfunc->methods[i]); if (cmp == IDENTICAL) @@ -633,7 +672,7 @@ globle DEFMETHOD *FindMethodByRestrictions( ***********************************************************/ static intBool ValidGenericName( void *theEnv, - char *theDefgenericName) + const char *theDefgenericName) { struct constructHeader *theDefgeneric; #if DEFFUNCTION_CONSTRUCT @@ -687,7 +726,7 @@ static intBool ValidGenericName( See if the defgeneric already exists in this module (or is imported from another) ========================================= */ - theDefgeneric = (struct constructHeader *) EnvFindDefgeneric(theEnv,theDefgenericName); + theDefgeneric = (struct constructHeader *) EnvFindDefgenericInModule(theEnv,theDefgenericName); if (theDefgeneric != NULL) { /* =========================================== @@ -737,13 +776,14 @@ static void CreateDefaultGenericPPForm( void *theEnv, DEFGENERIC *gfunc) { - char *moduleName,*genericName,*buf; + const char *moduleName, *genericName; + char *buf; moduleName = EnvGetDefmoduleName(theEnv,(void *) ((struct defmodule *) EnvGetCurrentModule(theEnv))); genericName = EnvGetDefgenericName(theEnv,(void *) gfunc); buf = (char *) gm2(theEnv,(sizeof(char) * (strlen(moduleName) + strlen(genericName) + 17))); - sprintf(buf,"(defgeneric %s::%s)\n",moduleName,genericName); - SetDefgenericPPForm((void *) gfunc,buf); + gensprintf(buf,"(defgeneric %s::%s)\n",moduleName,genericName); + EnvSetDefgenericPPForm(theEnv,(void *) gfunc,buf); } #endif @@ -761,14 +801,14 @@ static void CreateDefaultGenericPPForm( *******************************************************/ static SYMBOL_HN *ParseMethodNameAndIndex( void *theEnv, - char *readSource, - unsigned *theIndex) + const char *readSource, + int *theIndex) { SYMBOL_HN *gname; *theIndex = 0; gname = GetConstructNameAndComment(theEnv,readSource,&DefgenericData(theEnv)->GenericInputToken,"defgeneric", - EnvFindDefgeneric,NULL,"&",TRUE,FALSE,TRUE); + EnvFindDefgenericInModule,NULL,"&",TRUE,FALSE,TRUE,TRUE); if (gname == NULL) return(NULL); if (GetType(DefgenericData(theEnv)->GenericInputToken) == INTEGER) @@ -786,7 +826,7 @@ static SYMBOL_HN *ParseMethodNameAndIndex( EnvPrintRouter(theEnv,WERROR,"Method index out of range.\n"); return(NULL); } - *theIndex = (unsigned) tmp; + *theIndex = tmp; PPCRAndIndent(theEnv); GetToken(theEnv,readSource,&DefgenericData(theEnv)->GenericInputToken); } @@ -820,7 +860,7 @@ static SYMBOL_HN *ParseMethodNameAndIndex( ************************************************************************/ static int ParseMethodParameters( void *theEnv, - char *readSource, + const char *readSource, EXPRESSION **params, SYMBOL_HN **wildcard) { @@ -933,7 +973,7 @@ static int ParseMethodParameters( ************************************************************/ static RESTRICTION *ParseRestriction( void *theEnv, - char *readSource) + const char *readSource) { EXPRESSION *types = NULL,*new_types, *typesbot,*tmp,*tmp2, @@ -1176,39 +1216,39 @@ static EXPRESSION *ValidType( EnvPrintRouter(theEnv,WERROR,"Unknown class in method.\n"); return(NULL); } - return(GenConstant(theEnv,EXTERNAL_ADDRESS,(void *) cls)); + return(GenConstant(theEnv,DEFCLASS_PTR,(void *) cls)); } #else if (strcmp(ValueToString(tname),INTEGER_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) INTEGER))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) INTEGER))); if (strcmp(ValueToString(tname),FLOAT_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) FLOAT))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) FLOAT))); if (strcmp(ValueToString(tname),SYMBOL_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) SYMBOL))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) SYMBOL))); if (strcmp(ValueToString(tname),STRING_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) STRING))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) STRING))); if (strcmp(ValueToString(tname),MULTIFIELD_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) MULTIFIELD))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) MULTIFIELD))); if (strcmp(ValueToString(tname),EXTERNAL_ADDRESS_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) EXTERNAL_ADDRESS))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) EXTERNAL_ADDRESS))); if (strcmp(ValueToString(tname),FACT_ADDRESS_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) FACT_ADDRESS))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) FACT_ADDRESS))); if (strcmp(ValueToString(tname),NUMBER_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) NUMBER_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) NUMBER_TYPE_CODE))); if (strcmp(ValueToString(tname),LEXEME_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) LEXEME_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) LEXEME_TYPE_CODE))); if (strcmp(ValueToString(tname),ADDRESS_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) ADDRESS_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) ADDRESS_TYPE_CODE))); if (strcmp(ValueToString(tname),PRIMITIVE_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) PRIMITIVE_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) PRIMITIVE_TYPE_CODE))); if (strcmp(ValueToString(tname),OBJECT_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) OBJECT_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) OBJECT_TYPE_CODE))); if (strcmp(ValueToString(tname),INSTANCE_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) INSTANCE_TYPE_CODE))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) INSTANCE_TYPE_CODE))); if (strcmp(ValueToString(tname),INSTANCE_NAME_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) INSTANCE_NAME))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) INSTANCE_NAME))); if (strcmp(ValueToString(tname),INSTANCE_ADDRESS_TYPE_NAME) == 0) - return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) INSTANCE_ADDRESS))); + return(GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) INSTANCE_ADDRESS))); PrintErrorID(theEnv,"GENRCPSR",14,FALSE); EnvPrintRouter(theEnv,WERROR,"Unknown type in method.\n"); @@ -1232,7 +1272,7 @@ static intBool RedundantClasses( void *c1, void *c2) { - char *tname; + const char *tname; #if OBJECT_SYSTEM if (HasSuperclass((DEFCLASS *) c1,(DEFCLASS *) c2)) @@ -1275,7 +1315,7 @@ static DEFGENERIC *AddGeneric( { DEFGENERIC *gfunc; - gfunc = (DEFGENERIC *) EnvFindDefgeneric(theEnv,ValueToString(name)); + gfunc = (DEFGENERIC *) EnvFindDefgenericInModule(theEnv,ValueToString(name)); if (gfunc != NULL) { *newGeneric = FALSE; @@ -1317,15 +1357,15 @@ static DEFMETHOD *AddGenericMethod( void *theEnv, DEFGENERIC *gfunc, int mposn, - unsigned mi) + short mi) { DEFMETHOD *narr; - register unsigned b, e; + long b, e; narr = (DEFMETHOD *) gm2(theEnv,(sizeof(DEFMETHOD) * (gfunc->mcnt+1))); for (b = e = 0 ; b < gfunc->mcnt ; b++ , e++) { - if (b == (unsigned) mposn) + if (b == mposn) e++; GenCopyMemory(DEFMETHOD,1,&narr[e],&gfunc->methods[b]); } @@ -1335,7 +1375,7 @@ static DEFMETHOD *AddGenericMethod( { narr[mposn].index = mi; if (mi >= gfunc->new_index) - gfunc->new_index = mi+1; + gfunc->new_index = (short) (mi+1); } narr[mposn].busy = 0; #if DEBUGGING_FUNCTIONS @@ -1465,7 +1505,8 @@ static int TypeListCompare( RESTRICTION *r1, RESTRICTION *r2) { - register int i,diff = FALSE; + long i; + int diff = FALSE; if ((r1->tcnt == 0) && (r2->tcnt == 0)) return(IDENTICAL); @@ -1473,7 +1514,7 @@ static int TypeListCompare( return(LOWER_PRECEDENCE); if (r2->tcnt == 0) return(HIGHER_PRECEDENCE); - for (i = 0 ; ((unsigned) i < r1->tcnt) && ((unsigned) i < r2->tcnt) ; i++) + for (i = 0 ; (i < r1->tcnt) && (i < r2->tcnt) ; i++) { if (r1->types[i] != r2->types[i]) { diff --git a/src/genrcpsr.h b/src/genrcpsr.h index e182a71..b684fe8 100644 --- a/src/genrcpsr.h +++ b/src/genrcpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -18,6 +18,30 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* If the last construct in a loaded file is a */ +/* deffunction or defmethod with no closing right */ +/* parenthesis, an error should be issued, but is */ +/* not. DR0872 */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_AND_SAVE */ +/* compiler flag is set to 0. */ +/* */ +/* Fixed typing issue when OBJECT_SYSTEM */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #ifndef _H_genrcpsr @@ -37,21 +61,18 @@ #define LOCALE extern #endif -LOCALE intBool ParseDefgeneric(void *,char *); -LOCALE intBool ParseDefmethod(void *,char *); -LOCALE DEFMETHOD *AddMethod(void *,DEFGENERIC *,DEFMETHOD *,int,unsigned,EXPRESSION *, - int,int,SYMBOL_HN *,EXPRESSION *,char *,int); -LOCALE void PackRestrictionTypes(void *,RESTRICTION *,EXPRESSION *); -LOCALE void DeleteTempRestricts(void *,EXPRESSION *); -LOCALE DEFMETHOD *FindMethodByRestrictions(DEFGENERIC *,EXPRESSION *,int, - SYMBOL_HN *,int *); - -#ifndef _GENRCPSR_SOURCE_ -#endif + LOCALE intBool ParseDefgeneric(void *,const char *); + LOCALE intBool ParseDefmethod(void *,const char *); + LOCALE DEFMETHOD *AddMethod(void *,DEFGENERIC *,DEFMETHOD *,int,short,EXPRESSION *, + int,int,SYMBOL_HN *,EXPRESSION *,char *,int); + LOCALE void PackRestrictionTypes(void *,RESTRICTION *,EXPRESSION *); + LOCALE void DeleteTempRestricts(void *,EXPRESSION *); + LOCALE DEFMETHOD *FindMethodByRestrictions(DEFGENERIC *,EXPRESSION *,int, + SYMBOL_HN *,int *); -#endif +#endif /* DEFGENERIC_CONSTRUCT && (! BLOAD_ONLY) && (! RUN_TIME) */ -#endif +#endif /* _H_genrcpsr */ diff --git a/src/globlbin.c b/src/globlbin.c index e351546..3e9a585 100644 --- a/src/globlbin.c +++ b/src/globlbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -14,10 +14,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ /*************************************************************/ #define _GLOBLBIN_SOURCE_ @@ -90,7 +94,7 @@ static void DeallocateDefglobalBloadData( void *theEnv) { #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) - unsigned long space; + size_t space; long i; for (i = 0; i < DefglobalBinaryData(theEnv)->NumberOfDefglobals; i++) @@ -100,12 +104,12 @@ static void DeallocateDefglobalBloadData( } space = DefglobalBinaryData(theEnv)->NumberOfDefglobals * sizeof(struct defglobal); - if (space != 0) - { genlongfree(theEnv,(void *) DefglobalBinaryData(theEnv)->DefglobalArray,space); } + if (space != 0) + { genfree(theEnv,(void *) DefglobalBinaryData(theEnv)->DefglobalArray,space); } space = DefglobalBinaryData(theEnv)->NumberOfDefglobalModules * sizeof(struct defglobalModule); - if (space != 0) - { genlongfree(theEnv,(void *) DefglobalBinaryData(theEnv)->ModuleArray,space); } + if (space != 0) + { genfree(theEnv,(void *) DefglobalBinaryData(theEnv)->ModuleArray,space); } #endif } @@ -177,7 +181,7 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; /*===========================================================*/ /* Only two data structures are saved as part of a defglobal */ @@ -186,9 +190,9 @@ static void BsaveStorage( /*===========================================================*/ space = sizeof(long) * 2; - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); - GenWrite(&DefglobalBinaryData(theEnv)->NumberOfDefglobals,(unsigned long) sizeof(long int),fp); - GenWrite(&DefglobalBinaryData(theEnv)->NumberOfDefglobalModules,(unsigned long) sizeof(long int),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&DefglobalBinaryData(theEnv)->NumberOfDefglobals,sizeof(long int),fp); + GenWrite(&DefglobalBinaryData(theEnv)->NumberOfDefglobalModules,sizeof(long int),fp); } /*********************************************/ @@ -199,7 +203,7 @@ static void BsaveBinaryItem( void *theEnv, FILE *fp) { - unsigned long int space; + size_t space; struct defglobal *theDefglobal; struct bsaveDefglobal newDefglobal; struct defmodule *theModule; @@ -213,7 +217,7 @@ static void BsaveBinaryItem( space = DefglobalBinaryData(theEnv)->NumberOfDefglobals * sizeof(struct bsaveDefglobal) + (DefglobalBinaryData(theEnv)->NumberOfDefglobalModules * sizeof(struct bsaveDefglobalModule)); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*=================================================*/ /* Write out each defglobal module data structure. */ @@ -230,7 +234,7 @@ static void BsaveBinaryItem( GetModuleItem(theEnv,NULL,FindModuleItem(theEnv,"defglobal")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&tempDefglobalModule.header, &theModuleItem->header); - GenWrite(&tempDefglobalModule,(unsigned long) sizeof(struct bsaveDefglobalModule),fp); + GenWrite(&tempDefglobalModule,sizeof(struct bsaveDefglobalModule),fp); } /*===========================*/ @@ -252,7 +256,7 @@ static void BsaveBinaryItem( &theDefglobal->header); newDefglobal.initial = HashedExpressionIndex(theEnv,theDefglobal->initial); - GenWrite(&newDefglobal,(unsigned long) sizeof(struct bsaveDefglobal),fp); + GenWrite(&newDefglobal,sizeof(struct bsaveDefglobal),fp); } } @@ -276,16 +280,16 @@ static void BsaveBinaryItem( static void BloadStorageDefglobals( void *theEnv) { - unsigned long int space; + size_t space; /*=======================================================*/ /* Determine the number of defglobal and defglobalModule */ /* data structures to be read. */ /*=======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&DefglobalBinaryData(theEnv)->NumberOfDefglobals,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DefglobalBinaryData(theEnv)->NumberOfDefglobalModules,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&DefglobalBinaryData(theEnv)->NumberOfDefglobals,sizeof(long int)); + GenReadBinary(theEnv,&DefglobalBinaryData(theEnv)->NumberOfDefglobalModules,sizeof(long int)); /*===================================*/ /* Allocate the space needed for the */ @@ -299,7 +303,7 @@ static void BloadStorageDefglobals( } space = DefglobalBinaryData(theEnv)->NumberOfDefglobalModules * sizeof(struct defglobalModule); - DefglobalBinaryData(theEnv)->ModuleArray = (struct defglobalModule *) genlongalloc(theEnv,space); + DefglobalBinaryData(theEnv)->ModuleArray = (struct defglobalModule *) genalloc(theEnv,space); /*===================================*/ /* Allocate the space needed for the */ @@ -312,8 +316,8 @@ static void BloadStorageDefglobals( return; } - space = (unsigned long) (DefglobalBinaryData(theEnv)->NumberOfDefglobals * sizeof(struct defglobal)); - DefglobalBinaryData(theEnv)->DefglobalArray = (struct defglobal *) genlongalloc(theEnv,space); + space = (DefglobalBinaryData(theEnv)->NumberOfDefglobals * sizeof(struct defglobal)); + DefglobalBinaryData(theEnv)->DefglobalArray = (struct defglobal *) genalloc(theEnv,space); } /******************************************************/ @@ -323,7 +327,7 @@ static void BloadStorageDefglobals( static void BloadBinaryItem( void *theEnv) { - unsigned long int space; + size_t space; /*======================================================*/ /* Read in the amount of space used by the binary image */ @@ -331,7 +335,7 @@ static void BloadBinaryItem( /* is not available in the version being run). */ /*======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); /*=============================================*/ /* Read in the defglobalModule data structures */ @@ -339,7 +343,7 @@ static void BloadBinaryItem( /*=============================================*/ BloadandRefresh(theEnv,DefglobalBinaryData(theEnv)->NumberOfDefglobalModules, - (unsigned) sizeof(struct bsaveDefglobalModule), + sizeof(struct bsaveDefglobalModule), UpdateDefglobalModule); /*=======================================*/ @@ -348,7 +352,7 @@ static void BloadBinaryItem( /*=======================================*/ BloadandRefresh(theEnv,DefglobalBinaryData(theEnv)->NumberOfDefglobals, - (unsigned) sizeof(struct bsaveDefglobal), + sizeof(struct bsaveDefglobal), UpdateDefglobal); } @@ -387,7 +391,7 @@ static void UpdateDefglobal( (int) sizeof(struct defglobal),(void *) DefglobalBinaryData(theEnv)->DefglobalArray); #if DEBUGGING_FUNCTIONS - DefglobalBinaryData(theEnv)->DefglobalArray[obji].watch = WatchGlobals; + DefglobalBinaryData(theEnv)->DefglobalArray[obji].watch = DefglobalData(theEnv)->WatchGlobals; #endif DefglobalBinaryData(theEnv)->DefglobalArray[obji].initial = HashedExpressionPointer(bdp->initial); DefglobalBinaryData(theEnv)->DefglobalArray[obji].current.type = RVOID; @@ -402,7 +406,7 @@ static void ClearBload( void *theEnv) { long i; - unsigned long space; + size_t space; /*=======================================================*/ /* Decrement in use counters for atomic values contained */ @@ -424,15 +428,15 @@ static void ClearBload( /*==============================================================*/ space = DefglobalBinaryData(theEnv)->NumberOfDefglobals * sizeof(struct defglobal); - if (space != 0) genlongfree(theEnv,(void *) DefglobalBinaryData(theEnv)->DefglobalArray,space); + if (space != 0) genfree(theEnv,(void *) DefglobalBinaryData(theEnv)->DefglobalArray,space); DefglobalBinaryData(theEnv)->NumberOfDefglobals = 0; - + /*=====================================================================*/ /* Deallocate the space used for the defglobal module data structures. */ /*=====================================================================*/ space = DefglobalBinaryData(theEnv)->NumberOfDefglobalModules * sizeof(struct defglobalModule); - if (space != 0) genlongfree(theEnv,(void *) DefglobalBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DefglobalBinaryData(theEnv)->ModuleArray,space); DefglobalBinaryData(theEnv)->NumberOfDefglobalModules = 0; } diff --git a/src/globlbin.h b/src/globlbin.h index f610cd4..23805bf 100644 --- a/src/globlbin.h +++ b/src/globlbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL BINARY HEADER FILE */ /*******************************************************/ @@ -13,10 +13,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ /*************************************************************/ #ifndef _H_globlbin @@ -41,13 +45,13 @@ struct bsaveDefglobalModule #define GLOBLBIN_DATA 60 struct defglobalBinaryData - { + { struct defglobal *DefglobalArray; long NumberOfDefglobals; struct defglobalModule *ModuleArray; long NumberOfDefglobalModules; }; - + #define DefglobalBinaryData(theEnv) ((struct defglobalBinaryData *) GetEnvironmentData(theEnv,GLOBLBIN_DATA)) #define DefglobalPointer(i) ((struct defglobal *) (&DefglobalBinaryData(theEnv)->DefglobalArray[i])) @@ -65,10 +69,7 @@ struct defglobalBinaryData LOCALE void DefglobalBinarySetup(void *); LOCALE void *BloadDefglobalModuleReference(void *,int); -#ifndef _GLOBLBIN_SOURCE_ - extern struct defglobal *DefglobalArray; -#endif -#endif +#endif /* _H_globlbin */ diff --git a/src/globlbsc.c b/src/globlbsc.c index 2372890..cfe8b9c 100644 --- a/src/globlbsc.c +++ b/src/globlbsc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -29,6 +30,17 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _GLOBLBSC_SOURCE_ @@ -59,19 +71,11 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void SaveDefglobals(void *,void *,char *); + static void SaveDefglobals(void *,void *,const char *); static void ResetDefglobalAction(void *,struct constructHeader *,void *); #if DEBUGGING_FUNCTIONS && (! RUN_TIME) static unsigned DefglobalWatchAccess(void *,int,unsigned,struct expr *); - static unsigned DefglobalWatchPrint(void *,char *,int,struct expr *); -#endif - -/****************************************/ -/* GLOBAL INTERNAL VARIABLE DEFINITIONS */ -/****************************************/ - -#if DEBUGGING_FUNCTIONS - globle unsigned WatchGlobals = OFF; + static unsigned DefglobalWatchPrint(void *,const char *,int,struct expr *); #endif /*****************************************************************/ @@ -91,7 +95,7 @@ globle void DefglobalBasicCommands( #if DEBUGGING_FUNCTIONS EnvDefineFunction2(theEnv,"list-defglobals",'v', PTIEF ListDefglobalsCommand,"ListDefglobalsCommand","01w"); EnvDefineFunction2(theEnv,"ppdefglobal",'v',PTIEF PPDefglobalCommand,"PPDefglobalCommand","11w"); - AddWatchItem(theEnv,"globals",0,&WatchGlobals,0,DefglobalWatchAccess,DefglobalWatchPrint); + AddWatchItem(theEnv,"globals",0,&DefglobalData(theEnv)->WatchGlobals,0,DefglobalWatchAccess,DefglobalWatchPrint); #endif #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) @@ -120,15 +124,12 @@ globle void ResetDefglobals( /* ResetDefglobalAction: Action to be applied to each */ /* defglobal construct during a reset command. */ /******************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void ResetDefglobalAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif struct defglobal *theDefglobal = (struct defglobal *) theConstruct; @@ -150,9 +151,9 @@ static void ResetDefglobalAction( static void SaveDefglobals( void *theEnv, void *theModule, - char *logicalName) + const char *logicalName) { - SaveConstruct(theEnv,theModule,logicalName,DefglobalData(theEnv)->DefglobalConstruct); + SaveConstruct(theEnv,theModule,logicalName,DefglobalData(theEnv)->DefglobalConstruct); } /********************************************/ @@ -162,7 +163,7 @@ static void SaveDefglobals( globle void UndefglobalCommand( void *theEnv) { - UndefconstructCommand(theEnv,"undefglobal",DefglobalData(theEnv)->DefglobalConstruct); + UndefconstructCommand(theEnv,"undefglobal",DefglobalData(theEnv)->DefglobalConstruct); } /************************************/ @@ -173,7 +174,7 @@ globle intBool EnvUndefglobal( void *theEnv, void *theDefglobal) { - return(Undefconstruct(theEnv,theDefglobal,DefglobalData(theEnv)->DefglobalConstruct)); + return(Undefconstruct(theEnv,theDefglobal,DefglobalData(theEnv)->DefglobalConstruct)); } /**************************************************/ @@ -183,8 +184,8 @@ globle intBool EnvUndefglobal( globle void GetDefglobalListFunction( void *theEnv, DATA_OBJECT_PTR returnValue) - { - GetConstructListFunction(theEnv,"get-defglobal-list",returnValue,DefglobalData(theEnv)->DefglobalConstruct); + { + GetConstructListFunction(theEnv,"get-defglobal-list",returnValue,DefglobalData(theEnv)->DefglobalConstruct); } /******************************************/ @@ -196,7 +197,7 @@ globle void EnvGetDefglobalList( DATA_OBJECT_PTR returnValue, void *theModule) { - GetConstructList(theEnv,returnValue,DefglobalData(theEnv)->DefglobalConstruct,(struct defmodule *) theModule); + GetConstructList(theEnv,returnValue,DefglobalData(theEnv)->DefglobalConstruct,(struct defmodule *) theModule); } /*************************************************/ @@ -205,8 +206,8 @@ globle void EnvGetDefglobalList( /*************************************************/ globle void *DefglobalModuleFunction( void *theEnv) - { - return(GetConstructModuleCommand(theEnv,"defglobal-module",DefglobalData(theEnv)->DefglobalConstruct)); + { + return(GetConstructModuleCommand(theEnv,"defglobal-module",DefglobalData(theEnv)->DefglobalConstruct)); } #if DEBUGGING_FUNCTIONS @@ -218,7 +219,7 @@ globle void *DefglobalModuleFunction( globle void PPDefglobalCommand( void *theEnv) { - PPConstructCommand(theEnv,"ppdefglobal",DefglobalData(theEnv)->DefglobalConstruct); + PPConstructCommand(theEnv,"ppdefglobal",DefglobalData(theEnv)->DefglobalConstruct); } /*************************************/ @@ -227,10 +228,10 @@ globle void PPDefglobalCommand( /*************************************/ globle int PPDefglobal( void *theEnv, - char *defglobalName, - char *logicalName) + const char *defglobalName, + const char *logicalName) { - return(PPConstruct(theEnv,defglobalName,logicalName,DefglobalData(theEnv)->DefglobalConstruct)); + return(PPConstruct(theEnv,defglobalName,logicalName,DefglobalData(theEnv)->DefglobalConstruct)); } /***********************************************/ @@ -249,7 +250,7 @@ globle void ListDefglobalsCommand( /***************************************/ globle void EnvListDefglobals( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheModule) { struct defmodule *theModule = (struct defmodule *) vTheModule; @@ -261,37 +262,31 @@ globle void EnvListDefglobals( /* EnvGetDefglobalWatch: C access routine for retrieving */ /* the current watch value of a defglobal. */ /*********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefglobalWatch( void *theEnv, void *theGlobal) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(((struct defglobal *) theGlobal)->watch); + return(((struct defglobal *) theGlobal)->watch); } /********************************************************/ /* EnvSetDeftemplateWatch: C access routine for setting */ /* the current watch value of a deftemplate. */ /********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefglobalWatch( void *theEnv, unsigned newState, void *theGlobal) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - ((struct defglobal *) theGlobal)->watch = newState; + ((struct defglobal *) theGlobal)->watch = newState; } #if ! RUN_TIME @@ -300,16 +295,13 @@ globle void EnvSetDefglobalWatch( /* DefglobalWatchAccess: Access routine for setting the */ /* watch flag of a defglobal via the watch command. */ /********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefglobalWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -321,16 +313,13 @@ static unsigned DefglobalWatchAccess( /* DefglobalWatchPrint: Access routine for printing which defglobals */ /* have their watch flag set via the list-watch-items command. */ /*********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefglobalWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -338,10 +327,55 @@ static unsigned DefglobalWatchPrint( EnvGetDefglobalWatch,EnvSetDefglobalWatch)); } -#endif +#endif /* ! RUN_TIME */ + +#endif /* DEBUGGING_FUNCTIONS */ + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void GetDefglobalList( + DATA_OBJECT_PTR returnValue, + void *theModule) + { + EnvGetDefglobalList(GetCurrentEnvironment(),returnValue,theModule); + } + +#if DEBUGGING_FUNCTIONS + +globle unsigned GetDefglobalWatch( + void *theGlobal) + { + return EnvGetDefglobalWatch(GetCurrentEnvironment(),theGlobal); + } + +globle void ListDefglobals( + const char *logicalName, + void *vTheModule) + { + EnvListDefglobals(GetCurrentEnvironment(),logicalName,vTheModule); + } + +globle void SetDefglobalWatch( + unsigned newState, + void *theGlobal) + { + EnvSetDefglobalWatch(GetCurrentEnvironment(),newState,theGlobal); + } #endif /* DEBUGGING_FUNCTIONS */ +globle intBool Undefglobal( + void *theDefglobal) + { + return EnvUndefglobal(GetCurrentEnvironment(),theDefglobal); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFGLOBAL_CONSTRUCT */ diff --git a/src/globlbsc.h b/src/globlbsc.h index 07e1582..313f6f3 100644 --- a/src/globlbsc.h +++ b/src/globlbsc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -12,14 +12,32 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ +/* Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_globlbsc @@ -39,20 +57,6 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetDefglobalList(theEnv,a,b) EnvGetDefglobalList(theEnv,a,b) -#define GetDefglobalWatch(theEnv,a) EnvGetDefglobalWatch(theEnv,a) -#define ListDefglobals(theEnv,a,b) EnvListDefglobals(theEnv,a,b) -#define SetDefglobalWatch(theEnv,a,b) EnvSetDefglobalWatch(theEnv,a,b) -#define Undefglobal(theEnv,a) EnvUndefglobal(theEnv,a) -#else -#define GetDefglobalList(a,b) EnvGetDefglobalList(GetCurrentEnvironment(),a,b) -#define GetDefglobalWatch(a) EnvGetDefglobalWatch(GetCurrentEnvironment(),a) -#define ListDefglobals(a,b) EnvListDefglobals(GetCurrentEnvironment(),a,b) -#define SetDefglobalWatch(a,b) EnvSetDefglobalWatch(GetCurrentEnvironment(),a,b) -#define Undefglobal(a) EnvUndefglobal(GetCurrentEnvironment(),a) -#endif - LOCALE void DefglobalBasicCommands(void *); LOCALE void UndefglobalCommand(void *); LOCALE intBool EnvUndefglobal(void *,void *); @@ -60,17 +64,27 @@ LOCALE void EnvGetDefglobalList(void *,DATA_OBJECT_PTR,void *); LOCALE void *DefglobalModuleFunction(void *); LOCALE void PPDefglobalCommand(void *); - LOCALE int PPDefglobal(void *,char *,char *); + LOCALE int PPDefglobal(void *,const char *,const char *); LOCALE void ListDefglobalsCommand(void *); - LOCALE void EnvListDefglobals(void *,char *,void *); +#if DEBUGGING_FUNCTIONS LOCALE unsigned EnvGetDefglobalWatch(void *,void *); + LOCALE void EnvListDefglobals(void *,const char *,void *); LOCALE void EnvSetDefglobalWatch(void *,unsigned,void *); +#endif LOCALE void ResetDefglobals(void *); -#ifndef _GLOBLBSC_SOURCE_ - extern unsigned WatchGlobals; -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE void GetDefglobalList(DATA_OBJECT_PTR,void *); +#if DEBUGGING_FUNCTIONS + LOCALE unsigned GetDefglobalWatch(void *); + LOCALE void ListDefglobals(const char *,void *); + LOCALE void SetDefglobalWatch(unsigned,void *); #endif + LOCALE intBool Undefglobal(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_globlbsc */ diff --git a/src/globlcmp.c b/src/globlcmp.c index 6200731..9934bbb 100644 --- a/src/globlcmp.c +++ b/src/globlcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -14,10 +14,20 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _GLOBLCMP_SOURCE_ @@ -38,7 +48,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int ConstructToCode(void *,char *,int,FILE *,int,int); + static int ConstructToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void DefglobalToCode(void *,FILE *,struct defglobal *, int,int,int); static void DefglobalModuleToCode(void *,FILE *,struct defmodule *,int,int,int); @@ -53,7 +63,7 @@ globle void DefglobalCompilerSetup( void *theEnv) { - DefglobalData(theEnv)->DefglobalCodeItem = + DefglobalData(theEnv)->DefglobalCodeItem = AddCodeGeneratorItem(theEnv,"defglobal",0,BeforeDefglobalsToCode, InitDefglobalsCode,ConstructToCode,2); } @@ -73,16 +83,13 @@ static void BeforeDefglobalsToCode( /* InitDefglobalsCode: Writes out initialization */ /* code for defglobals for a run-time module. */ /*************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void InitDefglobalsCode( void *theEnv, FILE *initFP, int imageID, int maxIndices) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(maxIndices) #pragma unused(imageID) #pragma unused(theEnv) @@ -96,7 +103,9 @@ static void InitDefglobalsCode( /***********************************************************/ static int ConstructToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -126,7 +135,7 @@ static int ConstructToCode( { EnvSetCurrentModule(theEnv,(void *) theModule); - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "struct defglobalModule",ModulePrefix(DefglobalData(theEnv)->DefglobalCodeItem), FALSE,NULL); @@ -145,7 +154,7 @@ static int ConstructToCode( theDefglobal != NULL; theDefglobal = (struct defglobal *) EnvGetNextDefglobal(theEnv,theDefglobal)) { - defglobalFile = OpenFileIfNeeded(theEnv,defglobalFile,fileName,fileID,imageID,&fileCount, + defglobalFile = OpenFileIfNeeded(theEnv,defglobalFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, defglobalArrayVersion,headerFP, "struct defglobal",ConstructPrefix(DefglobalData(theEnv)->DefglobalCodeItem), FALSE,NULL); @@ -201,9 +210,6 @@ static void CloseDefglobalFiles( /* DefglobalModuleToCode: Writes the C code representation */ /* of a single defglobal module to the specified file. */ /***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DefglobalModuleToCode( void *theEnv, FILE *theFile, @@ -212,7 +218,7 @@ static void DefglobalModuleToCode( int maxIndices, int moduleCount) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(moduleCount) #endif diff --git a/src/globlcmp.h b/src/globlcmp.h index 24e8084..d3409ab 100644 --- a/src/globlcmp.h +++ b/src/globlcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,16 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_globlcmp @@ -36,5 +46,5 @@ LOCALE void DefglobalCModuleReference(void *,FILE *,int,int,int); LOCALE void DefglobalCConstructReference(void *,FILE *,void *,int,int); -#endif +#endif /* _H_globlcmp */ diff --git a/src/globlcom.c b/src/globlcom.c index df45754..ae2e959 100644 --- a/src/globlcom.c +++ b/src/globlcom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL COMMANDS MODULE */ /*******************************************************/ @@ -16,10 +16,20 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _GLOBLCOM_SOURCE_ @@ -43,7 +53,7 @@ /***************************************/ #if DEBUGGING_FUNCTIONS - static void PrintDefglobalValueForm(void *,char *,void *); + static void PrintDefglobalValueForm(void *,const char *,void *); #endif /************************************************************/ @@ -64,7 +74,7 @@ globle void DefglobalCommandDefinitions( #endif #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -149,8 +159,8 @@ globle int GetResetGlobalsCommand( /****************************************/ globle intBool EnvGetResetGlobals( void *theEnv) - { - return(DefglobalData(theEnv)->ResetGlobals); + { + return(DefglobalData(theEnv)->ResetGlobals); } #if DEBUGGING_FUNCTIONS @@ -184,7 +194,7 @@ globle void ShowDefglobalsCommand( /***************************************/ globle void EnvShowDefglobals( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheModule) { struct defmodule *theModule = (struct defmodule *) vTheModule; @@ -257,7 +267,7 @@ globle void EnvShowDefglobals( /*****************************************************/ static void PrintDefglobalValueForm( void *theEnv, - char *logicalName, + const char *logicalName, void *vTheGlobal) { struct defglobal *theGlobal = (struct defglobal *) vTheGlobal; @@ -270,5 +280,35 @@ static void PrintDefglobalValueForm( #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool GetResetGlobals() + { + return EnvGetResetGlobals(GetCurrentEnvironment()); + } + +globle intBool SetResetGlobals( + int value) + { + return EnvSetResetGlobals(GetCurrentEnvironment(),value); + } + +#if DEBUGGING_FUNCTIONS + +globle void ShowDefglobals( + const char *logicalName, + void *vTheModule) + { + EnvShowDefglobals(GetCurrentEnvironment(),logicalName,vTheModule); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFGLOBAL_CONSTRUCT */ diff --git a/src/globlcom.h b/src/globlcom.h index 70ded39..5f16fde 100644 --- a/src/globlcom.h +++ b/src/globlcom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL COMMANDS HEADER FILE */ /*******************************************************/ @@ -13,12 +13,23 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_globlcom @@ -34,23 +45,23 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetResetGlobals(theEnv) EnvGetResetGlobals(theEnv) -#define SetResetGlobals(theEnv,a) EnvSetResetGlobals(theEnv,a) -#define ShowDefglobals(theEnv,a,b) EnvShowDefglobals(theEnv,a,b) -#else -#define GetResetGlobals() EnvGetResetGlobals(GetCurrentEnvironment()) -#define SetResetGlobals(a) EnvSetResetGlobals(GetCurrentEnvironment(),a) -#define ShowDefglobals(a,b) EnvShowDefglobals(GetCurrentEnvironment(),a,b) -#endif - LOCALE void DefglobalCommandDefinitions(void *); LOCALE int SetResetGlobalsCommand(void *); LOCALE intBool EnvSetResetGlobals(void *,int); LOCALE int GetResetGlobalsCommand(void *); LOCALE intBool EnvGetResetGlobals(void *); LOCALE void ShowDefglobalsCommand(void *); - LOCALE void EnvShowDefglobals(void *,char *,void *); + LOCALE void EnvShowDefglobals(void *,const char *,void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE intBool GetResetGlobals(void); + LOCALE intBool SetResetGlobals(int); +#if DEBUGGING_FUNCTIONS + LOCALE void ShowDefglobals(const char *,void *); #endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_globlcom */ + diff --git a/src/globldef.c b/src/globldef.c index a42fa70..eb9ea2b 100644 --- a/src/globldef.c +++ b/src/globldef.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFGLOBAL MODULE */ /*******************************************************/ @@ -14,9 +14,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ @@ -24,6 +25,24 @@ /* Corrected code to remove run-time program */ /* compiler warning. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _GLOBLDEF_SOURCE_ @@ -72,21 +91,23 @@ static void DecrementDefglobalBusyCount(void *,void *); static void DeallocateDefglobalData(void *); static void DestroyDefglobalAction(void *,struct constructHeader *,void *); +#if (! BLOAD_ONLY) static void DestroyDefglobal(void *,void *); +#endif /**************************************************************/ /* InitializeDefglobals: Initializes the defglobal construct. */ /**************************************************************/ globle void InitializeDefglobals( void *theEnv) - { + { struct entityRecord globalInfo = { "GBL_VARIABLE", GBL_VARIABLE,0,0,0, NULL, NULL, NULL, GetDefglobalValue2, NULL,NULL, - NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord defglobalPtrRecord = { "DEFGLOBAL_PTR", DEFGLOBAL_PTR,0,0,0, NULL,NULL,NULL, @@ -94,16 +115,16 @@ globle void InitializeDefglobals( NULL, DecrementDefglobalBusyCount, IncrementDefglobalBusyCount, - NULL,NULL,NULL,NULL }; - + NULL,NULL,NULL,NULL,NULL }; + AllocateEnvironmentData(theEnv,DEFGLOBAL_DATA,sizeof(struct defglobalData),DeallocateDefglobalData); - - memcpy(&DefglobalData(theEnv)->GlobalInfo,&globalInfo,sizeof(struct entityRecord)); - memcpy(&DefglobalData(theEnv)->DefglobalPtrRecord,&defglobalPtrRecord,sizeof(struct entityRecord)); + + memcpy(&DefglobalData(theEnv)->GlobalInfo,&globalInfo,sizeof(struct entityRecord)); + memcpy(&DefglobalData(theEnv)->DefglobalPtrRecord,&defglobalPtrRecord,sizeof(struct entityRecord)); DefglobalData(theEnv)->ResetGlobals = TRUE; DefglobalData(theEnv)->LastModuleIndex = -1; - + InstallPrimitive(theEnv,&DefglobalData(theEnv)->GlobalInfo,GBL_VARIABLE); InstallPrimitive(theEnv,&DefglobalData(theEnv)->DefglobalPtrRecord,DEFGLOBAL_PTR); @@ -129,12 +150,12 @@ static void DeallocateDefglobalData( #if ! RUN_TIME struct defglobalModule *theModuleItem; void *theModule; - + #if BLOAD || BLOAD_AND_BSAVE if (Bloaded(theEnv)) return; #endif - DoForAllConstructs(theEnv,DestroyDefglobalAction,DefglobalData(theEnv)->DefglobalModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDefglobalAction,DefglobalData(theEnv)->DefglobalModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); theModule != NULL; @@ -146,33 +167,30 @@ static void DeallocateDefglobalData( rtn_struct(theEnv,defglobalModule,theModuleItem); } #else - DoForAllConstructs(theEnv,DestroyDefglobalAction,DefglobalData(theEnv)->DefglobalModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDefglobalAction,DefglobalData(theEnv)->DefglobalModuleIndex,FALSE,NULL); #endif } - + /***************************************************/ /* DestroyDefglobalAction: Action used to remove */ /* defglobals as a result of DestroyEnvironment. */ /***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDefglobalAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif #if (! BLOAD_ONLY) struct defglobal *theDefglobal = (struct defglobal *) theConstruct; - + if (theDefglobal == NULL) return; DestroyDefglobal(theEnv,theDefglobal); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv,theConstruct) #endif #endif @@ -198,7 +216,7 @@ static void InitializeDefglobalModules( #else NULL, #endif - EnvFindDefglobal); + EnvFindDefglobalInModule); #if (! BLOAD_ONLY) && (! RUN_TIME) && DEFMODULE_CONSTRUCT AddPortConstructItem(theEnv,"defglobal",SYMBOL); @@ -210,8 +228,8 @@ static void InitializeDefglobalModules( /*************************************************/ static void *AllocateModule( void *theEnv) - { - return((void *) get_struct(theEnv,defglobalModule)); + { + return((void *) get_struct(theEnv,defglobalModule)); } /***********************************************/ @@ -243,9 +261,21 @@ globle struct defglobalModule *GetDefglobalModuleItem( /*****************************************************/ globle void *EnvFindDefglobal( void *theEnv, - char *defglobalName) - { - return(FindNamedConstruct(theEnv,defglobalName,DefglobalData(theEnv)->DefglobalConstruct)); + const char *defglobalName) + { + return(FindNamedConstructInModuleOrImports(theEnv,defglobalName,DefglobalData(theEnv)->DefglobalConstruct)); + } + +/*****************************************************/ +/* EnvFindDefglobalInModule: Searches for a defglobal in the */ +/* list of defglobals. Returns a pointer to the */ +/* defglobal if found, otherwise NULL. */ +/*****************************************************/ +globle void *EnvFindDefglobalInModule( + void *theEnv, + const char *defglobalName) + { + return(FindNamedConstructInModule(theEnv,defglobalName,DefglobalData(theEnv)->DefglobalConstruct)); } /********************************************************************/ @@ -256,8 +286,8 @@ globle void *EnvFindDefglobal( globle void *EnvGetNextDefglobal( void *theEnv, void *defglobalPtr) - { - return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) defglobalPtr,DefglobalData(theEnv)->DefglobalModuleIndex)); + { + return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) defglobalPtr,DefglobalData(theEnv)->DefglobalModuleIndex)); } /*********************************************************/ @@ -284,13 +314,9 @@ static void ReturnDefglobal( void *theEnv, void *vTheDefglobal) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vTheDefglobal) -#endif - #if (! BLOAD_ONLY) && (! RUN_TIME) struct defglobal *theDefglobal = (struct defglobal *) vTheDefglobal; - + if (theDefglobal == NULL) return; /*====================================*/ @@ -329,22 +355,18 @@ static void ReturnDefglobal( DefglobalData(theEnv)->ChangeToGlobals = TRUE; #endif } - + /************************************************************/ /* DestroyDefglobal: Returns the data structures associated */ /* with a defglobal construct to the pool of free memory. */ /************************************************************/ +#if (! BLOAD_ONLY) static void DestroyDefglobal( void *theEnv, void *vTheDefglobal) { -#if (MAC_MCW || IBM_MCW) && BLOAD_ONLY -#pragma unused(theEnv,vTheDefglobal) -#endif - -#if (! BLOAD_ONLY) struct defglobal *theDefglobal = (struct defglobal *) vTheDefglobal; - + if (theDefglobal == NULL) return; /*====================================*/ @@ -353,7 +375,7 @@ static void DestroyDefglobal( if (theDefglobal->current.type == MULTIFIELD) { ReturnMultifield(theEnv,(struct multifield *) theDefglobal->current.value); } - + #if (! RUN_TIME) /*===============================*/ @@ -369,9 +391,9 @@ static void DestroyDefglobal( rtn_struct(theEnv,defglobal,theDefglobal); #endif -#endif } - +#endif + /************************************************/ /* QSetDefglobalValue: Lowest level routine for */ /* setting a defglobal's value. */ @@ -440,9 +462,12 @@ globle void QSetDefglobalValue( DefglobalData(theEnv)->ChangeToGlobals = TRUE; - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } } /**************************************************************/ @@ -473,7 +498,7 @@ globle struct defglobal *QFindDefglobal( globle void EnvGetDefglobalValueForm( void *theEnv, char *buffer, - unsigned bufferLength, + size_t bufferLength, void *vTheGlobal) { struct defglobal *theGlobal = (struct defglobal *) vTheGlobal; @@ -491,8 +516,8 @@ globle void EnvGetDefglobalValueForm( /************************************************************/ globle int EnvGetGlobalsChanged( void *theEnv) - { - return(DefglobalData(theEnv)->ChangeToGlobals); + { + return(DefglobalData(theEnv)->ChangeToGlobals); } /*********************************************************/ @@ -502,7 +527,7 @@ globle void EnvSetGlobalsChanged( void *theEnv, int value) { - DefglobalData(theEnv)->ChangeToGlobals = value; + DefglobalData(theEnv)->ChangeToGlobals = value; } /**********************************************************/ @@ -608,7 +633,7 @@ globle int QGetDefglobalValue( /************************************************************/ globle intBool EnvGetDefglobalValue( void *theEnv, - char *variableName, + const char *variableName, DATA_OBJECT_PTR vPtr) { struct defglobal *theDefglobal; @@ -627,7 +652,7 @@ globle intBool EnvGetDefglobalValue( /****************************************************************/ globle intBool EnvSetDefglobalValue( void *theEnv, - char *variableName, + const char *variableName, DATA_OBJECT_PTR vPtr) { struct defglobal *theGlobal; @@ -657,15 +682,12 @@ static void DecrementDefglobalBusyCount( /* IncrementDefglobalBusyCount: Increments the busy count */ /* of a defglobal data structure. */ /**********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void IncrementDefglobalBusyCount( void *theEnv, void *vTheGlobal) { struct defglobal *theGlobal = (struct defglobal *) vTheGlobal; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -682,7 +704,7 @@ globle void UpdateDefglobalScope( int moduleCount; struct defmodule *theModule; struct defmoduleItemHeader *theItem; - + /*============================*/ /* Loop through every module. */ /*============================*/ @@ -805,6 +827,108 @@ globle void *GetNextDefglobalInScope( return(NULL); } +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDefglobalModule( + void *theEnv, + void *theDefglobal) + { + return GetConstructModuleName((struct constructHeader *) theDefglobal); + } + +globle const char *EnvGetDefglobalName( + void *theEnv, + void *theDefglobal) + { + return GetConstructNameString((struct constructHeader *) theDefglobal); + } + +globle const char *EnvGetDefglobalPPForm( + void *theEnv, + void *theDefglobal) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDefglobal); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *DefglobalModule( + void *theDefglobal) + { + return EnvDefglobalModule(GetCurrentEnvironment(),theDefglobal); + } + +globle void *FindDefglobal( + const char *defglobalName) + { + return EnvFindDefglobal(GetCurrentEnvironment(),defglobalName); + } + +globle const char *GetDefglobalName( + void *theDefglobal) + { + return EnvGetDefglobalName(GetCurrentEnvironment(),theDefglobal); + } + +globle const char *GetDefglobalPPForm( + void *theDefglobal) + { + return EnvGetDefglobalPPForm(GetCurrentEnvironment(),theDefglobal); + } + +globle intBool GetDefglobalValue( + const char *variableName, + DATA_OBJECT_PTR vPtr) + { + return EnvGetDefglobalValue(GetCurrentEnvironment(),variableName,vPtr); + } + +globle void GetDefglobalValueForm( + char *buffer, + unsigned bufferLength, + void *vTheGlobal) + { + EnvGetDefglobalValueForm(GetCurrentEnvironment(),buffer,bufferLength,vTheGlobal); + } + +globle int GetGlobalsChanged() + { + return EnvGetGlobalsChanged(GetCurrentEnvironment()); + } + +globle void *GetNextDefglobal( + void *defglobalPtr) + { + return EnvGetNextDefglobal(GetCurrentEnvironment(),defglobalPtr); + } + +globle intBool IsDefglobalDeletable( + void *ptr) + { + return EnvIsDefglobalDeletable(GetCurrentEnvironment(),ptr); + } + +globle intBool SetDefglobalValue( + const char *variableName, + DATA_OBJECT_PTR vPtr) + { + return EnvSetDefglobalValue(GetCurrentEnvironment(),variableName,vPtr); + } + +globle void SetGlobalsChanged( + int value) + { + EnvSetGlobalsChanged(GetCurrentEnvironment(),value); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFGLOBAL_CONSTRUCT */ diff --git a/src/globldef.h b/src/globldef.h index a4f60aa..e4f756f 100644 --- a/src/globldef.h +++ b/src/globldef.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFGLOBAL HEADER FILE */ /*******************************************************/ @@ -13,12 +13,35 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove run-time program */ +/* compiler warning. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_globldef @@ -49,10 +72,13 @@ #define DEFGLOBAL_DATA 1 struct defglobalData - { + { struct construct *DefglobalConstruct; - int DefglobalModuleIndex; - int ChangeToGlobals; + int DefglobalModuleIndex; + int ChangeToGlobals; +#if DEBUGGING_FUNCTIONS + unsigned WatchGlobals; +#endif intBool ResetGlobals; struct entityRecord GlobalInfo; struct entityRecord DefglobalPtrRecord; @@ -78,10 +104,6 @@ struct defglobalModule struct defmoduleItemHeader header; }; -#define EnvGetDefglobalName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDefglobalPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define EnvDefglobalModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - #define DefglobalData(theEnv) ((struct defglobalData *) GetEnvironmentData(theEnv,DEFGLOBAL_DATA)) #ifdef LOCALE @@ -94,52 +116,43 @@ struct defglobalModule #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DefglobalModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefglobal(theEnv,a) EnvFindDefglobal(theEnv,a) -#define GetDefglobalName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDefglobalPPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetDefglobalValue(theEnv,a,b) EnvGetDefglobalValue(theEnv,a,b) -#define GetDefglobalValueForm(theEnv,a,b,c) EnvGetDefglobalValueForm(theEnv,a,b,c) -#define GetGlobalsChanged(theEnv) EnvGetGlobalsChanged(theEnv) -#define GetNextDefglobal(theEnv,a) EnvGetNextDefglobal(theEnv,a) -#define IsDefglobalDeletable(theEnv,a) EnvIsDefglobalDeletable(theEnv,a) -#define SetDefglobalValue(theEnv,a,b) EnvSetDefglobalValue(theEnv,a,b) -#define SetGlobalsChanged(theEnv,a) EnvSetGlobalsChanged(theEnv,a) -#else -#define DefglobalModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefglobal(a) EnvFindDefglobal(GetCurrentEnvironment(),a) -#define GetDefglobalName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDefglobalPPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetDefglobalValue(a,b) EnvGetDefglobalValue(GetCurrentEnvironment(),a,b) -#define GetDefglobalValueForm(a,b,c) EnvGetDefglobalValueForm(GetCurrentEnvironment(),a,b,c) -#define GetGlobalsChanged() EnvGetGlobalsChanged(GetCurrentEnvironment()) -#define GetNextDefglobal(a) EnvGetNextDefglobal(GetCurrentEnvironment(),a) -#define IsDefglobalDeletable(a) EnvIsDefglobalDeletable(GetCurrentEnvironment(),a) -#define SetDefglobalValue(a,b) EnvSetDefglobalValue(GetCurrentEnvironment(),a,b) -#define SetGlobalsChanged(a) EnvSetGlobalsChanged(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeDefglobals(void *); - LOCALE void *EnvFindDefglobal(void *,char *); + LOCALE void *EnvFindDefglobal(void *,const char *); + LOCALE void *EnvFindDefglobalInModule(void *,const char *); LOCALE void *EnvGetNextDefglobal(void *,void *); LOCALE void CreateInitialFactDefglobal(void); LOCALE intBool EnvIsDefglobalDeletable(void *,void *); LOCALE struct defglobalModule *GetDefglobalModuleItem(void *,struct defmodule *); LOCALE void QSetDefglobalValue(void *,struct defglobal *,DATA_OBJECT_PTR,int); LOCALE struct defglobal *QFindDefglobal(void *,struct symbolHashNode *); - LOCALE void EnvGetDefglobalValueForm(void *,char *,unsigned,void *); + LOCALE void EnvGetDefglobalValueForm(void *,char *,size_t,void *); LOCALE int EnvGetGlobalsChanged(void *); LOCALE void EnvSetGlobalsChanged(void *,int); - LOCALE intBool EnvGetDefglobalValue(void *,char *,DATA_OBJECT_PTR); - LOCALE intBool EnvSetDefglobalValue(void *,char *,DATA_OBJECT_PTR); + LOCALE intBool EnvGetDefglobalValue(void *,const char *,DATA_OBJECT_PTR); + LOCALE intBool EnvSetDefglobalValue(void *,const char *,DATA_OBJECT_PTR); LOCALE void UpdateDefglobalScope(void *); LOCALE void *GetNextDefglobalInScope(void *,void *); LOCALE int QGetDefglobalValue(void *,void *,DATA_OBJECT_PTR); - -#ifndef _GLOBLDEF_SOURCE_ -#endif - -#endif + LOCALE const char *EnvDefglobalModule(void *,void *); + LOCALE const char *EnvGetDefglobalName(void *,void *); + LOCALE const char *EnvGetDefglobalPPForm(void *,void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE const char *DefglobalModule(void *); + LOCALE void *FindDefglobal(const char *); + LOCALE const char *GetDefglobalName(void *); + LOCALE const char *GetDefglobalPPForm(void *); + LOCALE intBool GetDefglobalValue(const char *,DATA_OBJECT_PTR); + LOCALE void GetDefglobalValueForm(char *,unsigned,void *); + LOCALE int GetGlobalsChanged(void); + LOCALE void *GetNextDefglobal(void *); + LOCALE intBool IsDefglobalDeletable(void *); + LOCALE intBool SetDefglobalValue(const char *,DATA_OBJECT_PTR); + LOCALE void SetGlobalsChanged(int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_globldef */ diff --git a/src/globlpsr.c b/src/globlpsr.c index 5ed23d0..1a5e6b8 100644 --- a/src/globlpsr.c +++ b/src/globlpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL PARSER MODULE */ /*******************************************************/ @@ -13,7 +13,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -22,6 +22,15 @@ /* Made the construct redefinition message more */ /* prominent. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ /*************************************************************/ #define _GLOBLPSR_SOURCE_ @@ -59,7 +68,7 @@ /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static intBool GetVariableDefinition(void *,char *,int *,int,struct token *); + static intBool GetVariableDefinition(void *,const char *,int *,int,struct token *); static void AddDefglobal(void *,SYMBOL_HN *,DATA_OBJECT_PTR,struct expr *); #endif @@ -69,13 +78,9 @@ /*********************************************************************/ globle intBool ParseDefglobal( void *theEnv, - char *readSource) + const char *readSource) { int defglobalError = FALSE; -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,readSource) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) struct token theToken; @@ -194,7 +199,7 @@ globle intBool ParseDefglobal( /***************************************************************/ static intBool GetVariableDefinition( void *theEnv, - char *readSource, + const char *readSource, int *defglobalError, int tokenRead, struct token *theToken) @@ -235,14 +240,16 @@ static intBool GetVariableDefinition( #if DEBUGGING_FUNCTIONS if ((EnvGetWatchItem(theEnv,"compilations") == ON) && GetPrintWhileLoading(theEnv)) { - if (QFindDefglobal(theEnv,variableName) != NULL) + const char *outRouter = WDIALOG; + if (QFindDefglobal(theEnv,variableName) != NULL) { + outRouter = WWARNING; PrintWarningID(theEnv,"CSTRCPSR",1,TRUE); - EnvPrintRouter(theEnv,WDIALOG,"Redefining defglobal: "); + EnvPrintRouter(theEnv,outRouter,"Redefining defglobal: "); } - else EnvPrintRouter(theEnv,WDIALOG,"Defining defglobal: "); - EnvPrintRouter(theEnv,WDIALOG,ValueToString(variableName)); - EnvPrintRouter(theEnv,WDIALOG,"\n"); + else EnvPrintRouter(theEnv,outRouter,"Defining defglobal: "); + EnvPrintRouter(theEnv,outRouter,ValueToString(variableName)); + EnvPrintRouter(theEnv,outRouter,"\n"); } else #endif @@ -387,7 +394,7 @@ static void AddDefglobal( /*=================================*/ #if DEBUGGING_FUNCTIONS - defglobalPtr->watch = GlobalHadWatch ? TRUE : WatchGlobals; + defglobalPtr->watch = GlobalHadWatch ? TRUE : DefglobalData(theEnv)->WatchGlobals; #endif /*======================================*/ @@ -487,7 +494,7 @@ globle intBool ReplaceGlobalVariable( /*****************************************************************/ globle void GlobalReferenceErrorMessage( void *theEnv, - char *variableName) + const char *variableName) { PrintErrorID(theEnv,"GLOBLPSR",1,TRUE); EnvPrintRouter(theEnv,WERROR,"\nGlobal variable ?*"); diff --git a/src/globlpsr.h b/src/globlpsr.h index f7bf524..7c697f0 100644 --- a/src/globlpsr.h +++ b/src/globlpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFGLOBAL PARSER HEADER FILE */ /*******************************************************/ @@ -18,6 +18,18 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Made the construct redefinition message more */ +/* prominent. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Moved WatchGlobals global to defglobalData. */ +/* */ /*************************************************************/ #ifndef _H_globlpsr @@ -42,11 +54,11 @@ struct defglobal; #define LOCALE extern #endif - LOCALE intBool ParseDefglobal(void *,char *); + LOCALE intBool ParseDefglobal(void *,const char *); LOCALE intBool ReplaceGlobalVariable(void *,struct expr *); - LOCALE void GlobalReferenceErrorMessage(void *,char *); + LOCALE void GlobalReferenceErrorMessage(void *,const char *); -#endif +#endif /* _H_globlpsr */ diff --git a/src/immthpsr.c b/src/immthpsr.c index cd12a0a..19e8150 100644 --- a/src/immthpsr.c +++ b/src/immthpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* IMPLICIT SYSTEM METHODS PARSING MODULE */ /*******************************************************/ @@ -10,16 +10,26 @@ /* Purpose: Parsing routines for Implicit System Methods */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Added pragmas to remove unused parameter */ /* warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -54,9 +64,9 @@ ========================================= ***************************************** */ -static void FormMethodsFromRestrictions(void *,DEFGENERIC *,char *,EXPRESSION *); +static void FormMethodsFromRestrictions(void *,DEFGENERIC *,const char *,EXPRESSION *); static RESTRICTION *ParseRestrictionType(void *,int); -static EXPRESSION *GenTypeExpression(void *,EXPRESSION *,int,int,char *); +static EXPRESSION *GenTypeExpression(void *,EXPRESSION *,int,int,const char *); /* ========================================= ***************************************** @@ -112,7 +122,7 @@ globle void AddImplicitMethods( static void FormMethodsFromRestrictions( void *theEnv, DEFGENERIC *gfunc, - char *rstring, + const char *rstring, EXPRESSION *actions) { DEFMETHOD *meth; @@ -253,7 +263,7 @@ static void FormMethodsFromRestrictions( rptr->query->argList = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"length$")); rptr->query->argList->argList = GenProcWildcardReference(theEnv,min + i + 1); rptr->query->argList->nextArg = - GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) (max - min - i))); + GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) (max - min - i))); } tmp = get_struct(theEnv,expr); tmp->argList = (EXPRESSION *) rptr; @@ -377,22 +387,19 @@ static RESTRICTION *ParseRestrictionType( environment, they are pointers to classes ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static EXPRESSION *GenTypeExpression( void *theEnv, EXPRESSION *top, int nonCOOLCode, int primitiveCode, - char *COOLName) + const char *COOLName) { #if OBJECT_SYSTEM -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(nonCOOLCode) #endif #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(primitiveCode) #pragma unused(COOLName) #endif @@ -405,7 +412,7 @@ static EXPRESSION *GenTypeExpression( else tmp = GenConstant(theEnv,0,(void *) LookupDefclassByMdlOrScope(theEnv,COOLName)); #else - tmp = GenConstant(theEnv,0,EnvAddLong(theEnv,(long) nonCOOLCode)); + tmp = GenConstant(theEnv,0,EnvAddLong(theEnv,(long long) nonCOOLCode)); #endif tmp->nextArg = top; return(tmp); diff --git a/src/immthpsr.h b/src/immthpsr.h index ff2ccb6..140e530 100644 --- a/src/immthpsr.h +++ b/src/immthpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,21 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_immthpsr @@ -35,14 +44,11 @@ #define LOCALE extern #endif -LOCALE void AddImplicitMethods(void *,DEFGENERIC *); + LOCALE void AddImplicitMethods(void *,DEFGENERIC *); -#ifndef _IMMTHPSR_SOURCE_ -#endif +#endif /* DEFGENERIC_CONSTRUCT && (! BLOAD_ONLY) && (! RUN_TIME) */ -#endif - -#endif +#endif /* _H_immthpsr */ diff --git a/src/incrrset.c b/src/incrrset.c index 2c6b1ad..6eee578 100644 --- a/src/incrrset.c +++ b/src/incrrset.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INCREMENTAL RESET MODULE */ /*******************************************************/ @@ -17,12 +17,25 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed INCREMENTAL_RESET compilation flag. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for hashed alpha memories and */ +/* other join network changes. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Modified EnvSetIncrementalReset to check for */ +/* the existance of rules. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _INCRRSET_SOURCE_ @@ -43,6 +56,7 @@ #include "evaluatn.h" #include "pattern.h" #include "router.h" +#include "reteutil.h" #include "incrrset.h" @@ -52,8 +66,10 @@ #if (! RUN_TIME) && (! BLOAD_ONLY) static void MarkNetworkForIncrementalReset(void *,struct defrule *,int); - static void CheckForPrimableJoins(void *,struct defrule *); - static void PrimeJoin(void *,struct joinNode *); + static void MarkJoinsForIncrementalReset(void *,struct joinNode *,int); + static void CheckForPrimableJoins(void *,struct defrule *,struct joinNode *); + static void PrimeJoinFromLeftMemory(void *,struct joinNode *); + static void PrimeJoinFromRightMemory(void *,struct joinNode *); static void MarkPatternForIncrementalReset(void *,int,struct patternNodeHeader *,int); #endif @@ -64,10 +80,6 @@ globle void IncrementalReset( void *theEnv, struct defrule *tempRule) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,tempRule) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) struct defrule *tempPtr; struct patternParser *theParser; @@ -100,7 +112,7 @@ globle void IncrementalReset( for (tempPtr = tempRule; tempPtr != NULL; tempPtr = tempPtr->disjunct) - { CheckForPrimableJoins(theEnv,tempPtr); } + { CheckForPrimableJoins(theEnv,tempPtr,tempPtr->lastJoin); } /*===============================================*/ /* Filter existing data entities through the new */ @@ -141,9 +153,6 @@ static void MarkNetworkForIncrementalReset( struct defrule *tempRule, int value) { - struct joinNode *joinPtr; - struct patternNodeHeader *patternPtr; - /*============================================*/ /* Loop through each of the rule's disjuncts. */ /*============================================*/ @@ -151,25 +160,49 @@ static void MarkNetworkForIncrementalReset( for (; tempRule != NULL; tempRule = tempRule->disjunct) - { - /*============================================*/ - /* Loop through each of the disjunct's joins. */ - /*============================================*/ + { MarkJoinsForIncrementalReset(theEnv,tempRule->lastJoin,value); } + } - for (joinPtr = tempRule->lastJoin; - joinPtr != NULL; - joinPtr = GetPreviousJoin(joinPtr)) +/**********************************************************************/ +/* MarkJoinsForIncrementalReset: Coordinates marking the initialize */ +/* flags in the pattern and join networks both before and after an */ +/* incremental reset. */ +/**********************************************************************/ +static void MarkJoinsForIncrementalReset( + void *theEnv, + struct joinNode *joinPtr, + int value) + { + struct patternNodeHeader *patternPtr; + + for (; + joinPtr != NULL; + joinPtr = joinPtr->lastLevel) + { + if (joinPtr->ruleToActivate != NULL) { - /*================*/ - /* Mark the join. */ - /*================*/ + joinPtr->marked = FALSE; + joinPtr->initialize = value; + continue; + } - joinPtr->marked = FALSE; /* GDR 6.05 */ - if ((joinPtr->initialize) && (joinPtr->joinFromTheRight == FALSE)) + if (joinPtr->joinFromTheRight) + { MarkJoinsForIncrementalReset(theEnv,(struct joinNode *) joinPtr->rightSideEntryStructure,value); } + + /*================*/ + /* Mark the join. */ + /*================*/ + + joinPtr->marked = FALSE; /* GDR 6.05 */ + + if (joinPtr->initialize) + { + joinPtr->initialize = value; + if (joinPtr->joinFromTheRight == FALSE) { - joinPtr->initialize = value; patternPtr = (struct patternNodeHeader *) GetPatternForJoin(joinPtr); - MarkPatternForIncrementalReset(theEnv,(int) joinPtr->rhsType,patternPtr,value); + if (patternPtr != NULL) + { MarkPatternForIncrementalReset(theEnv,(int) joinPtr->rhsType,patternPtr,value); } } } } @@ -185,71 +218,79 @@ static void MarkNetworkForIncrementalReset( /*******************************************************************************/ static void CheckForPrimableJoins( void *theEnv, - struct defrule *tempRule) + struct defrule *tempRule, + struct joinNode *joinPtr) { - struct joinNode *joinPtr; - struct partialMatch *theList; - /*========================================*/ /* Loop through each of the rule's joins. */ /*========================================*/ - for (joinPtr = tempRule->lastJoin; + for (; joinPtr != NULL; - joinPtr = GetPreviousJoin(joinPtr)) + joinPtr = joinPtr->lastLevel) { /*===============================*/ /* Update the join if necessary. */ /*===============================*/ - if ((joinPtr->initialize) && (! joinPtr->marked)) /* GDR 6.05 */ + if ((joinPtr->initialize) && (! joinPtr->marked)) { if (joinPtr->firstJoin == TRUE) { - if (((struct patternNodeHeader *) GetPatternForJoin(joinPtr))->initialize == FALSE) + if (joinPtr->joinFromTheRight == FALSE) { - PrimeJoin(theEnv,joinPtr); - joinPtr->marked = TRUE; /* GDR 6.05 */ + if ((joinPtr->rightSideEntryStructure == NULL) || + (joinPtr->patternIsNegated) || + (((struct patternNodeHeader *) joinPtr->rightSideEntryStructure)->initialize == FALSE)) + { + PrimeJoinFromLeftMemory(theEnv,joinPtr); + joinPtr->marked = TRUE; + } + } + else + { + PrimeJoinFromRightMemory(theEnv,joinPtr); + joinPtr->marked = TRUE; } } else if (joinPtr->lastLevel->initialize == FALSE) { - PrimeJoin(theEnv,joinPtr); - joinPtr->marked = TRUE; /* GDR 6.05 */ + PrimeJoinFromLeftMemory(theEnv,joinPtr); + joinPtr->marked = TRUE; + } + else if ((joinPtr->joinFromTheRight) && + (((struct joinNode *) joinPtr->rightSideEntryStructure)->initialize == FALSE)) + { + PrimeJoinFromRightMemory(theEnv,joinPtr); + joinPtr->marked = TRUE; } } - /*================================================================*/ - /* If the join is associated with a rule activation (i.e. partial */ - /* matches that reach this join cause an activation to be placed */ - /* on the agenda), then add activations to the agenda for the */ - /* rule being incrementally reset. */ - /*================================================================*/ - - else if (joinPtr->ruleToActivate == tempRule) - { - for (theList = joinPtr->beta; - theList != NULL; - theList = theList->next) - { AddActivation(theEnv,tempRule,theList); } - } + if (joinPtr->joinFromTheRight) + { CheckForPrimableJoins(theEnv,tempRule,(struct joinNode *) joinPtr->rightSideEntryStructure); } } } /****************************************************************************/ -/* PrimeJoin: Updates a join in a rule for an incremental reset. Joins are */ -/* updated by "priming" them only if the join (or its associated pattern) */ -/* is shared with other rules that have already been incrementally reset. */ -/* A join for a new rule will be updated if it is marked for */ -/* initialization and either its parent join or its associated entry */ -/* pattern node has not been marked for initialization. */ +/* PrimeJoinFromLeftMemory: Updates a join in a rule for an incremental */ +/* reset. Joins are updated by "priming" them only if the join (or its */ +/* associated pattern) is shared with other rules that have already been */ +/* incrementally reset. A join for a new rule will be updated if it is */ +/* marked for initialization and either its parent join or its associated */ +/* entry pattern node has not been marked for initialization. */ /****************************************************************************/ -static void PrimeJoin( +static void PrimeJoinFromLeftMemory( void *theEnv, struct joinNode *joinPtr) { - struct partialMatch *theList; - + struct partialMatch *theList, *linker; + struct alphaMemoryHash *listOfHashNodes; + unsigned long b; + unsigned long hashValue; + struct betaMemory *theMemory; + struct partialMatch *notParent; + struct joinLink *tempLink; + /*===========================================================*/ /* If the join is the first join of a rule, then send all of */ /* the partial matches from the alpha memory of the pattern */ @@ -259,31 +300,196 @@ static void PrimeJoin( if (joinPtr->firstJoin == TRUE) { - for (theList = ((struct patternNodeHeader *) joinPtr->rightSideEntryStructure)->alphaMemory; + if (joinPtr->rightSideEntryStructure == NULL) + { NetworkAssert(theEnv,joinPtr->rightMemory->beta[0],joinPtr); } + else if (joinPtr->patternIsNegated) + { + notParent = joinPtr->leftMemory->beta[0]; + + if (joinPtr->secondaryNetworkTest != NULL) + { + if (EvaluateSecondaryNetworkTest(theEnv,notParent,joinPtr) == FALSE) + { return; } + } + + for (listOfHashNodes = ((struct patternNodeHeader *) joinPtr->rightSideEntryStructure)->firstHash; + listOfHashNodes != NULL; + listOfHashNodes = listOfHashNodes->nextHash) + { + if (listOfHashNodes->alphaMemory != NULL) + { + AddBlockedLink(notParent,listOfHashNodes->alphaMemory); + return; + } + } + + EPMDrive(theEnv,notParent,joinPtr,NETWORK_ASSERT); + } + else + { + for (listOfHashNodes = ((struct patternNodeHeader *) joinPtr->rightSideEntryStructure)->firstHash; + listOfHashNodes != NULL; + listOfHashNodes = listOfHashNodes->nextHash) + { + for (theList = listOfHashNodes->alphaMemory; + theList != NULL; + theList = theList->nextInMemory) + { NetworkAssert(theEnv,theList,joinPtr); } + } + } + return; + } + + /*========================================*/ + /* Find another beta memory from which we */ + /* can retrieve the partial matches. */ + /*========================================*/ + + tempLink = joinPtr->lastLevel->nextLinks; + + while (tempLink != NULL) + { + if ((tempLink->join != joinPtr) && + (tempLink->join->initialize == FALSE)) + { break; } + + tempLink = tempLink->next; + } + + if (tempLink == NULL) return; + + if (tempLink->enterDirection == LHS) + { theMemory = tempLink->join->leftMemory; } + else + { theMemory = tempLink->join->rightMemory; } + + /*============================================*/ + /* Send all partial matches from the selected */ + /* beta memory to the new join. */ + /*============================================*/ + + for (b = 0; b < theMemory->size; b++) + { + for (theList = theMemory->beta[b]; theList != NULL; - theList = theList->next) - { NetworkAssert(theEnv,theList,joinPtr,RHS); } + theList = theList->nextInMemory) + { + linker = CopyPartialMatch(theEnv,theList); + + if (joinPtr->leftHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,joinPtr->leftHash,linker,NULL,joinPtr); } + else + { hashValue = 0; } + + UpdateBetaPMLinks(theEnv,linker,theList->leftParent,theList->rightParent,joinPtr,hashValue,LHS); + + NetworkAssertLeft(theEnv,linker,joinPtr,NETWORK_ASSERT); + } + } + } + +/****************************************************************************/ +/* PrimeJoinFromRightMemory: Updates a join in a rule for an incremental */ +/* reset. Joins are updated by "priming" them only if the join (or its */ +/* associated pattern) is shared with other rules that have already been */ +/* incrementally reset. A join for a new rule will be updated if it is */ +/* marked for initialization and either its parent join or its associated */ +/* entry pattern node has not been marked for initialization. */ +/****************************************************************************/ +static void PrimeJoinFromRightMemory( + void *theEnv, + struct joinNode *joinPtr) + { + struct partialMatch *theList, *linker; + unsigned long b; + struct betaMemory *theMemory; + unsigned long hashValue; + struct joinLink *tempLink; + struct partialMatch *notParent; + + /*=======================================*/ + /* This should be a join from the right. */ + /*=======================================*/ + + if (joinPtr->joinFromTheRight == FALSE) + { return; } + + /*========================================*/ + /* Find another beta memory from which we */ + /* can retrieve the partial matches. */ + /*========================================*/ + + tempLink = ((struct joinNode *) joinPtr->rightSideEntryStructure)->nextLinks; + while (tempLink != NULL) + { + if ((tempLink->join != joinPtr) && + (tempLink->join->initialize == FALSE)) + { break; } + + tempLink = tempLink->next; + } + + if (tempLink == NULL) + { + if (joinPtr->firstJoin && + (joinPtr->rightMemory->beta[0] == NULL) && + (! joinPtr->patternIsExists)) + { + notParent = joinPtr->leftMemory->beta[0]; + + if (joinPtr->secondaryNetworkTest != NULL) + { + if (EvaluateSecondaryNetworkTest(theEnv,notParent,joinPtr) == FALSE) + { return; } + } + + EPMDrive(theEnv,notParent,joinPtr,NETWORK_ASSERT); + } + return; } - /*======================================================*/ - /* If the join already has partial matches in its beta */ - /* memory, then don't bother priming it. I don't recall */ - /* if this situation is possible. */ - /*======================================================*/ + if (tempLink->enterDirection == LHS) + { theMemory = tempLink->join->leftMemory; } + else + { theMemory = tempLink->join->rightMemory; } + + /*============================================*/ + /* Send all partial matches from the selected */ + /* beta memory to the new join. */ + /*============================================*/ + + for (b = 0; b < theMemory->size; b++) + { + for (theList = theMemory->beta[b]; + theList != NULL; + theList = theList->nextInMemory) + { + linker = CopyPartialMatch(theEnv,theList); - if (joinPtr->beta != NULL) return; + if (joinPtr->rightHash != NULL) + { hashValue = BetaMemoryHashValue(theEnv,joinPtr->rightHash,linker,NULL,joinPtr); } + else + { hashValue = 0; } - /*================================================================*/ - /* Send all partial matches from the preceding join to this join. */ - /*================================================================*/ + UpdateBetaPMLinks(theEnv,linker,theList->leftParent,theList->rightParent,joinPtr,hashValue,RHS); + NetworkAssert(theEnv,linker,joinPtr); + } + } - for (theList = joinPtr->lastLevel->beta; - theList != NULL; - theList = theList->next) + if (joinPtr->firstJoin && + (joinPtr->rightMemory->beta[0] == NULL) && + (! joinPtr->patternIsExists)) { - if (! theList->counterf) /* 6.05 incremental reset bug fix */ - { NetworkAssert(theEnv,theList,joinPtr,LHS); } + notParent = joinPtr->leftMemory->beta[0]; + + if (joinPtr->secondaryNetworkTest != NULL) + { + if (EvaluateSecondaryNetworkTest(theEnv,notParent,joinPtr) == FALSE) + { return; } + } + + EPMDrive(theEnv,notParent,joinPtr,NETWORK_ASSERT); } } @@ -300,7 +506,7 @@ static void MarkPatternForIncrementalReset( int value) { struct patternParser *tempParser; - + tempParser = GetPatternParser(theEnv,rhsType); if (tempParser != NULL) @@ -318,7 +524,7 @@ static void MarkPatternForIncrementalReset( /********************************************/ globle intBool EnvGetIncrementalReset( void *theEnv) - { + { return(EngineData(theEnv)->IncrementalResetFlag); } @@ -331,9 +537,34 @@ globle intBool EnvSetIncrementalReset( int value) { int ov; + struct defmodule *theModule; + + /*============================================*/ + /* The incremental reset behavior can only be */ + /* changed if there are no existing rules. */ + /*============================================*/ + + SaveCurrentModule(theEnv); + + for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL); + theModule != NULL; + theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule)) + { + EnvSetCurrentModule(theEnv,(void *) theModule); + if (EnvGetNextDefrule(theEnv,NULL) != NULL) + { + RestoreCurrentModule(theEnv); + return(-1); + } + } + + RestoreCurrentModule(theEnv); + + /*====================================*/ + /* Change the incremental reset flag. */ + /*====================================*/ ov = EngineData(theEnv)->IncrementalResetFlag; - if (EnvGetNextDefrule(theEnv,NULL) != NULL) return(-1); EngineData(theEnv)->IncrementalResetFlag = value; return(ov); } @@ -347,6 +578,7 @@ globle int SetIncrementalResetCommand( { int oldValue; DATA_OBJECT argPtr; + struct defmodule *theModule; oldValue = EnvGetIncrementalReset(theEnv); @@ -362,14 +594,25 @@ globle int SetIncrementalResetCommand( /* changed when rules are loaded. */ /*=========================================*/ - if (EnvGetNextDefrule(theEnv,NULL) != NULL) + SaveCurrentModule(theEnv); + + for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL); + theModule != NULL; + theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule)) { - PrintErrorID(theEnv,"INCRRSET",1,FALSE); - EnvPrintRouter(theEnv,WERROR,"The incremental reset behavior cannot be changed with rules loaded.\n"); - SetEvaluationError(theEnv,TRUE); - return(oldValue); + EnvSetCurrentModule(theEnv,(void *) theModule); + if (EnvGetNextDefrule(theEnv,NULL) != NULL) + { + RestoreCurrentModule(theEnv); + PrintErrorID(theEnv,"INCRRSET",1,FALSE); + EnvPrintRouter(theEnv,WERROR,"The incremental reset behavior cannot be changed with rules loaded.\n"); + SetEvaluationError(theEnv,TRUE); + return(oldValue); + } } + RestoreCurrentModule(theEnv); + /*==================================================*/ /* The symbol FALSE disables incremental reset. Any */ /* other value enables incremental reset. */ @@ -406,4 +649,23 @@ globle int GetIncrementalResetCommand( return(oldValue); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool GetIncrementalReset() + { + return EnvGetIncrementalReset(GetCurrentEnvironment()); + } + +globle intBool SetIncrementalReset( + int value) + { + return EnvSetIncrementalReset(GetCurrentEnvironment(),value); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFRULE_CONSTRUCT */ diff --git a/src/incrrset.h b/src/incrrset.h index dcb07f6..145ed60 100644 --- a/src/incrrset.h +++ b/src/incrrset.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INCREMENTAL RESET HEADER FILE */ /*******************************************************/ @@ -18,7 +18,23 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Added support for hashed alpha memories and */ +/* other join network changes. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Modified EnvSetIncrementalReset to check for */ +/* the existance of rules. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -40,21 +56,20 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetIncrementalReset(theEnv) EnvGetIncrementalReset(theEnv) -#define SetIncrementalReset(theEnv,a) EnvSetIncrementalReset(theEnv,a) -#else -#define GetIncrementalReset() EnvGetIncrementalReset(GetCurrentEnvironment()) -#define SetIncrementalReset(a) EnvSetIncrementalReset(GetCurrentEnvironment(),a) -#endif - LOCALE void IncrementalReset(void *,struct defrule *); LOCALE intBool EnvGetIncrementalReset(void *); LOCALE intBool EnvSetIncrementalReset(void *,intBool); LOCALE int GetIncrementalResetCommand(void *); LOCALE int SetIncrementalResetCommand(void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool GetIncrementalReset(void); + LOCALE intBool SetIncrementalReset(int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_incrrset */ diff --git a/src/inherpsr.c b/src/inherpsr.c index 4543aa3..cf3f20b 100644 --- a/src/inherpsr.c +++ b/src/inherpsr.c @@ -1,22 +1,27 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* MULTIPLE INHERITANCE PARSER MODULE */ /*******************************************************/ -/**************************************************************/ -/* Purpose: Parsing Routines for Multiple Inheritance */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* */ -/**************************************************************/ +/*************************************************************/ +/* Purpose: Parsing Routines for Multiple Inheritance */ +/* */ +/* Principal Programmer(s): */ +/* Brian L. Dantes */ +/* */ +/* Contributing Programmer(s): */ +/* */ +/* Revision History: */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/*************************************************************/ /* ========================================= ***************************************** @@ -67,10 +72,10 @@ struct successor ***************************************** */ static PARTIAL_ORDER *InitializePartialOrderTable(void *,PARTIAL_ORDER *,PACKED_CLASS_LINKS *); -static void RecordPartialOrders(void *,PARTIAL_ORDER *,DEFCLASS *,PACKED_CLASS_LINKS *,unsigned); +static void RecordPartialOrders(void *,PARTIAL_ORDER *,DEFCLASS *,PACKED_CLASS_LINKS *,long); static PARTIAL_ORDER *FindPartialOrder(PARTIAL_ORDER *,DEFCLASS *); static void PrintPartialOrderLoop(void *,PARTIAL_ORDER *); -static void PrintClassLinks(void *,char *,char *,CLASS_LINK *); +static void PrintClassLinks(void *,const char *,const char *,CLASS_LINK *); /* ========================================= ***************************************** @@ -113,7 +118,7 @@ static void PrintClassLinks(void *,char *,char *,CLASS_LINK *); ***************************************************************/ globle PACKED_CLASS_LINKS *ParseSuperclasses( void *theEnv, - char *readSource, + const char *readSource, SYMBOL_HN *newClassName) { CLASS_LINK *clink = NULL,*cbot = NULL,*ctmp; @@ -314,7 +319,7 @@ globle PACKED_CLASS_LINKS *FindPrecedenceList( SUCCESSOR *stmp; CLASS_LINK *ptop,*pbot,*ptmp; PACKED_CLASS_LINKS *plinks; - register unsigned i; + long i; /* ===================================================================== Recursively add all superclasses in a pre-order depth-first traversal @@ -547,7 +552,7 @@ static PARTIAL_ORDER *InitializePartialOrderTable( PACKED_CLASS_LINKS *supers) { register PARTIAL_ORDER *pop,*poprv; - register unsigned i; + long i; for (i = 0 ; i < supers->classCount ; i++) { @@ -626,7 +631,7 @@ static void RecordPartialOrders( PARTIAL_ORDER *po_table, DEFCLASS *cls, PACKED_CLASS_LINKS *successors, - unsigned starti) + long starti) { register PARTIAL_ORDER *clspo; register SUCCESSOR *stmp; @@ -819,8 +824,8 @@ static void PrintPartialOrderLoop( ***************************************************/ static void PrintClassLinks( void *theEnv, - char *logicalName, - char *title, + const char *logicalName, + const char *title, CLASS_LINK *clink) { if (title != NULL) diff --git a/src/inherpsr.h b/src/inherpsr.h index f3a70d8..b126c5d 100644 --- a/src/inherpsr.h +++ b/src/inherpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,17 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_inherpsr @@ -37,16 +42,13 @@ #define LOCALE extern #endif -LOCALE PACKED_CLASS_LINKS *ParseSuperclasses(void *,char *,SYMBOL_HN *); -LOCALE PACKED_CLASS_LINKS *FindPrecedenceList(void *,DEFCLASS *,PACKED_CLASS_LINKS *); -LOCALE void PackClassLinks(void *,PACKED_CLASS_LINKS *,CLASS_LINK *); - -#ifndef _INHERPSR_SOURCE_ -#endif + LOCALE PACKED_CLASS_LINKS *ParseSuperclasses(void *,const char *,SYMBOL_HN *); + LOCALE PACKED_CLASS_LINKS *FindPrecedenceList(void *,DEFCLASS *,PACKED_CLASS_LINKS *); + LOCALE void PackClassLinks(void *,PACKED_CLASS_LINKS *,CLASS_LINK *); -#endif +#endif /* OBJECT_SYSTEM && (! BLOAD_ONLY) && (! RUN_TIME) */ -#endif +#endif /* _H_inherpsr */ diff --git a/src/inscom.c b/src/inscom.c index 44d55b2..8174ce1 100644 --- a/src/inscom.c +++ b/src/inscom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* INSTANCE COMMAND MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Kernel Interface Commands for Instances */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -30,6 +31,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 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. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ /* ========================================= @@ -81,12 +95,12 @@ ***************************************** */ #if DEBUGGING_FUNCTIONS -static long ListInstancesInModule(void *,int,char *,char *,intBool,intBool); -static long TabulateInstances(void *,int,char *,DEFCLASS *,intBool,intBool); +static long ListInstancesInModule(void *,int,const char *,const char *,intBool,intBool); +static long TabulateInstances(void *,int,const char *,DEFCLASS *,intBool,intBool); #endif -static void PrintInstance(void *,char *,INSTANCE_TYPE *,char *); -static INSTANCE_SLOT *FindISlotByName(void *,INSTANCE_TYPE *,char *); +static void PrintInstance(void *,const char *,INSTANCE_TYPE *,const char *); +static INSTANCE_SLOT *FindISlotByName(void *,INSTANCE_TYPE *,const char *); static void DeallocateInstanceData(void *); /* ========================================= @@ -116,26 +130,30 @@ globle void SetupInstances( EnvGetNextInstance, EnvDecrementInstanceCount, EnvIncrementInstanceCount, - NULL,NULL,NULL,NULL + NULL,NULL,NULL,NULL,NULL }, #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM DecrementObjectBasisCount, IncrementObjectBasisCount, MatchObjectFunction, - NetworkSynchronized + NetworkSynchronized, + InstanceIsDeleted #else - NULL,NULL,NULL,NULL + NULL,NULL,NULL,NULL,NULL #endif }; - - INSTANCE_TYPE dummyInstance = { { NULL }, NULL,NULL, 0, 1 }; + + INSTANCE_TYPE dummyInstance = { { NULL, NULL, 0, 0L }, + NULL, NULL, 0, 1, 0, 0, 0, + NULL, 0, 0, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL }; AllocateEnvironmentData(theEnv,INSTANCE_DATA,sizeof(struct instanceData),DeallocateInstanceData); - + InstanceData(theEnv)->MkInsMsgPass = TRUE; - memcpy(&InstanceData(theEnv)->InstanceInfo,&instanceInfo,sizeof(struct patternEntityRecord)); - dummyInstance.header.theInfo = &InstanceData(theEnv)->InstanceInfo; - memcpy(&InstanceData(theEnv)->DummyInstance,&dummyInstance,sizeof(INSTANCE_TYPE)); + memcpy(&InstanceData(theEnv)->InstanceInfo,&instanceInfo,sizeof(struct patternEntityRecord)); + dummyInstance.header.theInfo = &InstanceData(theEnv)->InstanceInfo; + memcpy(&InstanceData(theEnv)->DummyInstance,&dummyInstance,sizeof(INSTANCE_TYPE)); InitializeInstanceTable(theEnv); InstallPrimitive(theEnv,(struct entityRecord *) &InstanceData(theEnv)->InstanceInfo,INSTANCE_ADDRESS); @@ -203,7 +221,7 @@ globle void SetupInstances( AddCleanupFunction(theEnv,"instances",CleanupInstances,0); EnvAddResetFunction(theEnv,"instances",DestroyAllInstances,60); } - + /***************************************/ /* DeallocateInstanceData: Deallocates */ /* environment data for instances. */ @@ -212,28 +230,28 @@ static void DeallocateInstanceData( void *theEnv) { INSTANCE_TYPE *tmpIPtr, *nextIPtr; - register unsigned i; + long i; INSTANCE_SLOT *sp; IGARBAGE *tmpGPtr, *nextGPtr; struct patternMatch *theMatch, *tmpMatch; - + /*=================================*/ /* Remove the instance hash table. */ /*=================================*/ - + rm(theEnv,InstanceData(theEnv)->InstanceTable, (int) (sizeof(INSTANCE_TYPE *) * INSTANCE_TABLE_HASH_SIZE)); - + /*=======================*/ /* Return all instances. */ /*=======================*/ - + tmpIPtr = InstanceData(theEnv)->InstanceList; while (tmpIPtr != NULL) { nextIPtr = tmpIPtr->nxtList; - - theMatch = (struct patternMatch *) tmpIPtr->partialMatchList; + + theMatch = (struct patternMatch *) tmpIPtr->partialMatchList; while (theMatch != NULL) { tmpMatch = theMatch->next; @@ -255,7 +273,7 @@ static void DeallocateInstanceData( { ReturnMultifield(theEnv,(MULTIFIELD_PTR) sp->value); } } } - + if (tmpIPtr->cls->instanceSlotCount != 0) { rm(theEnv,(void *) tmpIPtr->slotAddresses, @@ -266,16 +284,16 @@ static void DeallocateInstanceData( (tmpIPtr->cls->localInstanceSlotCount * sizeof(INSTANCE_SLOT))); } } - + rtn_struct(theEnv,instance,tmpIPtr); tmpIPtr = nextIPtr; } - + /*===============================*/ /* Get rid of garbage instances. */ /*===============================*/ - + tmpGPtr = InstanceData(theEnv)->InstanceGarbageList; while (tmpGPtr != NULL) { @@ -314,9 +332,12 @@ globle intBool EnvDeleteInstance( success = 0; } - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } return(success); } @@ -366,9 +387,12 @@ globle intBool EnvUnmakeInstance( InstanceData(theEnv)->MaintainGarbageInstances = svmaintain; CleanupInstances(theEnv); - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } return(success); } @@ -389,7 +413,7 @@ globle void InstancesCommand( { int argno, inheritFlag = FALSE; void *theDefmodule; - char *className = NULL; + const char *className = NULL; DATA_OBJECT temp; theDefmodule = (void *) EnvGetCurrentModule(theEnv); @@ -477,9 +501,9 @@ globle void PPInstanceCommand( **************************************************************/ globle void EnvInstances( void *theEnv, - char *logicalName, + const char *logicalName, void *theVModule, - char *className, + const char *className, int inheritFlag) { int id; @@ -534,7 +558,7 @@ globle void EnvInstances( PrintTally(theEnv,logicalName,count,"instance","instances"); } -#endif +#endif /* DEBUGGING_FUNCTIONS */ /********************************************************* NAME : EnvMakeInstance @@ -550,9 +574,9 @@ globle void EnvInstances( *********************************************************/ globle void *EnvMakeInstance( void *theEnv, - char *mkstr) + const char *mkstr) { - char *router = "***MKINS***"; + const char *router = "***MKINS***"; struct token tkn; EXPRESSION *top; DATA_OBJECT result; @@ -583,9 +607,12 @@ globle void *EnvMakeInstance( SyntaxErrorMessage(theEnv,"instance definition"); CloseStringSource(theEnv,router); - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } if ((result.type == SYMBOL) && (result.value == EnvFalseSymbol(theEnv))) return(NULL); @@ -608,7 +635,7 @@ globle void *EnvMakeInstance( globle void *EnvCreateRawInstance( void *theEnv, void *cptr, - char *iname) + const char *iname) { return((void *) BuildInstance(theEnv,(SYMBOL_HN *) EnvAddSymbol(theEnv,iname),(DEFCLASS *) cptr,FALSE)); } @@ -624,7 +651,7 @@ globle void *EnvCreateRawInstance( globle void *EnvFindInstance( void *theEnv, void *theModule, - char *iname, + const char *iname, unsigned searchImports) { SYMBOL_HN *isym; @@ -646,14 +673,11 @@ globle void *EnvFindInstance( SIDE EFFECTS : None NOTES : None ***************************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int EnvValidInstanceAddress( void *theEnv, void *iptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -673,7 +697,7 @@ globle int EnvValidInstanceAddress( globle void EnvDirectGetSlot( void *theEnv, void *ins, - char *sname, + const char *sname, DATA_OBJECT *result) { INSTANCE_SLOT *sp; @@ -700,7 +724,12 @@ globle void EnvDirectGetSlot( result->begin = 0; SetpDOEnd(result,GetInstanceSlotLength(sp)); } - PropagateReturnValue(theEnv,result); + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,result); + CallPeriodicTasks(theEnv); + } } /********************************************************* @@ -716,7 +745,7 @@ globle void EnvDirectGetSlot( globle int EnvDirectPutSlot( void *theEnv, void *ins, - char *sname, + const char *sname, DATA_OBJECT *val) { INSTANCE_SLOT *sp; @@ -736,9 +765,12 @@ globle int EnvDirectPutSlot( if (PutSlotValue(theEnv,(INSTANCE_TYPE *) ins,sp,val,&junk,"external put")) { - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } return(TRUE); } return(FALSE); @@ -752,14 +784,11 @@ globle int EnvDirectPutSlot( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetInstanceName( +globle const char *EnvGetInstanceName( void *theEnv, void *iptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -776,14 +805,11 @@ globle char *EnvGetInstanceName( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void *EnvGetInstanceClass( void *theEnv, void *iptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -873,15 +899,12 @@ globle void *GetNextInstanceInScope( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void *EnvGetNextInstanceInClass( void *theEnv, void *cptr, void *iptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -912,9 +935,9 @@ globle void *EnvGetNextInstanceInClassAndSubclasses( { INSTANCE_TYPE *nextInstance; DEFCLASS *theClass; - + theClass = (DEFCLASS *) *cptr; - + if (iptr == NULL) { ClassSubclassAddresses(theEnv,theClass,iterationInfo,TRUE); @@ -924,8 +947,8 @@ globle void *EnvGetNextInstanceInClassAndSubclasses( { nextInstance = NULL; } else { nextInstance = ((INSTANCE_TYPE *) iptr)->nxtClass; } - - while ((nextInstance == NULL) && + + while ((nextInstance == NULL) && (GetpDOBegin(iterationInfo) <= GetpDOEnd(iterationInfo))) { theClass = (struct defclass *) GetMFValue(DOPToPointer(iterationInfo), @@ -934,10 +957,10 @@ globle void *EnvGetNextInstanceInClassAndSubclasses( SetpDOBegin(iterationInfo,GetpDOBegin(iterationInfo) + 1); nextInstance = theClass->instanceList; } - + return(nextInstance); } - + /*************************************************** NAME : EnvGetInstancePPForm DESCRIPTION : Writes slot names and values to @@ -953,10 +976,10 @@ globle void *EnvGetNextInstanceInClassAndSubclasses( globle void EnvGetInstancePPForm( void *theEnv, char *buf, - unsigned buflen, + size_t buflen, void *iptr) { - char *pbuf = "***InstancePPForm***"; + const char *pbuf = "***InstancePPForm***"; if (((INSTANCE_TYPE *) iptr)->garbage == 1) return; @@ -981,7 +1004,7 @@ globle void ClassCommand( DATA_OBJECT *result) { INSTANCE_TYPE *ins; - char *func; + const char *func; DATA_OBJECT temp; func = ValueToString(((struct FunctionDefinition *) @@ -1025,6 +1048,7 @@ globle void ClassCommand( GetDefclassNamePointer((void *) DefclassData(theEnv)->PrimitiveClassMap[temp.type]); return; + default : PrintErrorID(theEnv,"INSCOM",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Undefined type in function "); EnvPrintRouter(theEnv,WERROR,func); @@ -1033,7 +1057,7 @@ globle void ClassCommand( } } } - + /****************************************************** NAME : CreateInstanceHandler DESCRIPTION : Message handler called after instance creation @@ -1043,13 +1067,10 @@ globle void ClassCommand( SIDE EFFECTS : None NOTES : Does nothing. Provided so it can be overridden. ******************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool CreateInstanceHandler( void *theEnv) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1118,7 +1139,7 @@ globle intBool UnmakeInstanceCommand( } else { - ExpectedTypeError1(theEnv,"retract",argNumber,"instance-address, instance-name, or the symbol *"); + ExpectedTypeError1(theEnv,"unmake-instance",argNumber,"instance-address, instance-name, or the symbol *"); SetEvaluationError(theEnv,TRUE); return(FALSE); } @@ -1403,8 +1424,8 @@ globle intBool InstanceExistPCommand( static long ListInstancesInModule( void *theEnv, int id, - char *logicalName, - char *className, + const char *logicalName, + const char *className, intBool inheritFlag, intBool allModulesFlag) { @@ -1488,13 +1509,13 @@ static long ListInstancesInModule( static long TabulateInstances( void *theEnv, int id, - char *logicalName, + const char *logicalName, DEFCLASS *cls, intBool inheritFlag, intBool allModulesFlag) { INSTANCE_TYPE *ins; - register unsigned i; + long i; long count = 0; if (TestTraversalID(cls->traversalRecord,id)) @@ -1537,11 +1558,11 @@ static long TabulateInstances( ***************************************************/ static void PrintInstance( void *theEnv, - char *logicalName, + const char *logicalName, INSTANCE_TYPE *ins, - char *separator) + const char *separator) { - register unsigned i; + long i; register INSTANCE_SLOT *sp; PrintInstanceNameAndClass(theEnv,logicalName,ins,FALSE); @@ -1580,7 +1601,7 @@ static void PrintInstance( static INSTANCE_SLOT *FindISlotByName( void *theEnv, INSTANCE_TYPE *ins, - char *sname) + const char *sname) { SYMBOL_HN *ssym; @@ -1590,5 +1611,120 @@ static INSTANCE_SLOT *FindISlotByName( return(FindInstanceSlot(theEnv,ins,ssym)); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *GetInstanceName( + void *iptr) + { + return EnvGetInstanceName(GetCurrentEnvironment(),iptr); + } + +globle void *CreateRawInstance( + void *cptr, + const char *iname) + { + return EnvCreateRawInstance(GetCurrentEnvironment(),cptr,iname); + } + +globle intBool DeleteInstance( + void *iptr) + { + return EnvDeleteInstance(GetCurrentEnvironment(),iptr); + } + +globle void DirectGetSlot( + void *ins, + const char *sname, + DATA_OBJECT *result) + { + EnvDirectGetSlot(GetCurrentEnvironment(),ins,sname,result); + } + +globle int DirectPutSlot( + void *ins, + const char *sname, + DATA_OBJECT *val) + { + return EnvDirectPutSlot(GetCurrentEnvironment(),ins,sname,val); + } + +globle void *FindInstance( + void *theModule, + const char *iname, + unsigned searchImports) + { + return EnvFindInstance(GetCurrentEnvironment(),theModule,iname,searchImports); + } + +globle void *GetInstanceClass( + void *iptr) + { + return EnvGetInstanceClass(GetCurrentEnvironment(),iptr); + } + +globle void GetInstancePPForm( + char *buf, + unsigned buflen, + void *iptr) + { + EnvGetInstancePPForm(GetCurrentEnvironment(),buf,buflen,iptr); + } + +globle void *GetNextInstance( + void *iptr) + { + return EnvGetNextInstance(GetCurrentEnvironment(),iptr); + } + +globle void *GetNextInstanceInClass( + void *cptr, + void *iptr) + { + return EnvGetNextInstanceInClass(GetCurrentEnvironment(),cptr,iptr); + } + +globle void *GetNextInstanceInClassAndSubclasses( + void **cptr, + void *iptr, + DATA_OBJECT *iterationInfo) + { + return EnvGetNextInstanceInClassAndSubclasses(GetCurrentEnvironment(),cptr,iptr,iterationInfo); + } + +#if DEBUGGING_FUNCTIONS +globle void Instances( + const char *logicalName, + void *theVModule, + const char *className, + int inheritFlag) + { + EnvInstances(GetCurrentEnvironment(),logicalName,theVModule,className,inheritFlag); + } #endif +globle void *MakeInstance( + const char *mkstr) + { + return EnvMakeInstance(GetCurrentEnvironment(),mkstr); + } + +globle intBool UnmakeInstance( + void *iptr) + { + return EnvUnmakeInstance(GetCurrentEnvironment(),iptr); + } + +globle int ValidInstanceAddress( + void *iptr) + { + return EnvValidInstanceAddress(GetCurrentEnvironment(),iptr); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* OBJECT_SYSTEM */ + diff --git a/src/inscom.h b/src/inscom.h index 2af6894..2ca01e2 100644 --- a/src/inscom.h +++ b/src/inscom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* */ /*******************************************************/ @@ -10,15 +10,39 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Loading a binary instance file from a run-time */ +/* program caused a bus error. DR0866 */ +/* */ +/* Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 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. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -36,7 +60,7 @@ #define INSTANCE_DATA 29 struct instanceData - { + { INSTANCE_TYPE DummyInstance; INSTANCE_TYPE **InstanceTable; int MaintainGarbageInstances; @@ -44,7 +68,7 @@ struct instanceData int ChangesToInstances; IGARBAGE *InstanceGarbageList; struct patternEntityRecord InstanceInfo; - INSTANCE_TYPE *InstanceList; + INSTANCE_TYPE *InstanceList; unsigned long GlobalNumberOfInstances; INSTANCE_TYPE *CurrentInstance; INSTANCE_TYPE *InstanceListBottom; @@ -63,76 +87,64 @@ struct instanceData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define CreateRawInstance(theEnv,a,b) EnvCreateRawInstance(theEnv,a,b) -#define DeleteInstance(theEnv,a) EnvDeleteInstance(theEnv,a) -#define DirectGetSlot(theEnv,a,b,c) EnvDirectGetSlot(theEnv,a,b,c) -#define DirectPutSlot(theEnv,a,b,c) EnvDirectPutSlot(theEnv,a,b,c) -#define FindInstance(theEnv,a,b,c) EnvFindInstance(theEnv,a,b,c) -#define GetInstanceClass(theEnv,a) EnvGetInstanceClass(theEnv,a) -#define GetInstanceName(theEnv,a) EnvGetInstanceName(theEnv,a) -#define GetInstancePPForm(theEnv,a,b,c) EnvGetInstancePPForm(theEnv,a,b,c) -#define GetNextInstance(theEnv,a) EnvGetNextInstance(theEnv,a) -#define GetNextInstanceInClass(theEnv,a,b) EnvGetNextInstanceInClass(theEnv,a,b) -#define GetNextInstanceInClassAndSubclasses(theEnv,a,b,c) EnvGetNextInstanceInClassAndSubclasses(theEnv,a,b,c) -#define Instances(theEnv,a,b,c,d) EnvInstances(theEnv,a,b,c,d) -#define MakeInstance(theEnv,a) EnvMakeInstance(theEnv,a) -#define UnmakeInstance(theEnv,a) EnvUnmakeInstance(theEnv,a) -#define ValidInstanceAddress(theEnv,a) EnvValidInstanceAddress(theEnv,a) -#else -#define CreateRawInstance(a,b) EnvCreateRawInstance(GetCurrentEnvironment(),a,b) -#define DeleteInstance(a) EnvDeleteInstance(GetCurrentEnvironment(),a) -#define DirectGetSlot(a,b,c) EnvDirectGetSlot(GetCurrentEnvironment(),a,b,c) -#define DirectPutSlot(a,b,c) EnvDirectPutSlot(GetCurrentEnvironment(),a,b,c) -#define FindInstance(a,b,c) EnvFindInstance(GetCurrentEnvironment(),a,b,c) -#define GetInstanceClass(a) EnvGetInstanceClass(GetCurrentEnvironment(),a) -#define GetInstanceName(a) EnvGetInstanceName(GetCurrentEnvironment(),a) -#define GetInstancePPForm(a,b,c) EnvGetInstancePPForm(GetCurrentEnvironment(),a,b,c) -#define GetNextInstance(a) EnvGetNextInstance(GetCurrentEnvironment(),a) -#define GetNextInstanceInClass(a,b) EnvGetNextInstanceInClass(GetCurrentEnvironment(),a,b) -#define GetNextInstanceInClassAndSubclasses(a,b,c) EnvGetNextInstanceInClassAndSubclasses(GetCurrentEnvironment(),a,b,c) -#define Instances(a,b,c,d) EnvInstances(GetCurrentEnvironment(),a,b,c,d) -#define MakeInstance(a) EnvMakeInstance(GetCurrentEnvironment(),a) -#define UnmakeInstance(a) EnvUnmakeInstance(GetCurrentEnvironment(),a) -#define ValidInstanceAddress(a) EnvValidInstanceAddress(GetCurrentEnvironment(),a) + LOCALE void SetupInstances(void *); + LOCALE intBool EnvDeleteInstance(void *,void *); + LOCALE intBool EnvUnmakeInstance(void *,void *); +#if DEBUGGING_FUNCTIONS + LOCALE void InstancesCommand(void *); + LOCALE void PPInstanceCommand(void *); + LOCALE void EnvInstances(void *,const char *,void *,const char *,int); #endif - -LOCALE void SetupInstances(void *); -LOCALE intBool EnvDeleteInstance(void *,void *); -LOCALE intBool EnvUnmakeInstance(void *,void *); + LOCALE void *EnvMakeInstance(void *,const char *); + LOCALE void *EnvCreateRawInstance(void *,void *,const char *); + LOCALE void *EnvFindInstance(void *,void *,const char *,unsigned); + LOCALE int EnvValidInstanceAddress(void *,void *); + LOCALE void EnvDirectGetSlot(void *,void *,const char *,DATA_OBJECT *); + LOCALE int EnvDirectPutSlot(void *,void *,const char *,DATA_OBJECT *); + LOCALE const char *EnvGetInstanceName(void *,void *); + LOCALE void *EnvGetInstanceClass(void *,void *); + LOCALE unsigned long GetGlobalNumberOfInstances(void *); + LOCALE void *EnvGetNextInstance(void *,void *); + LOCALE void *GetNextInstanceInScope(void *,void *); + LOCALE void *EnvGetNextInstanceInClass(void *,void *,void *); + LOCALE void *EnvGetNextInstanceInClassAndSubclasses(void *,void **,void *,DATA_OBJECT *); + LOCALE void EnvGetInstancePPForm(void *,char *,size_t,void *); + LOCALE void ClassCommand(void *,DATA_OBJECT *); + LOCALE intBool DeleteInstanceCommand(void *); + LOCALE intBool UnmakeInstanceCommand(void *); + LOCALE void SymbolToInstanceName(void *,DATA_OBJECT *); + LOCALE void *InstanceNameToSymbol(void *); + LOCALE void InstanceAddressCommand(void *,DATA_OBJECT *); + LOCALE void InstanceNameCommand(void *,DATA_OBJECT *); + LOCALE intBool InstanceAddressPCommand(void *); + LOCALE intBool InstanceNamePCommand(void *); + LOCALE intBool InstancePCommand(void *); + LOCALE intBool InstanceExistPCommand(void *); + LOCALE intBool CreateInstanceHandler(void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE const char *GetInstanceName(void *); + LOCALE void *CreateRawInstance(void *,const char *); + LOCALE intBool DeleteInstance(void *); + LOCALE void DirectGetSlot(void *,const char *,DATA_OBJECT *); + LOCALE int DirectPutSlot(void *,const char *,DATA_OBJECT *); + LOCALE void *FindInstance(void *,const char *,unsigned); + LOCALE void *GetInstanceClass(void *); + LOCALE void GetInstancePPForm(char *,unsigned,void *); + LOCALE void *GetNextInstance(void *); + LOCALE void *GetNextInstanceInClass(void *,void *); + LOCALE void *GetNextInstanceInClassAndSubclasses(void **,void *,DATA_OBJECT *); + LOCALE void Instances(const char *,void *,const char *,int); #if DEBUGGING_FUNCTIONS -LOCALE void InstancesCommand(void *); -LOCALE void PPInstanceCommand(void *); -LOCALE void EnvInstances(void *,char *,void *,char *,int); + LOCALE void *MakeInstance(const char *); #endif -LOCALE void *EnvMakeInstance(void *,char *); -LOCALE void *EnvCreateRawInstance(void *,void *,char *); -LOCALE void *EnvFindInstance(void *,void *,char *,unsigned); -LOCALE int EnvValidInstanceAddress(void *,void *); -LOCALE void EnvDirectGetSlot(void *,void *,char *,DATA_OBJECT *); -LOCALE int EnvDirectPutSlot(void *,void *,char *,DATA_OBJECT *); -LOCALE char *EnvGetInstanceName(void *,void *); -LOCALE void *EnvGetInstanceClass(void *,void *); -LOCALE unsigned long GetGlobalNumberOfInstances(void *); -LOCALE void *EnvGetNextInstance(void *,void *); -LOCALE void *GetNextInstanceInScope(void *,void *); -LOCALE void *EnvGetNextInstanceInClass(void *,void *,void *); -LOCALE void *EnvGetNextInstanceInClassAndSubclasses(void *,void **,void *,DATA_OBJECT *); -LOCALE void EnvGetInstancePPForm(void *,char *,unsigned,void *); -LOCALE void ClassCommand(void *,DATA_OBJECT *); -LOCALE intBool DeleteInstanceCommand(void *); -LOCALE intBool UnmakeInstanceCommand(void *); -LOCALE void SymbolToInstanceName(void *,DATA_OBJECT *); -LOCALE void *InstanceNameToSymbol(void *); -LOCALE void InstanceAddressCommand(void *,DATA_OBJECT *); -LOCALE void InstanceNameCommand(void *,DATA_OBJECT *); -LOCALE intBool InstanceAddressPCommand(void *); -LOCALE intBool InstanceNamePCommand(void *); -LOCALE intBool InstancePCommand(void *); -LOCALE intBool InstanceExistPCommand(void *); -LOCALE intBool CreateInstanceHandler(void *); + LOCALE intBool UnmakeInstance(void *); + LOCALE int ValidInstanceAddress(void *); -#endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_inscom */ diff --git a/src/insfile.c b/src/insfile.c index 6546fb2..1676c18 100644 --- a/src/insfile.c +++ b/src/insfile.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* INSTANCE LOAD/SAVE (ASCII/BINARY) MODULE */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: File load/save routines for instances */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -23,6 +23,22 @@ /* */ /* Corrected code to remove compiler warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* For save-instances, bsave-instances, and */ +/* bload-instances, the class name does not */ +/* have to be in scope if the module name is */ +/* specified. */ +/* */ /*************************************************************/ /* ========================================= @@ -90,16 +106,16 @@ struct bsaveSlotValueAtom ========================================= ***************************************** */ -static long InstancesSaveCommandParser(void *,char *,long (*)(void *,char *,int, +static long InstancesSaveCommandParser(void *,const char *,long (*)(void *,const char *,int, EXPRESSION *,intBool)); -static DATA_OBJECT *ProcessSaveClassList(void *,char *,EXPRESSION *,int,intBool); +static DATA_OBJECT *ProcessSaveClassList(void *,const char *,EXPRESSION *,int,intBool); static void ReturnSaveClassList(void *,DATA_OBJECT *); static long SaveOrMarkInstances(void *,void *,int,DATA_OBJECT *,intBool,intBool, void (*)(void *,void *,INSTANCE_TYPE *)); static long SaveOrMarkInstancesOfClass(void *,void *,struct defmodule *,int,DEFCLASS *, intBool,int,void (*)(void *,void *,INSTANCE_TYPE *)); static void SaveSingleInstanceText(void *,void *,INSTANCE_TYPE *); -static void ProcessFileErrorMessage(void *,char *,char *); +static void ProcessFileErrorMessage(void *,const char *,const char *); #if BSAVE_INSTANCES static void WriteBinaryHeader(void *,FILE *); static void MarkSingleInstance(void *,void *,INSTANCE_TYPE *); @@ -108,13 +124,13 @@ static void SaveSingleInstanceBinary(void *,void *,INSTANCE_TYPE *); static void SaveAtomBinary(void *,unsigned short,void *,FILE *); #endif -static long LoadOrRestoreInstances(void *,char *,int,int); +static long LoadOrRestoreInstances(void *,const char *,int,int); #if BLOAD_INSTANCES -static intBool VerifyBinaryHeader(void *,char *); +static intBool VerifyBinaryHeader(void *,const char *); static intBool LoadSingleBinaryInstance(void *); static void BinaryLoadInstanceError(void *,SYMBOL_HN *,DEFCLASS *); -static void CreateSlotValue(void *,DATA_OBJECT *,struct bsaveSlotValueAtom *,unsigned long); +static void CreateSlotValue(void *,DATA_OBJECT *,struct bsaveSlotValueAtom *,unsigned long); static void *GetBinaryAtomValue(void *,struct bsaveSlotValueAtom *); static void BufferedRead(void *,void *,unsigned long); static void FreeReadBuffer(void *); @@ -179,7 +195,7 @@ globle void SetupInstanceFileCommands( globle long SaveInstancesCommand( void *theEnv) { - return(InstancesSaveCommandParser(theEnv,"save-instances",EnvSaveInstances)); + return(InstancesSaveCommandParser(theEnv,"save-instances",EnvSaveInstancesDriver)); } /****************************************************** @@ -194,7 +210,7 @@ globle long SaveInstancesCommand( globle long LoadInstancesCommand( void *theEnv) { - char *fileFound; + const char *fileFound; DATA_OBJECT temp; long instanceCount; @@ -219,7 +235,7 @@ globle long LoadInstancesCommand( ***************************************************/ globle long EnvLoadInstances( void *theEnv, - char *file) + const char *file) { return(LoadOrRestoreInstances(theEnv,file,TRUE,TRUE)); } @@ -236,11 +252,11 @@ globle long EnvLoadInstances( ***************************************************/ globle long EnvLoadInstancesFromString( void *theEnv, - char *theString, + const char *theString, int theMax) { long theCount; - char * theStrRouter = "*** load-instances-from-string ***"; + const char * theStrRouter = "*** load-instances-from-string ***"; if ((theMax == -1) ? (!OpenStringSource(theEnv,theStrRouter,theString,0)) : (!OpenTextSource(theEnv,theStrRouter,theString,0,(unsigned) theMax))) @@ -262,7 +278,7 @@ globle long EnvLoadInstancesFromString( globle long RestoreInstancesCommand( void *theEnv) { - char *fileFound; + const char *fileFound; DATA_OBJECT temp; long instanceCount; @@ -287,7 +303,7 @@ globle long RestoreInstancesCommand( ***************************************************/ globle long EnvRestoreInstances( void *theEnv, - char *file) + const char *file) { return(LoadOrRestoreInstances(theEnv,file,FALSE,TRUE)); } @@ -304,11 +320,11 @@ globle long EnvRestoreInstances( ***************************************************/ globle long EnvRestoreInstancesFromString( void *theEnv, - char *theString, + const char *theString, int theMax) { long theCount; - char * theStrRouter = "*** load-instances-from-string ***"; + const char *theStrRouter = "*** load-instances-from-string ***"; if ((theMax == -1) ? (!OpenStringSource(theEnv,theStrRouter,theString,0)) : (!OpenTextSource(theEnv,theStrRouter,theString,0,(unsigned) theMax))) @@ -332,7 +348,7 @@ globle long EnvRestoreInstancesFromString( globle long BinaryLoadInstancesCommand( void *theEnv) { - char *fileFound; + const char *fileFound; DATA_OBJECT temp; long instanceCount; @@ -358,7 +374,7 @@ globle long BinaryLoadInstancesCommand( ****************************************************/ globle long EnvBinaryLoadInstances( void *theEnv, - char *theFile) + const char *theFile) { long i,instanceCount; @@ -373,14 +389,14 @@ globle long EnvBinaryLoadInstances( SetEvaluationError(theEnv,TRUE); return(-1L); } - + EnvIncrementGCLocks(theEnv); ReadNeededAtomicValues(theEnv); InstanceFileData(theEnv)->BinaryInstanceFileOffset = 0L; - GenReadBinary(theEnv,(void *) &InstanceFileData(theEnv)->BinaryInstanceFileSize,(unsigned long) sizeof(unsigned long)); - GenReadBinary(theEnv,(void *) &instanceCount,(unsigned long) sizeof(long)); + GenReadBinary(theEnv,(void *) &InstanceFileData(theEnv)->BinaryInstanceFileSize,sizeof(unsigned long)); + GenReadBinary(theEnv,(void *) &instanceCount,sizeof(long)); for (i = 0L ; i < instanceCount ; i++) { @@ -425,7 +441,33 @@ globle long EnvBinaryLoadInstances( *******************************************************/ globle long EnvSaveInstances( void *theEnv, - char *file, + const char *file, + int saveCode) + { + return EnvSaveInstancesDriver(theEnv,file,saveCode,NULL,TRUE); + } + +/******************************************************* + NAME : EnvSaveInstancesDriver + DESCRIPTION : Saves current instances to named file + INPUTS : 1) The name of the output file + 2) A flag indicating whether to + save local (current module only) + or visible instances + LOCAL_SAVE or VISIBLE_SAVE + 3) A list of expressions containing + the names of classes for which + instances are to be saved + 4) A flag indicating if the subclasses + of specified classes shoudl also + be processed + RETURNS : The number of instances saved + SIDE EFFECTS : Instances saved to file + NOTES : None + *******************************************************/ +globle long EnvSaveInstancesDriver( + void *theEnv, + const char *file, int saveCode, EXPRESSION *classExpressionList, intBool inheritFlag) @@ -486,7 +528,7 @@ globle long EnvSaveInstances( globle long BinarySaveInstancesCommand( void *theEnv) { - return(InstancesSaveCommandParser(theEnv,"bsave-instances",EnvBinarySaveInstances)); + return(InstancesSaveCommandParser(theEnv,"bsave-instances",EnvBinarySaveInstancesDriver)); } /******************************************************* @@ -497,6 +539,26 @@ globle long BinarySaveInstancesCommand( save local (current module only) or visible instances LOCAL_SAVE or VISIBLE_SAVE + RETURNS : The number of instances saved + SIDE EFFECTS : Instances saved to file + NOTES : None + *******************************************************/ +globle long EnvBinarySaveInstances( + void *theEnv, + const char *file, + int saveCode) + { + return EnvBinarySaveInstancesDriver(theEnv,file,saveCode,NULL,TRUE); + } + +/******************************************************* + NAME : EnvBinarySaveInstancesDriver + DESCRIPTION : Saves current instances to binary file + INPUTS : 1) The name of the output file + 2) A flag indicating whether to + save local (current module only) + or visible instances + LOCAL_SAVE or VISIBLE_SAVE 3) A list of expressions containing the names of classes for which instances are to be saved @@ -507,9 +569,9 @@ globle long BinarySaveInstancesCommand( SIDE EFFECTS : Instances saved to file NOTES : None *******************************************************/ -globle long EnvBinarySaveInstances( +globle long EnvBinarySaveInstancesDriver( void *theEnv, - char *file, + const char *file, int saveCode, EXPRESSION *classExpressionList, intBool inheritFlag) @@ -571,10 +633,10 @@ globle long EnvBinarySaveInstances( ******************************************************/ static long InstancesSaveCommandParser( void *theEnv, - char *functionName, - long (*saveFunction)(void *,char *,int,EXPRESSION *,intBool)) + const char *functionName, + long (*saveFunction)(void *,const char *,int,EXPRESSION *,intBool)) { - char *fileFound; + const char *fileFound; DATA_OBJECT temp; int argCount,saveCode = LOCAL_SAVE; EXPRESSION *classList = NULL; @@ -645,7 +707,7 @@ static long InstancesSaveCommandParser( ****************************************************/ static DATA_OBJECT *ProcessSaveClassList( void *theEnv, - char *functionName, + const char *functionName, EXPRESSION *classExps, int saveCode, intBool inheritFlag) @@ -665,7 +727,9 @@ static DATA_OBJECT *ProcessSaveClassList( if (saveCode == LOCAL_SAVE) theDefclass = LookupDefclassAnywhere(theEnv,currentModule,DOToString(tmp)); else - theDefclass = LookupDefclassInScope(theEnv,DOToString(tmp)); + //theDefclass = LookupDefclassInScope(theEnv,DOToString(tmp)); + { theDefclass = LookupDefclassByMdlOrScope(theEnv,DOToString(tmp)); } + if (theDefclass == NULL) goto ProcessClassListError; else if (theDefclass->abstract && (inheritFlag == FALSE)) @@ -698,8 +762,10 @@ static DATA_OBJECT *ProcessSaveClassList( return(head); ProcessClassListError: - ExpectedTypeError1(theEnv,functionName,argIndex, - (char *) (inheritFlag ? "valid class name" : "valid concrete class name")); + if (inheritFlag) + ExpectedTypeError1(theEnv,functionName,argIndex,"valid class name"); + else + ExpectedTypeError1(theEnv,functionName,argIndex,"valid concrete class name"); ReturnSaveClassList(theEnv,head); SetEvaluationError(theEnv,TRUE); return(NULL); @@ -837,7 +903,7 @@ static long SaveOrMarkInstancesOfClass( { INSTANCE_TYPE *theInstance; DEFCLASS *subclass; - register unsigned i; + long i; long instanceCount = 0L; if (TestTraversalID(theDefclass->traversalRecord,traversalID)) @@ -886,9 +952,9 @@ static void SaveSingleInstanceText( void *vLogicalName, INSTANCE_TYPE *theInstance) { - register unsigned i; + long i; INSTANCE_SLOT *sp; - char *logicalName = (char *) vLogicalName; + const char *logicalName = (const char *) vLogicalName; EnvPrintRouter(theEnv,logicalName,"(["); EnvPrintRouter(theEnv,logicalName,ValueToString(theInstance->name)); @@ -930,7 +996,7 @@ static void SaveSingleInstanceText( static void WriteBinaryHeader( void *theEnv, FILE *bsaveFP) - { + { fwrite((void *) InstanceFileData(theEnv)->InstanceBinaryPrefixID, (STD_SIZE) (strlen(InstanceFileData(theEnv)->InstanceBinaryPrefixID) + 1),1,bsaveFP); fwrite((void *) InstanceFileData(theEnv)->InstanceBinaryVersionID, @@ -947,19 +1013,16 @@ static void WriteBinaryHeader( SIDE EFFECTS : Instance slot value atoms marked NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkSingleInstance( void *theEnv, void *theOutput, INSTANCE_TYPE *theInstance) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theOutput) #endif INSTANCE_SLOT *sp; - register unsigned i,j; + long i, j; InstanceFileData(theEnv)->BinaryInstanceFileSize += (unsigned long) (sizeof(long) * 2); theInstance->name->neededSymbol = TRUE; @@ -1023,8 +1086,6 @@ static void MarkNeededAtom( case INSTANCE_ADDRESS: GetFullInstanceName(theEnv,(INSTANCE_TYPE *) value)->neededSymbol = TRUE; break; - default: - break; } } @@ -1043,12 +1104,12 @@ static void SaveSingleInstanceBinary( INSTANCE_TYPE *theInstance) { long nameIndex; - register unsigned i,j; + long i,j; INSTANCE_SLOT *sp; FILE *bsaveFP = (FILE *) vBsaveFP; struct bsaveSlotValue bs; - unsigned long totalValueCount = 0L; - unsigned slotLen; + long totalValueCount = 0L; + long slotLen; /* =========================== Write out the instance name @@ -1066,7 +1127,7 @@ static void SaveSingleInstanceBinary( Write out the number of slot-overrides ====================================== */ fwrite((void *) &theInstance->cls->instanceSlotCount, - (int) sizeof(unsigned),1,bsaveFP); + (int) sizeof(short),1,bsaveFP); /* ========================================= Write out the slot names and value counts @@ -1088,7 +1149,7 @@ static void SaveSingleInstanceBinary( Write out the number of slot value atoms for the whole instance ================================== */ - if (totalValueCount != 0L) + if (theInstance->cls->instanceSlotCount != 0) // (totalValueCount != 0L) : Bug fix if any slots, write out count fwrite((void *) &totalValueCount,(int) sizeof(unsigned long),1,bsaveFP); /* ============================== @@ -1178,13 +1239,13 @@ static void SaveAtomBinary( **********************************************************************/ static long LoadOrRestoreInstances( void *theEnv, - char *file, + const char *file, int usemsgs, int isFileName) { DATA_OBJECT temp; FILE *sfile = NULL,*svload = NULL; - char *ilog; + const char *ilog; EXPRESSION *top; int svoverride; long instanceCount = 0L; @@ -1260,8 +1321,8 @@ static long LoadOrRestoreInstances( ***************************************************/ static void ProcessFileErrorMessage( void *theEnv, - char *functionName, - char *fileName) + const char *functionName, + const char *fileName) { PrintErrorID(theEnv,"INSFILE",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Function "); @@ -1281,12 +1342,12 @@ static void ProcessFileErrorMessage( INPUTS : The name of the file RETURNS : TRUE if OK, FALSE otherwise SIDE EFFECTS : Input prefix and version read - NOTES : Assumes file already open with + NOTES : Assumes file already open with GenOpenReadBinary *******************************************************/ static intBool VerifyBinaryHeader( void *theEnv, - char *theFile) + const char *theFile) { char buf[20]; @@ -1326,15 +1387,14 @@ static intBool LoadSingleBinaryInstance( { SYMBOL_HN *instanceName, *className; - unsigned slotCount; + short slotCount; DEFCLASS *theDefclass; INSTANCE_TYPE *newInstance; struct bsaveSlotValue *bsArray; struct bsaveSlotValueAtom *bsaArray = NULL; long nameIndex; unsigned long totalValueCount; - register unsigned i; - unsigned long j; + long i, j; INSTANCE_SLOT *sp; DATA_OBJECT slotValue,junkValue; @@ -1353,13 +1413,14 @@ static intBool LoadSingleBinaryInstance( /* ================== Get the slot count ================== */ - BufferedRead(theEnv,(void *) &slotCount,(unsigned long) sizeof(unsigned)); + BufferedRead(theEnv,(void *) &slotCount,(unsigned long) sizeof(short)); /* ============================= Make sure the defclass exists and check the slot count ============================= */ - theDefclass = LookupDefclassInScope(theEnv,ValueToString(className)); + //theDefclass = LookupDefclassInScope(theEnv,ValueToString(className)); + theDefclass = LookupDefclassByMdlOrScope(theEnv,ValueToString(className)); if (theDefclass == NULL) { ClassExistError(theEnv,"bload-instances",ValueToString(className)); @@ -1543,6 +1604,7 @@ static void *GetBinaryAtomValue( #endif case EXTERNAL_ADDRESS: return(NULL); + default: { SystemError(theEnv,"INSFILE",1); @@ -1610,7 +1672,7 @@ static void BufferedRead( InstanceFileData(theEnv)->CurrentReadBufferSize = InstanceFileData(theEnv)->BinaryInstanceFileSize - InstanceFileData(theEnv)->BinaryInstanceFileOffset; else InstanceFileData(theEnv)->CurrentReadBufferSize = (unsigned long) MAX_BLOCK_SIZE; - InstanceFileData(theEnv)->CurrentReadBuffer = (char *) genlongalloc(theEnv,InstanceFileData(theEnv)->CurrentReadBufferSize); + InstanceFileData(theEnv)->CurrentReadBuffer = (char *) genalloc(theEnv,InstanceFileData(theEnv)->CurrentReadBufferSize); GenReadBinary(theEnv,(void *) InstanceFileData(theEnv)->CurrentReadBuffer,InstanceFileData(theEnv)->CurrentReadBufferSize); for (i = 0L ; i < bufsz ; i++) ((char *) buf)[i] = InstanceFileData(theEnv)->CurrentReadBuffer[i]; @@ -1632,14 +1694,73 @@ static void FreeReadBuffer( { if (InstanceFileData(theEnv)->CurrentReadBufferSize != 0L) { - genlongfree(theEnv,(void *) InstanceFileData(theEnv)->CurrentReadBuffer,InstanceFileData(theEnv)->CurrentReadBufferSize); + genfree(theEnv,(void *) InstanceFileData(theEnv)->CurrentReadBuffer,InstanceFileData(theEnv)->CurrentReadBufferSize); InstanceFileData(theEnv)->CurrentReadBuffer = NULL; InstanceFileData(theEnv)->CurrentReadBufferSize = 0L; } } +#endif /* BLOAD_INSTANCES */ + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if BLOAD_INSTANCES +globle long BinaryLoadInstances( + const char *theFile) + { + return EnvBinaryLoadInstances(GetCurrentEnvironment(),theFile); + } #endif +#if BSAVE_INSTANCES +globle long BinarySaveInstances( + const char *file, + int saveCode) + { + return EnvBinarySaveInstances(GetCurrentEnvironment(),file,saveCode); + } #endif +globle long LoadInstances( + const char *file) + { + return EnvLoadInstances(GetCurrentEnvironment(),file); + } + +globle long LoadInstancesFromString( + const char *theString, + int theMax) + { + return EnvLoadInstancesFromString(GetCurrentEnvironment(),theString,theMax); + } + +globle long RestoreInstances( + const char *file) + { + return EnvRestoreInstances(GetCurrentEnvironment(),file); + } + +globle long RestoreInstancesFromString( + const char *theString, + int theMax) + { + return EnvRestoreInstancesFromString(GetCurrentEnvironment(),theString,theMax); + } + +globle long SaveInstances( + const char *file, + int saveCode) + { + return EnvSaveInstances(GetCurrentEnvironment(),file,saveCode); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + + +#endif /* OBJECT_SYSTEM */ + diff --git a/src/insfile.h b/src/insfile.h index bc8641a..27164f2 100644 --- a/src/insfile.h +++ b/src/insfile.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* */ /*******************************************************/ @@ -10,13 +10,29 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Corrected code to remove compiler warnings. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -31,10 +47,9 @@ #if BLOAD_INSTANCES || BSAVE_INSTANCES struct instanceFileData - { -#if BLOAD_INSTANCES || BSAVE_INSTANCES - char *InstanceBinaryPrefixID; - char *InstanceBinaryVersionID; + { + const char *InstanceBinaryPrefixID; + const char *InstanceBinaryVersionID; unsigned long BinaryInstanceFileSize; #if BLOAD_INSTANCES @@ -43,13 +58,11 @@ struct instanceFileData unsigned long CurrentReadBufferSize; unsigned long CurrentReadBufferOffset; #endif - -#endif }; #define InstanceFileData(theEnv) ((struct instanceFileData *) GetEnvironmentData(theEnv,INSTANCE_FILE_DATA)) -#endif +#endif /* BLOAD_INSTANCES || BSAVE_INSTANCES */ #ifdef LOCALE #undef LOCALE @@ -61,50 +74,43 @@ struct instanceFileData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define BinaryLoadInstances(theEnv,a) EnvBinaryLoadInstances(theEnv,a) -#define BinarySaveInstances(theEnv,a,b,c,d) EnvBinarySaveInstances(theEnv,a,b,c,d) -#define LoadInstances(theEnv,a) EnvLoadInstances(theEnv,a) -#define LoadInstancesFromString(theEnv,a,b) EnvLoadInstancesFromString(theEnv,a,b) -#define RestoreInstances(theEnv,a) EnvRestoreInstances(theEnv,a) -#define RestoreInstancesFromString(theEnv,a,b) EnvRestoreInstancesFromString(theEnv,a,b) -#define SaveInstances(theEnv,a,b,c,d) EnvSaveInstances(theEnv,a,b,c,d) -#else -#define BinaryLoadInstances(a) EnvBinaryLoadInstances(GetCurrentEnvironment(),a) -#define BinarySaveInstances(a,b,c,d) EnvBinarySaveInstances(GetCurrentEnvironment(),a,b,c,d) -#define LoadInstances(a) EnvLoadInstances(GetCurrentEnvironment(),a) -#define LoadInstancesFromString(a,b) EnvLoadInstancesFromString(GetCurrentEnvironment(),a,b) -#define RestoreInstances(a) EnvRestoreInstances(GetCurrentEnvironment(),a) -#define RestoreInstancesFromString(a,b) EnvRestoreInstancesFromString(GetCurrentEnvironment(),a,b) -#define SaveInstances(a,b,c,d) EnvSaveInstances(GetCurrentEnvironment(),a,b,c,d) -#endif - -LOCALE void SetupInstanceFileCommands(void *); - -LOCALE long SaveInstancesCommand(void *); -LOCALE long LoadInstancesCommand(void *); -LOCALE long RestoreInstancesCommand(void *); -LOCALE long EnvSaveInstances(void *,char *,int,EXPRESSION *,intBool); - + LOCALE void SetupInstanceFileCommands(void *); + LOCALE long SaveInstancesCommand(void *); + LOCALE long LoadInstancesCommand(void *); + LOCALE long RestoreInstancesCommand(void *); + LOCALE long EnvSaveInstancesDriver(void *,const char *,int,EXPRESSION *,intBool); + LOCALE long EnvSaveInstances(void *,const char *,int); #if BSAVE_INSTANCES -LOCALE long BinarySaveInstancesCommand(void *); -LOCALE long EnvBinarySaveInstances(void *,char *,int,EXPRESSION *,intBool); + LOCALE long BinarySaveInstancesCommand(void *); + LOCALE long EnvBinarySaveInstancesDriver(void *,const char *,int,EXPRESSION *,intBool); + LOCALE long EnvBinarySaveInstances(void *,const char *,int); #endif - #if BLOAD_INSTANCES -LOCALE long BinaryLoadInstancesCommand(void *); -LOCALE long EnvBinaryLoadInstances(void *,char *); + LOCALE long BinaryLoadInstancesCommand(void *); + LOCALE long EnvBinaryLoadInstances(void *,const char *); #endif + LOCALE long EnvLoadInstances(void *,const char *); + LOCALE long EnvLoadInstancesFromString(void *,const char *,int); + LOCALE long EnvRestoreInstances(void *,const char *); + LOCALE long EnvRestoreInstancesFromString(void *,const char *,int); -LOCALE long EnvLoadInstances(void *,char *); -LOCALE long EnvLoadInstancesFromString(void *,char *,int); -LOCALE long EnvRestoreInstances(void *,char *); -LOCALE long EnvRestoreInstancesFromString(void *,char *,int); +#if ALLOW_ENVIRONMENT_GLOBALS -#ifndef _INSFILE_SOURCE_ +#if BLOAD_INSTANCES + LOCALE long BinaryLoadInstances(const char *); #endif - +#if BSAVE_INSTANCES + LOCALE long BinarySaveInstances(const char *,int); #endif + LOCALE long LoadInstances(const char *); + LOCALE long LoadInstancesFromString(const char *,int); + LOCALE long RestoreInstances(const char *); + LOCALE long RestoreInstancesFromString(const char *,int); + LOCALE long SaveInstances(const char *,int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_insfile */ diff --git a/src/insfun.c b/src/insfun.c index 3b38d09..32d4329 100644 --- a/src/insfun.c +++ b/src/insfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* INSTANCE FUNCTIONS MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: Internal instance manipulation routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable log to logName */ @@ -38,6 +39,26 @@ /* 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. */ +/* */ /*************************************************************/ /* ========================================= @@ -110,14 +131,11 @@ static void NetworkModifyForSharedSlot(void *,int,DEFCLASS *,SLOT_DESC *); SIDE EFFECTS : Count set NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvIncrementInstanceCount( void *theEnv, void *vptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -133,14 +151,11 @@ globle void EnvIncrementInstanceCount( SIDE EFFECTS : Count set NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvDecrementInstanceCount( void *theEnv, void *vptr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -189,14 +204,13 @@ globle void CleanupInstances( gtmp = InstanceData(theEnv)->InstanceGarbageList; while (gtmp != NULL) { - if ((gtmp->ins->busy == 0) && (gtmp->ins->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) #if DEFRULE_CONSTRUCT - && (gtmp->ins->header.busyCount == 0) + if ((gtmp->ins->busy == 0) + && (gtmp->ins->header.busyCount == 0)) +#else + if (gtmp->ins->busy == 0) #endif - ) { - UtilityData(theEnv)->EphemeralItemCount -= 2; - UtilityData(theEnv)->EphemeralItemSize -= InstanceSizeHeuristic(gtmp->ins) + sizeof(IGARBAGE); DecrementSymbolCount(theEnv,gtmp->ins->name); rtn_struct(theEnv,instance,gtmp->ins); if (gprv == NULL) @@ -286,7 +300,7 @@ globle void RemoveInstanceData( void *theEnv, INSTANCE_TYPE *ins) { - register unsigned i; + long i; INSTANCE_SLOT *sp; DecrementDefclassBusyCount(theEnv,(void *) ins->cls); @@ -326,7 +340,9 @@ globle void RemoveInstanceData( 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 + to the order given in the current module's definition. + Instances of the form [<name>] are now searched for in + all modules. ***************************************************************************/ globle INSTANCE_TYPE *FindInstanceBySymbol( void *theEnv, @@ -345,9 +361,21 @@ globle INSTANCE_TYPE *FindInstanceBySymbol( modulePosition = FindModuleSeparator(ValueToString(moduleAndInstanceName)); if (modulePosition == FALSE) { + /* theModule = currentModule; instanceName = moduleAndInstanceName; searchImports = FALSE; + */ + INSTANCE_TYPE *ins; + + ins = InstanceData(theEnv)->InstanceTable[HashInstance(moduleAndInstanceName)]; + while (ins != NULL) + { + if (ins->name == moduleAndInstanceName) + { return ins; } + ins = ins->nxtHash; + } + return(NULL); } /* ========================================= @@ -393,7 +421,9 @@ globle INSTANCE_TYPE *FindInstanceBySymbol( given module as well RETURNS : The instance (NULL if none found) SIDE EFFECTS : None - NOTES : None + NOTES : The class no longer needs to be in + scope of the current module if the + instance's module name has been specified. ***************************************************/ globle INSTANCE_TYPE *FindInstanceInModule( void *theEnv, @@ -428,8 +458,9 @@ globle INSTANCE_TYPE *FindInstanceInModule( 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) && + // DefclassInScope(theEnv,ins->cls,currentModule)) + if (ins->cls->header.whichModule->theModule == theModule) return(ins); /* ================================ @@ -512,7 +543,7 @@ globle int PutSlotValue( INSTANCE_SLOT *sp, DATA_OBJECT *val, DATA_OBJECT *setVal, - char *theCommand) + const char *theCommand) { if (ValidSlotValue(theEnv,val,sp->desc,ins,theCommand) == FALSE) { @@ -570,8 +601,19 @@ globle int DirectPutSlotValue( (EXPRESSION *) sp->desc->defaultValue,val,TRUE)) return(FALSE); } + else if (sp->desc->defaultValue != NULL) + { val = (DATA_OBJECT *) sp->desc->defaultValue; } else - val = (DATA_OBJECT *) sp->desc->defaultValue; + { + PrintErrorID(theEnv,"INSMNGR",14,FALSE); + EnvPrintRouter(theEnv,WERROR,"Override required for slot "); + EnvPrintRouter(theEnv,WERROR,ValueToString(sp->desc->slotName->name)); + EnvPrintRouter(theEnv,WERROR," in instance "); + EnvPrintRouter(theEnv,WERROR,ValueToString(ins->name)); + EnvPrintRouter(theEnv,WERROR,".\n"); + SetEvaluationError(theEnv,TRUE); + return(FALSE); + } } #if DEFRULE_CONSTRUCT if (EngineData(theEnv)->JoinOperationInProgress && sp->desc->reactive && @@ -737,7 +779,7 @@ globle int ValidSlotValue( DATA_OBJECT *val, SLOT_DESC *sd, INSTANCE_TYPE *ins, - char *theCommand) + const char *theCommand) { register int violationCode; @@ -801,7 +843,7 @@ globle int ValidSlotValue( ********************************************************/ globle INSTANCE_TYPE *CheckInstance( void *theEnv, - char *func) + const char *func) { INSTANCE_TYPE *ins; DATA_OBJECT temp; @@ -852,8 +894,8 @@ globle INSTANCE_TYPE *CheckInstance( ***************************************************/ globle void NoInstanceError( void *theEnv, - char *iname, - char *func) + const char *iname, + const char *func) { PrintErrorID(theEnv,"INSFUN",2,FALSE); EnvPrintRouter(theEnv,WERROR,"No such instance "); @@ -876,7 +918,7 @@ globle void NoInstanceError( ***************************************************/ globle void StaleInstanceAddress( void *theEnv, - char *func, + const char *func, int whichArg) { PrintErrorID(theEnv,"INSFUN",4,FALSE); @@ -885,7 +927,7 @@ globle void StaleInstanceAddress( if (whichArg > 0) { EnvPrintRouter(theEnv,WERROR,", argument #"); - PrintLongInteger(theEnv,WERROR,(long) whichArg); + PrintLongInteger(theEnv,WERROR,(long long) whichArg); } EnvPrintRouter(theEnv,WERROR,".\n"); } @@ -936,10 +978,10 @@ globle void EnvSetInstancesChanged( *******************************************************************/ globle void PrintSlot( void *theEnv, - char *logName, + const char *logName, SLOT_DESC *sd, INSTANCE_TYPE *ins, - char *theCommand) + const char *theCommand) { EnvPrintRouter(theEnv,logName,"slot "); EnvPrintRouter(theEnv,logName,ValueToString(sd->slotName->name)); @@ -974,7 +1016,7 @@ globle void PrintSlot( *****************************************************/ globle void PrintInstanceNameAndClass( void *theEnv, - char *logicalName, + const char *logicalName, INSTANCE_TYPE *theInstance, intBool linefeedFlag) { @@ -983,7 +1025,7 @@ globle void PrintInstanceNameAndClass( EnvPrintRouter(theEnv,logicalName,"] of "); PrintClassName(theEnv,logicalName,theInstance->cls,linefeedFlag); } - + /*************************************************** NAME : PrintInstanceName DESCRIPTION : Used by the rule system commands @@ -997,7 +1039,7 @@ globle void PrintInstanceNameAndClass( ***************************************************/ globle void PrintInstanceName( void *theEnv, - char *logName, + const char *logName, void *vins) { INSTANCE_TYPE *ins; @@ -1016,7 +1058,7 @@ globle void PrintInstanceName( EnvPrintRouter(theEnv,logName,"]"); } } - + /*************************************************** NAME : PrintInstanceLongForm DESCRIPTION : Used by kernel to print @@ -1029,7 +1071,7 @@ globle void PrintInstanceName( ***************************************************/ globle void PrintInstanceLongForm( void *theEnv, - char *logName, + const char *logName, void *vins) { INSTANCE_TYPE *ins = (INSTANCE_TYPE *) vins; @@ -1089,7 +1131,7 @@ globle void DecrementObjectBasisCount( void *vins) { INSTANCE_TYPE *ins; - register unsigned i; + long i; ins = (INSTANCE_TYPE *) vins; ins->header.busyCount--; @@ -1136,7 +1178,7 @@ globle void IncrementObjectBasisCount( void *vins) { INSTANCE_TYPE *ins; - register unsigned i; + long i; ins = (INSTANCE_TYPE *) vins; if (ins->header.busyCount == 0) @@ -1185,19 +1227,37 @@ globle void MatchObjectFunction( SIDE EFFECTS : None NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle intBool NetworkSynchronized( void *theEnv, void *vins) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif return(((INSTANCE_TYPE *) vins)->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 + ***************************************************/ +globle intBool InstanceIsDeleted( + void *theEnv, + void *vins) + { +#if MAC_XCD +#pragma unused(theEnv) +#endif + + return(((INSTANCE_TYPE *) vins)->garbage); + } #endif /* ========================================= @@ -1291,7 +1351,7 @@ static void NetworkModifyForSharedSlot( SLOT_DESC *sd) { INSTANCE_TYPE *ins; - register unsigned i; + long i; /* ================================================ Make sure we haven't already examined this class @@ -1320,8 +1380,39 @@ static void NetworkModifyForSharedSlot( NetworkModifyForSharedSlot(theEnv,sharedTraversalID,cls->directSubclasses.classArray[i],sd); } -#endif +#endif /* DEFRULE_CONSTRUCT */ -#endif +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void DecrementInstanceCount( + void *vptr) + { + EnvDecrementInstanceCount(GetCurrentEnvironment(),vptr); + } + +globle int GetInstancesChanged() + { + return EnvGetInstancesChanged(GetCurrentEnvironment()); + } + +globle void IncrementInstanceCount( + void *vptr) + { + EnvIncrementInstanceCount(GetCurrentEnvironment(),vptr); + } + +globle void SetInstancesChanged( + int changed) + { + EnvSetInstancesChanged(GetCurrentEnvironment(),changed); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* OBJECT_SYSTEM */ diff --git a/src/insfun.h b/src/insfun.h index aef34c5..6dec767 100644 --- a/src/insfun.h +++ b/src/insfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INSTANCE FUNCTIONS MODULE */ /*******************************************************/ @@ -10,12 +10,22 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* 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 */ @@ -28,7 +38,24 @@ /* 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. */ +/* */ +//*************************************************************/ #ifndef _H_insfun #define _H_insfun @@ -66,51 +93,48 @@ typedef struct igarbage #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DecrementInstanceCount(theEnv,a) EnvDecrementInstanceCount(theEnv,a) -#define GetInstancesChanged(theEnv) EnvGetInstancesChanged(theEnv) -#define IncrementInstanceCount(theEnv,a) EnvIncrementInstanceCount(theEnv,a) -#define SetInstancesChanged(theEnv,a) EnvSetInstancesChanged(theEnv,a) -#else -#define DecrementInstanceCount(a) EnvDecrementInstanceCount(GetCurrentEnvironment(),a) -#define GetInstancesChanged() EnvGetInstancesChanged(GetCurrentEnvironment()) -#define IncrementInstanceCount(a) EnvIncrementInstanceCount(GetCurrentEnvironment(),a) -#define SetInstancesChanged(a) EnvSetInstancesChanged(GetCurrentEnvironment(),a) -#endif - -LOCALE void EnvIncrementInstanceCount(void *,void *); -LOCALE void EnvDecrementInstanceCount(void *,void *); -LOCALE void InitializeInstanceTable(void *); -LOCALE void CleanupInstances(void *); -LOCALE unsigned HashInstance(SYMBOL_HN *); -LOCALE void DestroyAllInstances(void *); -LOCALE void RemoveInstanceData(void *,INSTANCE_TYPE *); -LOCALE INSTANCE_TYPE *FindInstanceBySymbol(void *,SYMBOL_HN *); -LOCALE INSTANCE_TYPE *FindInstanceInModule(void *,SYMBOL_HN *,struct defmodule *, + LOCALE void EnvIncrementInstanceCount(void *,void *); + LOCALE void EnvDecrementInstanceCount(void *,void *); + LOCALE void InitializeInstanceTable(void *); + LOCALE void CleanupInstances(void *); + LOCALE unsigned HashInstance(SYMBOL_HN *); + LOCALE void DestroyAllInstances(void *); + LOCALE void RemoveInstanceData(void *,INSTANCE_TYPE *); + LOCALE INSTANCE_TYPE *FindInstanceBySymbol(void *,SYMBOL_HN *); + LOCALE INSTANCE_TYPE *FindInstanceInModule(void *,SYMBOL_HN *,struct defmodule *, struct defmodule *,unsigned); -LOCALE INSTANCE_SLOT *FindInstanceSlot(void *,INSTANCE_TYPE *,SYMBOL_HN *); -LOCALE int FindInstanceTemplateSlot(void *,DEFCLASS *,SYMBOL_HN *); -LOCALE int PutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *,char *); -LOCALE int DirectPutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *); -LOCALE intBool ValidSlotValue(void *,DATA_OBJECT *,SLOT_DESC *,INSTANCE_TYPE *,char *); -LOCALE INSTANCE_TYPE *CheckInstance(void *,char *); -LOCALE void NoInstanceError(void *,char *,char *); -LOCALE void StaleInstanceAddress(void *,char *,int); -LOCALE int EnvGetInstancesChanged(void *); -LOCALE void EnvSetInstancesChanged(void *,int); -LOCALE void PrintSlot(void *,char *,SLOT_DESC *,INSTANCE_TYPE *,char *); -LOCALE void PrintInstanceNameAndClass(void *,char *,INSTANCE_TYPE *,intBool); -LOCALE void PrintInstanceName(void *,char *,void *); -LOCALE void PrintInstanceLongForm(void *,char *,void *); - + LOCALE INSTANCE_SLOT *FindInstanceSlot(void *,INSTANCE_TYPE *,SYMBOL_HN *); + LOCALE int FindInstanceTemplateSlot(void *,DEFCLASS *,SYMBOL_HN *); + LOCALE int PutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *,const char *); + LOCALE int DirectPutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *); + LOCALE intBool ValidSlotValue(void *,DATA_OBJECT *,SLOT_DESC *,INSTANCE_TYPE *,const char *); + LOCALE INSTANCE_TYPE *CheckInstance(void *,const char *); + LOCALE void NoInstanceError(void *,const char *,const char *); + LOCALE void StaleInstanceAddress(void *,const char *,int); + LOCALE int EnvGetInstancesChanged(void *); + LOCALE void EnvSetInstancesChanged(void *,int); + LOCALE void PrintSlot(void *,const char *,SLOT_DESC *,INSTANCE_TYPE *,const char *); + LOCALE void PrintInstanceNameAndClass(void *,const char *,INSTANCE_TYPE *,intBool); + LOCALE void PrintInstanceName(void *,const char *,void *); + LOCALE void PrintInstanceLongForm(void *,const char *,void *); #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM -LOCALE void DecrementObjectBasisCount(void *,void *); -LOCALE void IncrementObjectBasisCount(void *,void *); -LOCALE void MatchObjectFunction(void *,void *); -LOCALE intBool NetworkSynchronized(void *,void *); + LOCALE void DecrementObjectBasisCount(void *,void *); + LOCALE void IncrementObjectBasisCount(void *,void *); + LOCALE void MatchObjectFunction(void *,void *); + LOCALE intBool NetworkSynchronized(void *,void *); + LOCALE intBool InstanceIsDeleted(void *,void *); #endif -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void DecrementInstanceCount(void *); + LOCALE int GetInstancesChanged(void); + LOCALE void IncrementInstanceCount(void *); + LOCALE void SetInstancesChanged(int); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_insfun */ diff --git a/src/insmngr.c b/src/insmngr.c index 40d3a09..3d96c46 100644 --- a/src/insmngr.c +++ b/src/insmngr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* INSTANCE PRIMITIVE SUPPORT MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: Creation and Deletion of Instances Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ @@ -25,6 +26,19 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Newly created instances can no longer use */ +/* a preexisting instance name of another class */ +/* [INSMNGR16]. */ +/* */ /*************************************************************/ /* ========================================= @@ -55,6 +69,7 @@ #include "msgfun.h" #include "prccode.h" #include "router.h" +#include "sysdep.h" #include "utility.h" #define _INSMNGR_SOURCE_ @@ -87,7 +102,7 @@ static int InsertSlotOverrides(void *,INSTANCE_TYPE *,EXPRESSION *); static void EvaluateClassDefaults(void *,INSTANCE_TYPE *); #if DEBUGGING_FUNCTIONS -static void PrintInstanceWatch(void *,char *,INSTANCE_TYPE *); +static void PrintInstanceWatch(void *,const char *,INSTANCE_TYPE *); #endif /* ========================================= @@ -133,6 +148,9 @@ globle void InitializeInstanceCommand( NOTES : H/L Syntax: (active-make-instance <instance-name> of <class> <slot-override>*) + CHANGES : It's now possible to create an instance of a + class that's not in scope if the module name + is specified. ****************************************************************/ globle void MakeInstanceCommand( void *theEnv, @@ -168,7 +186,10 @@ globle void MakeInstanceCommand( SetEvaluationError(theEnv,TRUE); return; } - cls = LookupDefclassInScope(theEnv,DOToString(temp)); + + //cls = LookupDefclassInScope(theEnv,DOToString(temp)); + cls = LookupDefclassByMdlOrScope(theEnv,DOToString(temp)); // Module or scope is now allowed + if (cls == NULL) { ClassExistError(theEnv,ValueToString(ExpressionFunctionCallName(EvaluationData(theEnv)->CurrentExpression)), @@ -181,7 +202,7 @@ globle void MakeInstanceCommand( ins = BuildInstance(theEnv,iname,cls,TRUE); if (ins == NULL) return; - + if (CoreInitializeInstance(theEnv,ins,GetFirstArgument()->nextArg->nextArg) == TRUE) { result->type = INSTANCE_NAME; @@ -207,18 +228,30 @@ globle void MakeInstanceCommand( and new symbol created NOTES : Used to differentiate between instances of the same name in - different modules + different modules. + Instances are now global in scope so + each instance name must belong to a + single instance. It's no longer + necessary to return the full instance + name. ***************************************************/ globle SYMBOL_HN *GetFullInstanceName( void *theEnv, INSTANCE_TYPE *ins) { - char *moduleName,*buffer; - unsigned bufsz; + /* + const char *moduleName; + char *buffer; + size_t bufsz; SYMBOL_HN *iname; + */ if (ins == &InstanceData(theEnv)->DummyInstance) return((SYMBOL_HN *) EnvAddSymbol(theEnv,"Dummy Instance")); + + return(ins->name); + +/* if (ins->garbage) return(ins->name); if (ins->cls->header.whichModule->theModule == ((struct defmodule *) EnvGetCurrentModule(theEnv))) @@ -227,10 +260,11 @@ globle SYMBOL_HN *GetFullInstanceName( bufsz = (sizeof(char) * (strlen(moduleName) + strlen(ValueToString(ins->name)) + 3)); buffer = (char *) gm2(theEnv,bufsz); - sprintf(buffer,"%s::%s",moduleName,ValueToString(ins->name)); + gensprintf(buffer,"%s::%s",moduleName,ValueToString(ins->name)); iname = (SYMBOL_HN *) EnvAddSymbol(theEnv,buffer); rm(theEnv,(void *) buffer,bufsz); return(iname); +*/ } /*************************************************** @@ -296,8 +330,21 @@ globle INSTANCE_TYPE *BuildInstance( iname = ExtractConstructName(theEnv,modulePosition,ValueToString(iname)); } ins = InstanceLocationInfo(theEnv,cls,iname,&iprv,&hashTableIndex); + if (ins != NULL) { + if (ins->cls != cls) + { + PrintErrorID(theEnv,"INSMNGR",16,FALSE); + EnvPrintRouter(theEnv,WERROR,"The instance name "); + EnvPrintRouter(theEnv,WERROR,ValueToString(iname)); + EnvPrintRouter(theEnv,WERROR," is in use by an instance of class "); + EnvPrintRouter(theEnv,WERROR,ValueToString(ins->cls->header.name)); + EnvPrintRouter(theEnv,WERROR,".\n"); + SetEvaluationError(theEnv,TRUE); + return(NULL); + } + if (ins->installed == 0) { PrintErrorID(theEnv,"INSMNGR",4,FALSE); @@ -534,14 +581,15 @@ globle intBool QuashInstance( rule, don't bother deleting its slots yet, for they may still be needed by pattern variables ============================================== */ - if ((iflag == 1) #if DEFRULE_CONSTRUCT - && (ins->header.busyCount == 0) + if ((iflag == 1) + && (ins->header.busyCount == 0)) +#else + if (iflag == 1) #endif - ) RemoveInstanceData(theEnv,ins); - if ((ins->busy == 0) && (ins->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) && + if ((ins->busy == 0) && (InstanceData(theEnv)->MaintainGarbageInstances == FALSE) #if DEFRULE_CONSTRUCT && (ins->header.busyCount == 0) @@ -558,8 +606,7 @@ globle intBool QuashInstance( gptr->ins = ins; gptr->nxt = InstanceData(theEnv)->InstanceGarbageList; InstanceData(theEnv)->InstanceGarbageList = gptr; - UtilityData(theEnv)->EphemeralItemCount += 2; - UtilityData(theEnv)->EphemeralItemSize += InstanceSizeHeuristic(ins) + sizeof(IGARBAGE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; } InstanceData(theEnv)->ChangesToInstances = TRUE; return(1); @@ -654,7 +701,6 @@ static INSTANCE_TYPE *NewInstance( instance->garbage = 0; instance->initSlotsCalled = 0; instance->initializeInProgress = 0; - instance->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; instance->name = NULL; instance->hashTableIndex = 0; instance->cls = NULL; @@ -680,7 +726,9 @@ static INSTANCE_TYPE *NewInstance( RETURNS : The address of the found instance, NULL otherwise SIDE EFFECTS : None NOTES : Instance names only have to be unique within - a module + a module. + Change: instance names must be unique regardless + of module. *****************************************************************/ static INSTANCE_TYPE *InstanceLocationInfo( void *theEnv, @@ -700,6 +748,15 @@ static INSTANCE_TYPE *InstanceLocationInfo( module their classes are in ======================================== */ *prv = NULL; + while (ins != NULL) + { + if (ins->name == iname) + { return(ins); } + *prv = ins; + ins = ins->nxtHash; + } + + /* while ((ins != NULL) ? (ins->name != iname) : FALSE) { *prv = ins; @@ -713,6 +770,7 @@ static INSTANCE_TYPE *InstanceLocationInfo( *prv = ins; ins = ins->nxtHash; } + */ return(NULL); } @@ -743,7 +801,6 @@ static void InstallInstance( PrintInstanceWatch(theEnv,MAKE_TRACE,ins); #endif ins->installed = 1; - ins->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; IncrementSymbolCount(ins->name); IncrementDefclassBusyCount(theEnv,(void *) ins->cls); InstanceData(theEnv)->GlobalNumberOfInstances++; @@ -914,7 +971,7 @@ static int CoreInitializeInstance( EnvPrintRouter(theEnv,WERROR,".\n"); return(FALSE); } - + ins->initializeInProgress = 0; return((ins->initSlotsCalled == 0) ? FALSE : TRUE); } @@ -1007,7 +1064,7 @@ static void EvaluateClassDefaults( { INSTANCE_SLOT *slot; DATA_OBJECT temp,junk; - register unsigned i; + long i; if (ins->initializeInProgress == 0) { @@ -1077,7 +1134,7 @@ static void EvaluateClassDefaults( ***************************************************/ static void PrintInstanceWatch( void *theEnv, - char *traceString, + const char *traceString, INSTANCE_TYPE *theInstance) { EnvPrintRouter(theEnv,WTRACE,traceString); diff --git a/src/insmngr.h b/src/insmngr.h index 3b8fc44..3dc7a4b 100644 --- a/src/insmngr.h +++ b/src/insmngr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INSTANCE PRIMITIVE SUPPORT MODULE */ /*******************************************************/ @@ -10,17 +10,30 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_insmngr @@ -40,19 +53,19 @@ #define LOCALE extern #endif -LOCALE void InitializeInstanceCommand(void *,DATA_OBJECT *); -LOCALE void MakeInstanceCommand(void *,DATA_OBJECT *); -LOCALE SYMBOL_HN *GetFullInstanceName(void *,INSTANCE_TYPE *); -LOCALE INSTANCE_TYPE *BuildInstance(void *,SYMBOL_HN *,DEFCLASS *,intBool); -LOCALE void InitSlotsCommand(void *,DATA_OBJECT *); -LOCALE intBool QuashInstance(void *,INSTANCE_TYPE *); + LOCALE void InitializeInstanceCommand(void *,DATA_OBJECT *); + LOCALE void MakeInstanceCommand(void *,DATA_OBJECT *); + LOCALE SYMBOL_HN *GetFullInstanceName(void *,INSTANCE_TYPE *); + LOCALE INSTANCE_TYPE *BuildInstance(void *,SYMBOL_HN *,DEFCLASS *,intBool); + LOCALE void InitSlotsCommand(void *,DATA_OBJECT *); + LOCALE intBool QuashInstance(void *,INSTANCE_TYPE *); #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM -LOCALE void InactiveInitializeInstance(void *,DATA_OBJECT *); -LOCALE void InactiveMakeInstance(void *,DATA_OBJECT *); + LOCALE void InactiveInitializeInstance(void *,DATA_OBJECT *); + LOCALE void InactiveMakeInstance(void *,DATA_OBJECT *); #endif -#endif +#endif /* _H_insmngr */ diff --git a/src/insmoddp.c b/src/insmoddp.c index eed4efa..5718284 100644 --- a/src/insmoddp.c +++ b/src/insmoddp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INSTANCE MODIFY AND DUPLICATE MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: Instance modify and duplicate support routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable exp to theExp */ @@ -25,6 +26,13 @@ /* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ +/* 6.30: Added DATA_OBJECT_ARRAY primitive type. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* The return value of DirectMessage indicates */ +/* whether an execution error has occurred. */ +/* */ /*************************************************************/ /* ========================================= @@ -186,7 +194,7 @@ globle void ModifyInstance( to whatever message-handler implements the modify ====================================== */ - theExp.type = EXTERNAL_ADDRESS; + theExp.type = DATA_OBJECT_ARRAY; theExp.value = (void *) overrides; theExp.argList = NULL; theExp.nextArg = NULL; @@ -253,7 +261,7 @@ globle void MsgModifyInstance( to whatever message-handler implements the modify ====================================== */ - theExp.type = EXTERNAL_ADDRESS; + theExp.type = DATA_OBJECT_ARRAY; theExp.value = (void *) overrides; theExp.argList = NULL; theExp.nextArg = NULL; @@ -333,7 +341,7 @@ globle void DuplicateInstance( theExp[0].value = newName.value; theExp[0].argList = NULL; theExp[0].nextArg = &theExp[1]; - theExp[1].type = EXTERNAL_ADDRESS; + theExp[1].type = DATA_OBJECT_ARRAY; theExp[1].value = (void *) overrides; theExp[1].argList = NULL; theExp[1].nextArg = NULL; @@ -413,7 +421,7 @@ globle void MsgDuplicateInstance( theExp[0].value = newName.value; theExp[0].argList = NULL; theExp[0].nextArg = &theExp[1]; - theExp[1].type = EXTERNAL_ADDRESS; + theExp[1].type = DATA_OBJECT_ARRAY; theExp[1].value = (void *) overrides; theExp[1].argList = NULL; theExp[1].nextArg = NULL; @@ -790,9 +798,7 @@ static void ModifyMsgHandlerSupport( msgExp.value = (void *) slotOverrides; msgExp.argList = NULL; msgExp.nextArg = NULL; - DirectMessage(theEnv,insSlot->desc->overrideMessage,ins,&temp,&msgExp); - if (EvaluationData(theEnv)->EvaluationError || - ((temp.type == SYMBOL) && (temp.value == EnvFalseSymbol(theEnv)))) + if (! DirectMessage(theEnv,insSlot->desc->overrideMessage,ins,&temp,&msgExp)) return; } else @@ -841,10 +847,11 @@ static void DuplicateMsgHandlerSupport( SYMBOL_HN *newName; DATA_OBJECT *slotOverrides; EXPRESSION *valArg,msgExp; - unsigned i; + long i; int oldMkInsMsgPass; INSTANCE_SLOT *dstInsSlot; DATA_OBJECT temp,junk,*newval; + intBool success; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); @@ -917,9 +924,7 @@ static void DuplicateMsgHandlerSupport( msgExp.value = (void *) slotOverrides; msgExp.argList = NULL; msgExp.nextArg = NULL; - DirectMessage(theEnv,dstInsSlot->desc->overrideMessage,dstins,&temp,&msgExp); - if (EvaluationData(theEnv)->EvaluationError || - ((temp.type == SYMBOL) && (temp.value == EnvFalseSymbol(theEnv)))) + if (! DirectMessage(theEnv,dstInsSlot->desc->overrideMessage,dstins,&temp,&msgExp)) goto DuplicateError; } else @@ -961,11 +966,10 @@ static void DuplicateMsgHandlerSupport( SetDOEnd(temp,GetMFLength(temp.value)); } valArg = ConvertValueToExpression(theEnv,&temp); - DirectMessage(theEnv,dstins->slots[i].desc->overrideMessage, + success = DirectMessage(theEnv,dstins->slots[i].desc->overrideMessage, dstins,&temp,valArg); ReturnExpression(theEnv,valArg); - if (EvaluationData(theEnv)->EvaluationError || - ((temp.type == SYMBOL) && (temp.value == EnvFalseSymbol(theEnv)))) + if (! success) goto DuplicateError; } else diff --git a/src/insmoddp.h b/src/insmoddp.h index c06d7e4..def8b5c 100644 --- a/src/insmoddp.h +++ b/src/insmoddp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INSTANCE MODIFY AND DUPLICATE MODULE */ /*******************************************************/ @@ -10,15 +10,28 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ +/* 6.30: Added DATA_OBJECT_ARRAY primitive type. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* The return value of DirectMessage indicates */ +/* whether an execution error has occurred. */ +/* */ /*************************************************************/ #ifndef _H_insmoddp @@ -44,30 +57,27 @@ #endif #if (! RUN_TIME) -LOCALE void SetupInstanceModDupCommands(void *); + LOCALE void SetupInstanceModDupCommands(void *); #endif -LOCALE void ModifyInstance(void *,DATA_OBJECT *); -LOCALE void MsgModifyInstance(void *,DATA_OBJECT *); -LOCALE void DuplicateInstance(void *,DATA_OBJECT *); -LOCALE void MsgDuplicateInstance(void *,DATA_OBJECT *); + LOCALE void ModifyInstance(void *,DATA_OBJECT *); + LOCALE void MsgModifyInstance(void *,DATA_OBJECT *); + LOCALE void DuplicateInstance(void *,DATA_OBJECT *); + LOCALE void MsgDuplicateInstance(void *,DATA_OBJECT *); #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM -LOCALE void InactiveModifyInstance(void *,DATA_OBJECT *); -LOCALE void InactiveMsgModifyInstance(void *,DATA_OBJECT *); -LOCALE void InactiveDuplicateInstance(void *,DATA_OBJECT *); -LOCALE void InactiveMsgDuplicateInstance(void *,DATA_OBJECT *); + LOCALE void InactiveModifyInstance(void *,DATA_OBJECT *); + LOCALE void InactiveMsgModifyInstance(void *,DATA_OBJECT *); + LOCALE void InactiveDuplicateInstance(void *,DATA_OBJECT *); + LOCALE void InactiveMsgDuplicateInstance(void *,DATA_OBJECT *); #endif -LOCALE void DirectModifyMsgHandler(void *,DATA_OBJECT *); -LOCALE void MsgModifyMsgHandler(void *,DATA_OBJECT *); -LOCALE void DirectDuplicateMsgHandler(void *,DATA_OBJECT *); -LOCALE void MsgDuplicateMsgHandler(void *,DATA_OBJECT *); - -#ifndef _INSMODDP_SOURCE_ -#endif + LOCALE void DirectModifyMsgHandler(void *,DATA_OBJECT *); + LOCALE void MsgModifyMsgHandler(void *,DATA_OBJECT *); + LOCALE void DirectDuplicateMsgHandler(void *,DATA_OBJECT *); + LOCALE void MsgDuplicateMsgHandler(void *,DATA_OBJECT *); -#endif +#endif /* _H_insmoddp */ diff --git a/src/insmult.c b/src/insmult.c index f3f3389..7fdf67f 100644 --- a/src/insmult.c +++ b/src/insmult.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INSTANCE MULTIFIELD SLOT MODULE */ /*******************************************************/ @@ -10,15 +10,21 @@ /* Purpose: Access routines for Instance Multifield Slots */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ /* ========================================= @@ -57,9 +63,9 @@ ========================================= ***************************************** */ -static INSTANCE_TYPE *CheckMultifieldSlotInstance(void *,char *); -static INSTANCE_SLOT *CheckMultifieldSlotModify(void *,int,char *,INSTANCE_TYPE *, - EXPRESSION *,int *,int *,DATA_OBJECT *); +static INSTANCE_TYPE *CheckMultifieldSlotInstance(void *,const char *); +static INSTANCE_SLOT *CheckMultifieldSlotModify(void *,int,const char *,INSTANCE_TYPE *, + EXPRESSION *,long *,long *,DATA_OBJECT *); static void AssignSlotToDataObject(DATA_OBJECT *,INSTANCE_SLOT *); /* ========================================= @@ -137,7 +143,7 @@ globle void MVSlotReplaceCommand( DATA_OBJECT newval,newseg,oldseg; INSTANCE_TYPE *ins; INSTANCE_SLOT *sp; - int rb,re; + long rb,re; EXPRESSION arg; result->type = SYMBOL; @@ -177,7 +183,7 @@ globle void MVSlotInsertCommand( DATA_OBJECT newval,newseg,oldseg; INSTANCE_TYPE *ins; INSTANCE_SLOT *sp; - int theIndex; + long theIndex; EXPRESSION arg; result->type = SYMBOL; @@ -218,7 +224,7 @@ globle void MVSlotDeleteCommand( DATA_OBJECT newseg,oldseg; INSTANCE_TYPE *ins; INSTANCE_SLOT *sp; - int rb,re; + long rb,re; EXPRESSION arg; result->type = SYMBOL; @@ -254,7 +260,7 @@ globle intBool DirectMVReplaceCommand( { INSTANCE_SLOT *sp; INSTANCE_TYPE *ins; - int rb,re; + long rb,re; DATA_OBJECT newval,newseg,oldseg; if (CheckCurrentMessage(theEnv,"direct-slot-replace$",TRUE) == FALSE) @@ -286,7 +292,7 @@ globle intBool DirectMVInsertCommand( { INSTANCE_SLOT *sp; INSTANCE_TYPE *ins; - int theIndex; + long theIndex; DATA_OBJECT newval,newseg,oldseg; if (CheckCurrentMessage(theEnv,"direct-slot-insert$",TRUE) == FALSE) @@ -319,7 +325,7 @@ globle intBool DirectMVDeleteCommand( { INSTANCE_SLOT *sp; INSTANCE_TYPE *ins; - int rb,re; + long rb,re; DATA_OBJECT newseg,oldseg; if (CheckCurrentMessage(theEnv,"direct-slot-delete$",TRUE) == FALSE) @@ -355,7 +361,7 @@ globle intBool DirectMVDeleteCommand( **********************************************************************/ static INSTANCE_TYPE *CheckMultifieldSlotInstance( void *theEnv, - char *func) + const char *func) { INSTANCE_TYPE *ins; DATA_OBJECT temp; @@ -415,11 +421,11 @@ static INSTANCE_TYPE *CheckMultifieldSlotInstance( static INSTANCE_SLOT *CheckMultifieldSlotModify( void *theEnv, int code, - char *func, + const char *func, INSTANCE_TYPE *ins, EXPRESSION *args, - int *rb, - int *re, + long *rb, + long *re, DATA_OBJECT *newval) { DATA_OBJECT temp; @@ -462,7 +468,7 @@ static INSTANCE_SLOT *CheckMultifieldSlotModify( return(NULL); } args = args->nextArg->nextArg; - *rb = ValueToInteger(temp.value); + *rb = (long) ValueToLong(temp.value); if ((code == REPLACE) || (code == DELETE_OP)) { EvaluateExpression(theEnv,args,&temp); @@ -472,7 +478,7 @@ static INSTANCE_SLOT *CheckMultifieldSlotModify( SetEvaluationError(theEnv,TRUE); return(NULL); } - *re = ValueToInteger(temp.value); + *re = (long) ValueToLong(temp.value); args = args->nextArg; } if ((code == INSERT) || (code == REPLACE)) diff --git a/src/insmult.h b/src/insmult.h index bc2c686..5f4ad52 100644 --- a/src/insmult.h +++ b/src/insmult.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,14 +10,21 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_insmult @@ -38,20 +45,17 @@ #endif #if (! RUN_TIME) -LOCALE void SetupInstanceMultifieldCommands(void *); + LOCALE void SetupInstanceMultifieldCommands(void *); #endif -LOCALE void MVSlotReplaceCommand(void *,DATA_OBJECT *); -LOCALE void MVSlotInsertCommand(void *,DATA_OBJECT *); -LOCALE void MVSlotDeleteCommand(void *,DATA_OBJECT *); -LOCALE intBool DirectMVReplaceCommand(void *); -LOCALE intBool DirectMVInsertCommand(void *); -LOCALE intBool DirectMVDeleteCommand(void *); + LOCALE void MVSlotReplaceCommand(void *,DATA_OBJECT *); + LOCALE void MVSlotInsertCommand(void *,DATA_OBJECT *); + LOCALE void MVSlotDeleteCommand(void *,DATA_OBJECT *); + LOCALE intBool DirectMVReplaceCommand(void *); + LOCALE intBool DirectMVInsertCommand(void *); + LOCALE intBool DirectMVDeleteCommand(void *); -#ifndef _INSMULT_SOURCE_ -#endif - -#endif +#endif /* _H_insmult */ diff --git a/src/inspsr.c b/src/inspsr.c index 5c22cfe..2145407 100644 --- a/src/inspsr.c +++ b/src/inspsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* INSTANCE PARSER MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: Instance Function Parsing Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable exp to theExp */ @@ -23,6 +24,19 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed ParseSlotOverrides memory release issue. */ +/* */ +/* It's now possible to create an instance of a */ +/* class that's not in scope if the module name */ +/* is specified. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ /* ========================================= @@ -163,7 +177,7 @@ static intBool ReplaceClassNameWithReference(void *,EXPRESSION *); globle EXPRESSION *ParseInitializeInstance( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { int error,fcalltype,readclass; @@ -329,10 +343,11 @@ ParseInitializeInstanceError: ********************************************************************************/ globle EXPRESSION *ParseSlotOverrides( void *theEnv, - char *readSource, + const char *readSource, int *error) { EXPRESSION *top = NULL,*bot = NULL,*theExp; + EXPRESSION *theExpNext; while (GetType(DefclassData(theEnv)->ObjectParseToken) == LPAREN) { @@ -351,13 +366,15 @@ globle EXPRESSION *ParseSlotOverrides( SetEvaluationError(theEnv,TRUE); return(NULL); } - theExp->nextArg = GenConstant(theEnv,SYMBOL,EnvTrueSymbol(theEnv)); - if (CollectArguments(theEnv,theExp->nextArg,readSource) == NULL) + theExpNext = GenConstant(theEnv,SYMBOL,EnvTrueSymbol(theEnv)); + if (CollectArguments(theEnv,theExpNext,readSource) == NULL) { *error = TRUE; ReturnExpression(theEnv,top); + ReturnExpression(theEnv,theExp); return(NULL); } + theExp->nextArg = theExpNext; if (top == NULL) top = theExp; else @@ -410,7 +427,7 @@ globle EXPRESSION *ParseSlotOverrides( globle EXPRESSION *ParseSimpleInstance( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *theExp,*vals = NULL,*vbot,*tval; unsigned short type; @@ -524,18 +541,22 @@ SlotOverrideError: modified if class is found NOTES : Searches current nd imported modules for reference + CHANGES : It's now possible to create an instance of a + class that's not in scope if the module name + is specified. ***************************************************/ static intBool ReplaceClassNameWithReference( void *theEnv, EXPRESSION *theExp) { - char *theClassName; + const char *theClassName; void *theDefclass; if (theExp->type == SYMBOL) { theClassName = ValueToString(theExp->value); - theDefclass = (void *) LookupDefclassInScope(theEnv,theClassName); + //theDefclass = (void *) LookupDefclassInScope(theEnv,theClassName); + theDefclass = (void *) LookupDefclassByMdlOrScope(theEnv,theClassName); // Module or scope is now allowed if (theDefclass == NULL) { CantFindItemErrorMessage(theEnv,"class",theClassName); @@ -551,6 +572,11 @@ static intBool ReplaceClassNameWithReference( } theExp->type = DEFCLASS_PTR; theExp->value = theDefclass; + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif } return(TRUE); } diff --git a/src/inspsr.h b/src/inspsr.h index c02441a..a903cdb 100644 --- a/src/inspsr.h +++ b/src/inspsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,25 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed ParseSlotOverrides memory release issue. */ +/* */ /*************************************************************/ #ifndef _H_inspsr @@ -36,16 +49,13 @@ #endif #if ! RUN_TIME -LOCALE EXPRESSION *ParseInitializeInstance(void *,EXPRESSION *,char *); -LOCALE EXPRESSION *ParseSlotOverrides(void *,char *,int *); + LOCALE EXPRESSION *ParseInitializeInstance(void *,EXPRESSION *,const char *); + LOCALE EXPRESSION *ParseSlotOverrides(void *,const char *,int *); #endif -LOCALE EXPRESSION *ParseSimpleInstance(void *,EXPRESSION *,char *); - -#ifndef _INSCOM_SOURCE_ -#endif + LOCALE EXPRESSION *ParseSimpleInstance(void *,EXPRESSION *,const char *); -#endif +#endif /* _H_inspsr */ diff --git a/src/insquery.c b/src/insquery.c index 9368280..f3bea31 100644 --- a/src/insquery.c +++ b/src/insquery.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: Query Functions for Objects */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -23,6 +24,13 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -59,8 +67,8 @@ static void PushQueryCore(void *); static void PopQueryCore(void *); static QUERY_CORE *FindQueryCore(void *,int); -static QUERY_CLASS *DetermineQueryClasses(void *,EXPRESSION *,char *,unsigned *); -static QUERY_CLASS *FormChain(void *,char *,DATA_OBJECT *); +static QUERY_CLASS *DetermineQueryClasses(void *,EXPRESSION *,const char *,unsigned *); +static QUERY_CLASS *FormChain(void *,const char *,DATA_OBJECT *); static void DeleteQueryClasses(void *,QUERY_CLASS *); static int TestForFirstInChain(void *,QUERY_CLASS *,int); static int TestForFirstInstanceInClass(void *,struct defmodule *,int,DEFCLASS *,QUERY_CLASS *,int); @@ -133,8 +141,8 @@ globle void *GetQueryInstance( { register QUERY_CORE *core; - core = FindQueryCore(theEnv,DOPToInteger(GetFirstArgument())); - return(GetFullInstanceName(theEnv,core->solns[DOPToInteger(GetFirstArgument()->nextArg)])); + core = FindQueryCore(theEnv,ValueToInteger(GetpValue(GetFirstArgument()))); + return(GetFullInstanceName(theEnv,core->solns[ValueToInteger(GetpValue(GetFirstArgument()->nextArg))])); } /*************************************************************************** @@ -158,8 +166,8 @@ globle void GetQueryInstanceSlot( result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); - core = FindQueryCore(theEnv,DOPToInteger(GetFirstArgument())); - ins = core->solns[DOPToInteger(GetFirstArgument()->nextArg)]; + core = FindQueryCore(theEnv,ValueToInteger(GetpValue(GetFirstArgument()))); + ins = core->solns[ValueToInteger(GetpValue(GetFirstArgument()->nextArg))]; EvaluateExpression(theEnv,GetFirstArgument()->nextArg->nextArg,&temp); if (temp.type != SYMBOL) { @@ -454,6 +462,7 @@ globle void QueryDoForAllInstances( "do-for-all-instances",&rcnt); if (qclasses == NULL) return; + PushQueryCore(theEnv); InstanceQueryData(theEnv)->QueryCore = get_struct(theEnv,query_core); InstanceQueryData(theEnv)->QueryCore->solns = (INSTANCE_TYPE **) gm2(theEnv,(sizeof(INSTANCE_TYPE *) * rcnt)); @@ -463,7 +472,7 @@ globle void QueryDoForAllInstances( ValueInstall(theEnv,InstanceQueryData(theEnv)->QueryCore->result); TestEntireChain(theEnv,qclasses,0); ValueDeinstall(theEnv,InstanceQueryData(theEnv)->QueryCore->result); - PropagateReturnValue(theEnv,InstanceQueryData(theEnv)->QueryCore->result); + InstanceQueryData(theEnv)->AbortQuery = FALSE; ProcedureFunctionData(theEnv)->BreakFlag = FALSE; rm(theEnv,(void *) InstanceQueryData(theEnv)->QueryCore->solns,(sizeof(INSTANCE_TYPE *) * rcnt)); @@ -496,6 +505,8 @@ globle void DelayedQueryDoForAllInstances( QUERY_CLASS *qclasses; unsigned rcnt; register unsigned i; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); @@ -503,6 +514,7 @@ globle void DelayedQueryDoForAllInstances( "delayed-do-for-all-instances",&rcnt); if (qclasses == NULL) return; + PushQueryCore(theEnv); InstanceQueryData(theEnv)->QueryCore = get_struct(theEnv,query_core); InstanceQueryData(theEnv)->QueryCore->solns = (INSTANCE_TYPE **) gm2(theEnv,(sizeof(INSTANCE_TYPE *) * rcnt)); @@ -514,24 +526,33 @@ globle void DelayedQueryDoForAllInstances( TestEntireChain(theEnv,qclasses,0); InstanceQueryData(theEnv)->AbortQuery = FALSE; InstanceQueryData(theEnv)->QueryCore->action = GetFirstArgument()->nextArg; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + while (InstanceQueryData(theEnv)->QueryCore->soln_set != NULL) { for (i = 0 ; i < rcnt ; i++) InstanceQueryData(theEnv)->QueryCore->solns[i] = InstanceQueryData(theEnv)->QueryCore->soln_set->soln[i]; PopQuerySoln(theEnv); - EvaluationData(theEnv)->CurrentEvaluationDepth++; EvaluateExpression(theEnv,InstanceQueryData(theEnv)->QueryCore->action,result); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - if (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE) - { PropagateReturnValue(theEnv,result); } - PeriodicCleanup(theEnv,FALSE,TRUE); + if (EvaluationData(theEnv)->HaltExecution || ProcedureFunctionData(theEnv)->BreakFlag || ProcedureFunctionData(theEnv)->ReturnFlag) { while (InstanceQueryData(theEnv)->QueryCore->soln_set != NULL) PopQuerySoln(theEnv); break; } + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + ProcedureFunctionData(theEnv)->BreakFlag = FALSE; rm(theEnv,(void *) InstanceQueryData(theEnv)->QueryCore->solns,(sizeof(INSTANCE_TYPE *) * rcnt)); rtn_struct(theEnv,query_core,InstanceQueryData(theEnv)->QueryCore); @@ -636,7 +657,7 @@ static QUERY_CORE *FindQueryCore( static QUERY_CLASS *DetermineQueryClasses( void *theEnv, EXPRESSION *classExp, - char *func, + const char *func, unsigned *rcnt) { QUERY_CLASS *clist = NULL,*cnxt = NULL,*cchain = NULL,*tmp; @@ -698,13 +719,13 @@ static QUERY_CLASS *DetermineQueryClasses( *************************************************************/ static QUERY_CLASS *FormChain( void *theEnv, - char *func, + const char *func, DATA_OBJECT *val) { DEFCLASS *cls; QUERY_CLASS *head,*bot,*tmp; register long i,end; /* 6.04 Bug Fix */ - char *className; + const char *className; struct defmodule *currentModule; currentModule = ((struct defmodule *) EnvGetCurrentModule(theEnv)); @@ -879,15 +900,23 @@ static int TestForFirstInstanceInClass( QUERY_CLASS *qchain, int indx) { - register unsigned i; + long i; INSTANCE_TYPE *ins; DATA_OBJECT temp; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; if (TestTraversalID(cls->traversalRecord,id)) return(FALSE); SetTraversalID(cls->traversalRecord,id); if (DefclassInScope(theEnv,cls,theModule) == FALSE) return(FALSE); + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + ins = cls->instanceList; while (ins != NULL) { @@ -907,10 +936,7 @@ static int TestForFirstInstanceInClass( else { ins->busy++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; EvaluateExpression(theEnv,InstanceQueryData(theEnv)->QueryCore->query,&temp); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); ins->busy--; if (EvaluationData(theEnv)->HaltExecution == TRUE) break; @@ -918,10 +944,18 @@ static int TestForFirstInstanceInClass( (temp.value != EnvFalseSymbol(theEnv))) break; } + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + ins = ins->nxtClass; while ((ins != NULL) ? (ins->garbage == 1) : FALSE) ins = ins->nxtClass; } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame, oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + if (ins != NULL) return(((EvaluationData(theEnv)->HaltExecution == TRUE) || (InstanceQueryData(theEnv)->AbortQuery == TRUE)) ? FALSE : TRUE); @@ -993,15 +1027,23 @@ static void TestEntireClass( QUERY_CLASS *qchain, int indx) { - register unsigned i; + long i; INSTANCE_TYPE *ins; DATA_OBJECT temp; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; if (TestTraversalID(cls->traversalRecord,id)) return; SetTraversalID(cls->traversalRecord,id); if (DefclassInScope(theEnv,cls,theModule) == FALSE) return; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + ins = cls->instanceList; while (ins != NULL) { @@ -1017,10 +1059,9 @@ static void TestEntireClass( else { ins->busy++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; + EvaluateExpression(theEnv,InstanceQueryData(theEnv)->QueryCore->query,&temp); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + ins->busy--; if (EvaluationData(theEnv)->HaltExecution == TRUE) break; @@ -1030,12 +1071,11 @@ static void TestEntireClass( if (InstanceQueryData(theEnv)->QueryCore->action != NULL) { ins->busy++; - EvaluationData(theEnv)->CurrentEvaluationDepth++; + ValueDeinstall(theEnv,InstanceQueryData(theEnv)->QueryCore->result); EvaluateExpression(theEnv,InstanceQueryData(theEnv)->QueryCore->action,InstanceQueryData(theEnv)->QueryCore->result); ValueInstall(theEnv,InstanceQueryData(theEnv)->QueryCore->result); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - PeriodicCleanup(theEnv,FALSE,TRUE); + ins->busy--; if (ProcedureFunctionData(theEnv)->BreakFlag || ProcedureFunctionData(theEnv)->ReturnFlag) { @@ -1049,11 +1089,18 @@ static void TestEntireClass( AddSolution(theEnv); } } - + ins = ins->nxtClass; while ((ins != NULL) ? (ins->garbage == 1) : FALSE) ins = ins->nxtClass; + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame, oldGarbageFrame,NULL); + CallPeriodicTasks(theEnv); + if (ins != NULL) return; for (i = 0 ; i < cls->directSubclasses.classCount ; i++) diff --git a/src/insquery.h b/src/insquery.h index dbcf7c1..9898ff0 100644 --- a/src/insquery.h +++ b/src/insquery.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,16 +10,26 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_insquery @@ -62,7 +72,7 @@ typedef struct query_stack #define INSTANCE_QUERY_DATA 31 struct instanceQueryData - { + { SYMBOL_HN *QUERY_DELIMETER_SYMBOL; QUERY_CORE *QueryCore; QUERY_STACK *QueryCoreStack; @@ -71,7 +81,6 @@ struct instanceQueryData #define InstanceQueryData(theEnv) ((struct instanceQueryData *) GetEnvironmentData(theEnv,INSTANCE_QUERY_DATA)) - #ifdef LOCALE #undef LOCALE #endif @@ -84,19 +93,19 @@ struct instanceQueryData #define QUERY_DELIMETER_STRING "(QDS)" -LOCALE void SetupQuery(void *); -LOCALE void *GetQueryInstance(void *); -LOCALE void GetQueryInstanceSlot(void *,DATA_OBJECT *); -LOCALE intBool AnyInstances(void *); -LOCALE void QueryFindInstance(void *,DATA_OBJECT *); -LOCALE void QueryFindAllInstances(void *,DATA_OBJECT *); -LOCALE void QueryDoForInstance(void *,DATA_OBJECT *); -LOCALE void QueryDoForAllInstances(void *,DATA_OBJECT *); -LOCALE void DelayedQueryDoForAllInstances(void *,DATA_OBJECT *); + LOCALE void SetupQuery(void *); + LOCALE void *GetQueryInstance(void *); + LOCALE void GetQueryInstanceSlot(void *,DATA_OBJECT *); + LOCALE intBool AnyInstances(void *); + LOCALE void QueryFindInstance(void *,DATA_OBJECT *); + LOCALE void QueryFindAllInstances(void *,DATA_OBJECT *); + LOCALE void QueryDoForInstance(void *,DATA_OBJECT *); + LOCALE void QueryDoForAllInstances(void *,DATA_OBJECT *); + LOCALE void DelayedQueryDoForAllInstances(void *,DATA_OBJECT *); -#endif +#endif /* INSTANCE_SET_QUERIES */ -#endif +#endif /* _H_insquery */ diff --git a/src/insqypsr.c b/src/insqypsr.c index 6ceaff1..eec8f57 100644 --- a/src/insqypsr.c +++ b/src/insqypsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* INSTANCE-SET QUERIES PARSER MODULE */ /*******************************************************/ @@ -10,18 +10,32 @@ /* Purpose: Instance_set Queries Parsing Routines */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Fixed memory leaks when error occurred. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ /*************************************************************/ /* ========================================= @@ -62,10 +76,10 @@ ========================================= ***************************************** */ -static EXPRESSION *ParseQueryRestrictions(void *,EXPRESSION *,char *,struct token *); +static EXPRESSION *ParseQueryRestrictions(void *,EXPRESSION *,const char *,struct token *); static intBool ReplaceClassNameWithReference(void *,EXPRESSION *); -static int ParseQueryTestExpression(void *,EXPRESSION *,char *); -static int ParseQueryActionExpression(void *,EXPRESSION *,char *,EXPRESSION *,struct token *); +static int ParseQueryTestExpression(void *,EXPRESSION *,const char *); +static int ParseQueryActionExpression(void *,EXPRESSION *,const char *,EXPRESSION *,struct token *); static void ReplaceInstanceVariables(void *,EXPRESSION *,EXPRESSION *,int,int); static void ReplaceSlotReference(void *,EXPRESSION *,EXPRESSION *, struct FunctionDefinition *,int); @@ -109,7 +123,7 @@ static int IsQueryFunction(EXPRESSION *); globle EXPRESSION *ParseQueryNoAction( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *insQuerySetVars; struct token queryInputToken; @@ -171,7 +185,7 @@ globle EXPRESSION *ParseQueryNoAction( globle EXPRESSION *ParseQueryAction( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *insQuerySetVars; struct token queryInputToken; @@ -195,7 +209,7 @@ globle EXPRESSION *ParseQueryAction( return(NULL); } DecrementIndentDepth(theEnv,3); - + if (GetType(queryInputToken) != RPAREN) { SyntaxErrorMessage(theEnv,"instance-set query function"); @@ -232,7 +246,7 @@ globle EXPRESSION *ParseQueryAction( static EXPRESSION *ParseQueryRestrictions( void *theEnv, EXPRESSION *top, - char *readSource, + const char *readSource, struct token *queryInputToken) { EXPRESSION *insQuerySetVars = NULL,*lastInsQuerySetVars = NULL, @@ -341,7 +355,7 @@ static intBool ReplaceClassNameWithReference( void *theEnv, EXPRESSION *theExp) { - char *theClassName; + const char *theClassName; void *theDefclass; if (theExp->type == SYMBOL) @@ -355,6 +369,11 @@ static intBool ReplaceClassNameWithReference( } theExp->type = DEFCLASS_PTR; theExp->value = theDefclass; + +#if (! RUN_TIME) && (! BLOAD_ONLY) + if (! ConstructData(theEnv)->ParsingConstruct) + { ConstructData(theEnv)->DanglingConstructs++; } +#endif } return(TRUE); } @@ -374,7 +393,7 @@ static intBool ReplaceClassNameWithReference( static int ParseQueryTestExpression( void *theEnv, EXPRESSION *top, - char *readSource) + const char *readSource) { EXPRESSION *qtest; int error; @@ -386,12 +405,14 @@ static int ParseQueryTestExpression( qtest = ArgumentParse(theEnv,readSource,&error); if (error == TRUE) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); ReturnExpression(theEnv,top); return(FALSE); } if (qtest == NULL) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); SyntaxErrorMessage(theEnv,"instance-set query function"); ReturnExpression(theEnv,top); @@ -431,15 +452,13 @@ static int ParseQueryTestExpression( static int ParseQueryActionExpression( void *theEnv, EXPRESSION *top, - char *readSource, + const char *readSource, EXPRESSION *insQuerySetVars, struct token *queryInputToken) { EXPRESSION *qaction,*tmpInsSetVars; - int error; struct BindInfo *oldBindList,*newBindList,*prev; - error = FALSE; oldBindList = GetParsedBindNames(theEnv); SetParsedBindNames(theEnv,NULL); ExpressionData(theEnv)->BreakContext = TRUE; @@ -451,14 +470,9 @@ static int ParseQueryActionExpression( SavePPBuffer(theEnv,queryInputToken->printForm); ExpressionData(theEnv)->BreakContext = FALSE; - if (error == TRUE) - { - SetParsedBindNames(theEnv,oldBindList); - ReturnExpression(theEnv,top); - return(FALSE); - } if (qaction == NULL) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); SyntaxErrorMessage(theEnv,"instance-set query function"); ReturnExpression(theEnv,top); @@ -545,8 +559,8 @@ static void ReplaceInstanceVariables( { bexp->type = FCALL; bexp->value = (void *) rindx_func; - eptr = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) ndepth)); - eptr->nextArg = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) posn)); + eptr = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) ndepth)); + eptr->nextArg = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) posn)); bexp->argList = eptr; } else if (sdirect == TRUE) @@ -585,10 +599,10 @@ static void ReplaceSlotReference( struct FunctionDefinition *func, int ndepth) { - unsigned len; + size_t len; int posn,oldpp; - register unsigned i; - register char *str; + size_t i; + const char *str; EXPRESSION *eptr; struct token itkn; @@ -619,9 +633,9 @@ static void ReplaceSlotReference( CloseStringSource(theEnv,"query-var"); theExp->type = FCALL; theExp->value = (void *) func; - theExp->argList = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) ndepth)); + theExp->argList = GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) ndepth)); theExp->argList->nextArg = - GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long) posn)); + GenConstant(theEnv,INTEGER,(void *) EnvAddLong(theEnv,(long long) posn)); theExp->argList->nextArg->nextArg = GenConstant(theEnv,itkn.type,itkn.value); break; } diff --git a/src/insqypsr.h b/src/insqypsr.h index 1f1f33d..734b7fc 100644 --- a/src/insqypsr.h +++ b/src/insqypsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,27 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Fixed memory leaks when error occurred. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_insqypsr @@ -37,15 +52,12 @@ #define LOCALE extern #endif -LOCALE EXPRESSION *ParseQueryNoAction(void *,EXPRESSION *,char *); -LOCALE EXPRESSION *ParseQueryAction(void *,EXPRESSION *,char *); + LOCALE EXPRESSION *ParseQueryNoAction(void *,EXPRESSION *,const char *); + LOCALE EXPRESSION *ParseQueryAction(void *,EXPRESSION *,const char *); -#ifndef _INSQYPSR_SOURCE_ -#endif +#endif /* INSTANCE_SET_QUERIES && (! RUN_TIME) */ -#endif - -#endif +#endif /* _H_insqypsr */ diff --git a/src/iofun.c b/src/iofun.c index b6c45aa..b2fb78d 100644 --- a/src/iofun.c +++ b/src/iofun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* I/O FUNCTIONS MODULE */ /*******************************************************/ @@ -12,13 +12,14 @@ /* format, and readline. */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* Gary D. Riley */ /* Bebe Ly */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.24: Added the get-char, set-locale, and */ /* read-number functions. */ /* */ @@ -29,13 +30,46 @@ /* Moved IllegalLogicalNameMessage function to */ /* argacces.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Removed the undocumented use of t in the */ +/* printout command to perform the same function */ +/* as crlf. */ +/* */ +/* Replaced EXT_IO and BASIC_IO compiler flags */ +/* with IO_FUNCTIONS compiler flag. */ +/* */ +/* Added rb and ab and removed r+ modes for the */ +/* open function. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added put-char function. */ +/* */ +/* Added SetFullCRLF which allows option to */ +/* specify crlf as \n or \r\n. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ #define _IOFUN_SOURCE_ #include "setup.h" -#if EXT_IO +#if IO_FUNCTIONS #include <locale.h> #include <stdlib.h> #include <ctype.h> @@ -74,8 +108,9 @@ #define IO_FUNCTION_DATA 64 struct IOFunctionData - { + { void *locale; + intBool useFullCRLF; }; #define IOFunctionData(theEnv) ((struct IOFunctionData *) GetEnvironmentData(theEnv,IO_FUNCTION_DATA)) @@ -84,15 +119,13 @@ struct IOFunctionData /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /****************************************/ -#if BASIC_IO +#if IO_FUNCTIONS static void ReadTokenFromStdin(void *,struct token *); -#endif -#if EXT_IO - static char *ControlStringCheck(void *,int); - static char FindFormatFlag(char *,unsigned *,char *,int *); - static char *PrintFormatFlag(void *,char *,int,int,int); - static char *FillBuffer(void *,char *,int *,unsigned *); - static void ReadNumber(void *,char *,struct token *,int); + static const char *ControlStringCheck(void *,int); + static char FindFormatFlag(const char *,size_t *,char *,size_t); + static const char *PrintFormatFlag(void *,const char *,int,int); + static char *FillBuffer(void *,const char *,size_t *,size_t *); + static void ReadNumber(void *,const char *,struct token *,int); #endif /**************************************/ @@ -103,20 +136,21 @@ globle void IOFunctionDefinitions( void *theEnv) { AllocateEnvironmentData(theEnv,IO_FUNCTION_DATA,sizeof(struct IOFunctionData),NULL); - + +#if IO_FUNCTIONS + IOFunctionData(theEnv)->useFullCRLF = FALSE; IOFunctionData(theEnv)->locale = (SYMBOL_HN *) EnvAddSymbol(theEnv,setlocale(LC_ALL,NULL)); IncrementSymbolCount(IOFunctionData(theEnv)->locale); +#endif #if ! RUN_TIME -#if BASIC_IO +#if IO_FUNCTIONS EnvDefineFunction2(theEnv,"printout", 'v', PTIEF PrintoutFunction, "PrintoutFunction", "1*"); EnvDefineFunction2(theEnv,"read", 'u', PTIEF ReadFunction, "ReadFunction", "*1"); EnvDefineFunction2(theEnv,"open", 'b', OpenFunction, "OpenFunction", "23*k"); EnvDefineFunction2(theEnv,"close", 'b', CloseFunction, "CloseFunction", "*1"); EnvDefineFunction2(theEnv,"get-char", 'i', GetCharFunction, "GetCharFunction", "*1"); -#endif - -#if EXT_IO + EnvDefineFunction2(theEnv,"put-char", 'v', PTIEF PutCharFunction, "PutCharFunction", "12"); EnvDefineFunction2(theEnv,"remove", 'b', RemoveFunction, "RemoveFunction", "11k"); EnvDefineFunction2(theEnv,"rename", 'b', RenameFunction, "RenameFunction", "22k"); EnvDefineFunction2(theEnv,"format", 's', PTIEF FormatFunction, "FormatFunction", "2**us"); @@ -125,13 +159,13 @@ globle void IOFunctionDefinitions( EnvDefineFunction2(theEnv,"read-number", 'u', PTIEF ReadNumberFunction, "ReadNumberFunction", "*1"); #endif #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } -#if BASIC_IO +#if IO_FUNCTIONS /******************************************/ /* PrintoutFunction: H/L access routine */ @@ -140,7 +174,7 @@ globle void IOFunctionDefinitions( globle void PrintoutFunction( void *theEnv) { - char *dummyid; + const char *dummyid; int i, argCount; DATA_OBJECT theArgument; @@ -154,7 +188,7 @@ globle void PrintoutFunction( /* Get the logical name to which output is to be sent. */ /*=====================================================*/ - dummyid = GetLogicalName(theEnv,1,"stdout"); + dummyid = GetLogicalName(theEnv,1,STDOUT); if (dummyid == NULL) { IllegalLogicalNameMessage(theEnv,"printout"); @@ -188,15 +222,27 @@ globle void PrintoutFunction( { case SYMBOL: if (strcmp(DOToString(theArgument),"crlf") == 0) - { EnvPrintRouter(theEnv,dummyid,"\n"); } + { + if (IOFunctionData(theEnv)->useFullCRLF) + { EnvPrintRouter(theEnv,dummyid,"\r\n"); } + else + { EnvPrintRouter(theEnv,dummyid,"\n"); } + } else if (strcmp(DOToString(theArgument),"tab") == 0) { EnvPrintRouter(theEnv,dummyid,"\t"); } else if (strcmp(DOToString(theArgument),"vtab") == 0) { EnvPrintRouter(theEnv,dummyid,"\v"); } else if (strcmp(DOToString(theArgument),"ff") == 0) { EnvPrintRouter(theEnv,dummyid,"\f"); } + /* else if (strcmp(DOToString(theArgument),"t") == 0) - { EnvPrintRouter(theEnv,dummyid,"\n"); } + { + if (IOFunctionData(theEnv)->useFullCRLF) + { EnvPrintRouter(theEnv,dummyid,"\r\n"); } + else + { EnvPrintRouter(theEnv,dummyid,"\n"); } + } + */ else { EnvPrintRouter(theEnv,dummyid,DOToString(theArgument)); } break; @@ -212,6 +258,21 @@ globle void PrintoutFunction( } } +/*****************************************************/ +/* SetFullCRLF: Set the flag which indicates whether */ +/* crlf is treated just as '\n' or '\r\n'. */ +/*****************************************************/ +globle intBool SetFullCRLF( + void *theEnv, + intBool value) + { + intBool oldValue = IOFunctionData(theEnv)->useFullCRLF; + + IOFunctionData(theEnv)->useFullCRLF = value; + + return(oldValue); + } + /*************************************************************/ /* ReadFunction: H/L access routine for the read function. */ /*************************************************************/ @@ -221,7 +282,7 @@ globle void ReadFunction( { struct token theToken; int numberOfArguments; - char *logicalName = NULL; + const char *logicalName = NULL; /*===============================================*/ /* Check for an appropriate number of arguments. */ @@ -239,10 +300,10 @@ globle void ReadFunction( /*======================================================*/ if (numberOfArguments == 0) - { logicalName = "stdin"; } + { logicalName = STDIN; } else if (numberOfArguments == 1) { - logicalName = GetLogicalName(theEnv,1,"stdin"); + logicalName = GetLogicalName(theEnv,1,STDIN); if (logicalName == NULL) { IllegalLogicalNameMessage(theEnv,"read"); @@ -273,12 +334,13 @@ globle void ReadFunction( /* source is stdin, else just get token. */ /*=======================================*/ - if (strcmp(logicalName,"stdin") == 0) + if (strcmp(logicalName,STDIN) == 0) { ReadTokenFromStdin(theEnv,&theToken); } else { GetToken(theEnv,logicalName,&theToken); } - RouterData(theEnv)->CommandBufferInputCount = -1; + RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = FALSE; /*====================================================*/ /* Copy the token to the return value data structure. */ @@ -319,7 +381,7 @@ static void ReadTokenFromStdin( struct token *theToken) { char *inputString; - unsigned inputStringSize; + size_t inputStringSize; int inchar; /*=============================================*/ @@ -336,8 +398,9 @@ static void ReadTokenFromStdin( inputString = NULL; RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; inputStringSize = 0; - inchar = EnvGetcRouter(theEnv,"stdin"); + inchar = EnvGetcRouter(theEnv,STDIN); /*========================================================*/ /* Continue reading characters until a carriage return is */ @@ -352,7 +415,7 @@ static void ReadTokenFromStdin( { inputString = ExpandStringWithChar(theEnv,inchar,inputString,&RouterData(theEnv)->CommandBufferInputCount, &inputStringSize,inputStringSize + 80); - inchar = EnvGetcRouter(theEnv,"stdin"); + inchar = EnvGetcRouter(theEnv,STDIN); } /*==================================================*/ @@ -399,7 +462,7 @@ globle int OpenFunction( void *theEnv) { int numberOfArguments; - char *fileName, *logicalName, *accessMode = NULL; + const char *fileName, *logicalName, *accessMode = NULL; DATA_OBJECT theArgument; /*========================================*/ @@ -461,14 +524,15 @@ globle int OpenFunction( /*=====================================*/ if ((strcmp(accessMode,"r") != 0) && - (strcmp(accessMode,"r+") != 0) && (strcmp(accessMode,"w") != 0) && (strcmp(accessMode,"a") != 0) && - (strcmp(accessMode,"wb") != 0)) + (strcmp(accessMode,"rb") != 0) && + (strcmp(accessMode,"wb") != 0) && + (strcmp(accessMode,"ab") != 0)) { SetHaltExecution(theEnv,TRUE); SetEvaluationError(theEnv,TRUE); - ExpectedTypeError1(theEnv,"open",3,"string with value \"r\", \"r+\", \"w\", \"wb\", or \"a\""); + ExpectedTypeError1(theEnv,"open",3,"string with value \"r\", \"w\", \"a\", \"rb\", \"wb\", or \"ab\""); return(0); } @@ -488,7 +552,7 @@ globle int CloseFunction( void *theEnv) { int numberOfArguments; - char *logicalName; + const char *logicalName; /*======================================*/ /* Check for valid number of arguments. */ @@ -534,16 +598,16 @@ globle int GetCharFunction( void *theEnv) { int numberOfArguments; - char *logicalName; + const char *logicalName; if ((numberOfArguments = EnvArgCountCheck(theEnv,"get-char",NO_MORE_THAN,1)) == -1) { return(-1); } if (numberOfArguments == 0 ) - { logicalName = "stdin"; } + { logicalName = STDIN; } else { - logicalName = GetLogicalName(theEnv,1,"stdin"); + logicalName = GetLogicalName(theEnv,1,STDIN); if (logicalName == NULL) { IllegalLogicalNameMessage(theEnv,"get-char"); @@ -564,9 +628,70 @@ globle int GetCharFunction( return(EnvGetcRouter(theEnv,logicalName)); } -#endif +/***************************************/ +/* PutCharFunction: H/L access routine */ +/* for the put-char function. */ +/***************************************/ +globle void PutCharFunction( + void *theEnv) + { + int numberOfArguments; + const char *logicalName; + DATA_OBJECT theValue; + long long theChar; + FILE *theFile; -#if EXT_IO + if ((numberOfArguments = EnvArgRangeCheck(theEnv,"put-char",1,2)) == -1) + { return; } + + /*=======================*/ + /* Get the logical name. */ + /*=======================*/ + + if (numberOfArguments == 1) + { logicalName = STDOUT; } + else + { + logicalName = GetLogicalName(theEnv,1,STDOUT); + if (logicalName == NULL) + { + IllegalLogicalNameMessage(theEnv,"put-char"); + SetHaltExecution(theEnv,TRUE); + SetEvaluationError(theEnv,TRUE); + return; + } + } + + if (QueryRouters(theEnv,logicalName) == FALSE) + { + UnrecognizedRouterMessage(theEnv,logicalName); + SetHaltExecution(theEnv,TRUE); + SetEvaluationError(theEnv,TRUE); + return; + } + + /*===========================*/ + /* Get the character to put. */ + /*===========================*/ + + if (numberOfArguments == 1) + { if (EnvArgTypeCheck(theEnv,"put-char",1,INTEGER,&theValue) == FALSE) return; } + else + { if (EnvArgTypeCheck(theEnv,"put-char",2,INTEGER,&theValue) == FALSE) return; } + + theChar = DOToLong(theValue); + + /*===================================================*/ + /* If the "fast load" option is being used, then the */ + /* logical name is actually a pointer to a file and */ + /* we can bypass the router and directly output the */ + /* value. */ + /*===================================================*/ + + theFile = FindFptr(theEnv,logicalName); + if (theFile != NULL) + { putc((int) theChar,theFile); } + } /****************************************/ /* RemoveFunction: H/L access routine */ @@ -575,7 +700,7 @@ globle int GetCharFunction( globle int RemoveFunction( void *theEnv) { - char *theFileName; + const char *theFileName; /*======================================*/ /* Check for valid number of arguments. */ @@ -604,7 +729,7 @@ globle int RemoveFunction( globle int RenameFunction( void *theEnv) { - char *oldFileName, *newFileName; + const char *oldFileName, *newFileName; /*========================================*/ /* Check for a valid number of arguments. */ @@ -635,19 +760,18 @@ globle void *FormatFunction( void *theEnv) { int argCount; - unsigned start_pos; - char *formatString, *logicalName; + size_t start_pos; + const char *formatString; + const char *logicalName; char formatFlagType; int f_cur_arg = 3; - unsigned form_pos = 0; - char buffer[FORMAT_MAX]; + size_t form_pos = 0; char percentBuffer[FLAG_MAX]; char *fstr = NULL; - unsigned fmaxm = 0; - int fpos = 0; + size_t fmaxm = 0; + size_t fpos = 0; void *hptr; - int longFound; - char *theString; + const char *theString; /*======================================*/ /* Set default return value for errors. */ @@ -667,7 +791,7 @@ globle void *FormatFunction( /* First argument must be a logical name. */ /*========================================*/ - if ((logicalName = GetLogicalName(theEnv,1,"stdout")) == NULL) + if ((logicalName = GetLogicalName(theEnv,1,STDOUT)) == NULL) { IllegalLogicalNameMessage(theEnv,"format"); SetHaltExecution(theEnv,TRUE); @@ -692,12 +816,10 @@ globle void *FormatFunction( if ((formatString = ControlStringCheck(theEnv,argCount)) == NULL) { return (hptr); } - /*==============================================*/ - /* Locate a string of 80 character for scanning */ - /* sub_string from control_string */ - /*==============================================*/ - - /* Scanning and print the format */ + /*========================================*/ + /* Search the format string, printing the */ + /* format flags as they are encountered. */ + /*========================================*/ while (formatString[form_pos] != '\0') { @@ -705,32 +827,17 @@ globle void *FormatFunction( { start_pos = form_pos; while ((formatString[form_pos] != '%') && - (formatString[form_pos] != '\0') && - ((form_pos - start_pos) < FLAG_MAX)) + (formatString[form_pos] != '\0')) { form_pos++; } fstr = AppendNToString(theEnv,&formatString[start_pos],fstr,form_pos-start_pos,&fpos,&fmaxm); } else { - start_pos = form_pos; - form_pos++; - formatFlagType = FindFormatFlag(formatString,&form_pos,buffer,&longFound); + form_pos++; + formatFlagType = FindFormatFlag(formatString,&form_pos,percentBuffer,FLAG_MAX); if (formatFlagType != ' ') { - strncpy(percentBuffer,&formatString[start_pos], - (STD_SIZE) form_pos-start_pos); - percentBuffer[form_pos-start_pos] = EOS; - if ((! longFound) && - ((formatFlagType == 'd') || (formatFlagType == 'o') || - (formatFlagType == 'u') || (formatFlagType == 'x'))) - { - longFound = TRUE; - percentBuffer[(form_pos-start_pos) - 1] = 'l'; - percentBuffer[form_pos-start_pos] = formatFlagType; - percentBuffer[(form_pos-start_pos) + 1] = EOS; - } - - if ((theString = PrintFormatFlag(theEnv,percentBuffer,f_cur_arg,formatFlagType,longFound)) == NULL) + if ((theString = PrintFormatFlag(theEnv,percentBuffer,f_cur_arg,formatFlagType)) == NULL) { if (fstr != NULL) rm(theEnv,fstr,fmaxm); return (hptr); @@ -741,7 +848,7 @@ globle void *FormatFunction( } else { - fstr = AppendToString(theEnv,buffer,fstr,&fpos,&fmaxm); + fstr = AppendToString(theEnv,percentBuffer,fstr,&fpos,&fmaxm); if (fstr == NULL) return(hptr); } } @@ -763,16 +870,16 @@ globle void *FormatFunction( /* ControlStringCheck: Checks the 2nd parameter which is the format */ /* control string to see if there are enough matching arguments. */ /*********************************************************************/ -static char *ControlStringCheck( +static const char *ControlStringCheck( void *theEnv, int argCount) { DATA_OBJECT t_ptr; - char *str_array; - char print_buff[10]; - int longFound; - unsigned i; + const char *str_array; + char print_buff[FLAG_MAX]; + size_t i; int per_count; + char formatFlag; if (EnvArgTypeCheck(theEnv,"format",2,STRING,&t_ptr) == FALSE) return(NULL); @@ -783,7 +890,17 @@ static char *ControlStringCheck( if (str_array[i] == '%') { i++; - if (FindFormatFlag(str_array,&i,print_buff,&longFound) != ' ') + formatFlag = FindFormatFlag(str_array,&i,print_buff,FLAG_MAX); + if (formatFlag == '-') + { + PrintErrorID(theEnv,"IOFUN",3,FALSE); + EnvPrintRouter(theEnv,WERROR,"Invalid format flag \""); + EnvPrintRouter(theEnv,WERROR,print_buff); + EnvPrintRouter(theEnv,WERROR,"\" specified in format function.\n"); + SetEvaluationError(theEnv,TRUE); + return (NULL); + } + else if (formatFlag != ' ') { per_count++; } } else @@ -805,24 +922,21 @@ static char *ControlStringCheck( /* a format flag in the format string. */ /***********************************************/ static char FindFormatFlag( - char *formatString, - unsigned *a, + const char *formatString, + size_t *a, char *formatBuffer, - int *longFound) + size_t bufferMax) { char inchar, formatFlagType; - unsigned start_pos, copy_pos = 0; + size_t copy_pos = 0; - /*===========================================================*/ - /* Set return values to the default value. A blank character */ - /* indicates that no format flag was found which requires a */ - /* parameter. The longFound flag indicates whether the */ - /* character 'l' was used with the float or integer flag to */ - /* indicate a double precision float or a long integer. */ - /*===========================================================*/ + /*====================================================*/ + /* Set return values to the default value. A blank */ + /* character indicates that no format flag was found */ + /* which requires a parameter. */ + /*====================================================*/ formatFlagType = ' '; - *longFound = FALSE; /*=====================================================*/ /* The format flags for carriage returns, line feeds, */ @@ -832,31 +946,31 @@ static char FindFormatFlag( if (formatString[*a] == 'n') { - sprintf(formatBuffer,"\n"); + gensprintf(formatBuffer,"\n"); (*a)++; return(formatFlagType); } else if (formatString[*a] == 'r') { - sprintf(formatBuffer,"\r"); + gensprintf(formatBuffer,"\r"); (*a)++; return(formatFlagType); } else if (formatString[*a] == 't') { - sprintf(formatBuffer,"\t"); + gensprintf(formatBuffer,"\t"); (*a)++; return(formatFlagType); } else if (formatString[*a] == 'v') { - sprintf(formatBuffer,"\v"); + gensprintf(formatBuffer,"\v"); (*a)++; return(formatFlagType); } else if (formatString[*a] == '%') { - sprintf(formatBuffer,"%%"); + gensprintf(formatBuffer,"%%"); (*a)++; return(formatFlagType); } @@ -865,32 +979,56 @@ static char FindFormatFlag( /* Identify the format flag which requires a parameter. */ /*======================================================*/ - start_pos = *a; + formatBuffer[copy_pos++] = '%'; formatBuffer[copy_pos] = '\0'; while ((formatString[*a] != '%') && (formatString[*a] != '\0') && - ((*a - start_pos) < FLAG_MAX)) + (copy_pos < (bufferMax - 5))) { inchar = formatString[*a]; - formatBuffer[copy_pos++] = inchar; - formatBuffer[copy_pos] = '\0'; + (*a)++; + if ( (inchar == 'd') || (inchar == 'o') || (inchar == 'x') || - (inchar == 'u') || - (inchar == 'c') || - (inchar == 's') || - (inchar == 'e') || - (inchar == 'f') || - (inchar == 'g') ) + (inchar == 'u')) { formatFlagType = inchar; - if (formatString[(*a) - 1] == 'l') - { *longFound = TRUE; } - (*a)++; + formatBuffer[copy_pos++] = 'l'; + formatBuffer[copy_pos++] = 'l'; + formatBuffer[copy_pos++] = inchar; + formatBuffer[copy_pos] = '\0'; return(formatFlagType); } - (*a)++; + else if ( (inchar == 'c') || + (inchar == 's') || + (inchar == 'e') || + (inchar == 'f') || + (inchar == 'g') ) + { + formatBuffer[copy_pos++] = inchar; + formatBuffer[copy_pos] = '\0'; + formatFlagType = inchar; + return(formatFlagType); + } + + /*=======================================================*/ + /* If the type hasn't been read, then this should be the */ + /* -M.N part of the format specification (where M and N */ + /* are integers). */ + /*=======================================================*/ + + if ( (! isdigit(inchar)) && + (inchar != '.') && + (inchar != '-') ) + { + formatBuffer[copy_pos++] = inchar; + formatBuffer[copy_pos] = '\0'; + return('-'); + } + + formatBuffer[copy_pos++] = inchar; + formatBuffer[copy_pos] = '\0'; } return(formatFlagType); @@ -900,18 +1038,18 @@ static char FindFormatFlag( /* PrintFormatFlag: Prints out part of the total format string along */ /* with the argument for that part of the format string. */ /**********************************************************************/ -static char *PrintFormatFlag( +static const char *PrintFormatFlag( void *theEnv, - char *formatString, + const char *formatString, int whichArg, - int formatType, - int longFound) + int formatType) { DATA_OBJECT theResult; - char *theString, *printBuffer; - unsigned theLength; + const char *theString; + char *printBuffer; + size_t theLength; void *oldLocale; - + /*=================*/ /* String argument */ /*=================*/ @@ -922,7 +1060,7 @@ static char *PrintFormatFlag( if (EnvArgTypeCheck(theEnv,"format",whichArg,SYMBOL_OR_STRING,&theResult) == FALSE) return(NULL); theLength = strlen(formatString) + strlen(ValueToString(theResult.value)) + 200; printBuffer = (char *) gm2(theEnv,(sizeof(char) * theLength)); - sprintf(printBuffer,formatString,ValueToString(theResult.value)); + gensprintf(printBuffer,formatString,ValueToString(theResult.value)); break; case 'c': @@ -932,13 +1070,13 @@ static char *PrintFormatFlag( { theLength = strlen(formatString) + 200; printBuffer = (char *) gm2(theEnv,(sizeof(char) * theLength)); - sprintf(printBuffer,formatString,(ValueToString(theResult.value))[0]); + gensprintf(printBuffer,formatString,(ValueToString(theResult.value))[0]); } else if (GetType(theResult) == INTEGER) { theLength = strlen(formatString) + 200; printBuffer = (char *) gm2(theEnv,(sizeof(char) * theLength)); - sprintf(printBuffer,formatString,(char) DOToLong(theResult)); + gensprintf(printBuffer,formatString,(char) DOToLong(theResult)); } else { @@ -954,25 +1092,15 @@ static char *PrintFormatFlag( if (EnvArgTypeCheck(theEnv,"format",whichArg,INTEGER_OR_FLOAT,&theResult) == FALSE) return(NULL); theLength = strlen(formatString) + 200; printBuffer = (char *) gm2(theEnv,(sizeof(char) * theLength)); - + oldLocale = EnvAddSymbol(theEnv,setlocale(LC_NUMERIC,NULL)); setlocale(LC_NUMERIC,ValueToString(IOFunctionData(theEnv)->locale)); if (GetType(theResult) == FLOAT) - { - if (longFound) - { sprintf(printBuffer,formatString,(long) ValueToDouble(theResult.value)); } - else - { sprintf(printBuffer,formatString,(int) ValueToDouble(theResult.value)); } - } + { gensprintf(printBuffer,formatString,(long long) ValueToDouble(theResult.value)); } else - { - if (longFound) - { sprintf(printBuffer,formatString,(long) ValueToLong(theResult.value)); } - else - { sprintf(printBuffer,formatString,(int) ValueToLong(theResult.value)); } - } - + { gensprintf(printBuffer,formatString,(long long) ValueToLong(theResult.value)); } + setlocale(LC_NUMERIC,ValueToString(oldLocale)); break; @@ -984,16 +1112,16 @@ static char *PrintFormatFlag( printBuffer = (char *) gm2(theEnv,(sizeof(char) * theLength)); oldLocale = EnvAddSymbol(theEnv,setlocale(LC_NUMERIC,NULL)); - + setlocale(LC_NUMERIC,ValueToString(IOFunctionData(theEnv)->locale)); if (GetType(theResult) == FLOAT) - { sprintf(printBuffer,formatString,ValueToDouble(theResult.value)); } + { gensprintf(printBuffer,formatString,ValueToDouble(theResult.value)); } else - { sprintf(printBuffer,formatString,(double) ValueToLong(theResult.value)); } - + { gensprintf(printBuffer,formatString,(double) ValueToLong(theResult.value)); } + setlocale(LC_NUMERIC,ValueToString(oldLocale)); - + break; default: @@ -1016,9 +1144,9 @@ globle void ReadlineFunction( DATA_OBJECT_PTR returnValue) { char *buffer; - unsigned line_max = 0; + size_t line_max = 0; int numberOfArguments; - char *logicalName; + const char *logicalName; returnValue->type = STRING; @@ -1029,10 +1157,10 @@ globle void ReadlineFunction( } if (numberOfArguments == 0 ) - { logicalName = "stdin"; } + { logicalName = STDIN; } else { - logicalName = GetLogicalName(theEnv,1,"stdin"); + logicalName = GetLogicalName(theEnv,1,STDIN); if (logicalName == NULL) { IllegalLogicalNameMessage(theEnv,"readline"); @@ -1053,8 +1181,10 @@ globle void ReadlineFunction( } RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; buffer = FillBuffer(theEnv,logicalName,&RouterData(theEnv)->CommandBufferInputCount,&line_max); - RouterData(theEnv)->CommandBufferInputCount = -1; + RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = FALSE; if (GetHaltExecution(theEnv)) { @@ -1082,9 +1212,9 @@ globle void ReadlineFunction( /*************************************************************/ static char *FillBuffer( void *theEnv, - char *logicalName, - int *currentPosition, - unsigned *maximumSize) + const char *logicalName, + size_t *currentPosition, + size_t *maximumSize) { int c; char *buf = NULL; @@ -1116,7 +1246,7 @@ static char *FillBuffer( buf = ExpandStringWithChar(theEnv,EOS,buf,currentPosition,maximumSize,*maximumSize+80); return (buf); } - + /*****************************************/ /* SetLocaleFunction: H/L access routine */ /* for the set-locale function. */ @@ -1127,23 +1257,23 @@ globle void SetLocaleFunction( { DATA_OBJECT theResult; int numArgs; - + /*======================================*/ /* Check for valid number of arguments. */ /*======================================*/ - + if ((numArgs = EnvArgCountCheck(theEnv,"set-locale",NO_MORE_THAN,1)) == -1) { returnValue->type = SYMBOL; returnValue->value = EnvFalseSymbol(theEnv); return; } - + /*=================================*/ /* If there are no arguments, just */ /* return the current locale. */ /*=================================*/ - + if (numArgs == 0) { returnValue->type = STRING; @@ -1154,25 +1284,25 @@ globle void SetLocaleFunction( /*=================*/ /* Get the locale. */ /*=================*/ - + if (EnvArgTypeCheck(theEnv,"set-locale",1,STRING,&theResult) == FALSE) { returnValue->type = SYMBOL; returnValue->value = EnvFalseSymbol(theEnv); return; } - + /*=====================================*/ /* Return the old value of the locale. */ /*=====================================*/ - + returnValue->type = STRING; returnValue->value = IOFunctionData(theEnv)->locale; - + /*======================================================*/ /* Change the value of the locale to the one specified. */ /*======================================================*/ - + DecrementSymbolCount(theEnv,(struct symbolHashNode *) IOFunctionData(theEnv)->locale); IOFunctionData(theEnv)->locale = DOToPointer(theResult); IncrementSymbolCount(IOFunctionData(theEnv)->locale); @@ -1188,7 +1318,7 @@ globle void ReadNumberFunction( { struct token theToken; int numberOfArguments; - char *logicalName = NULL; + const char *logicalName = NULL; /*===============================================*/ /* Check for an appropriate number of arguments. */ @@ -1206,10 +1336,10 @@ globle void ReadNumberFunction( /*======================================================*/ if (numberOfArguments == 0) - { logicalName = "stdin"; } + { logicalName = STDIN; } else if (numberOfArguments == 1) { - logicalName = GetLogicalName(theEnv,1,"stdin"); + logicalName = GetLogicalName(theEnv,1,STDIN); if (logicalName == NULL) { IllegalLogicalNameMessage(theEnv,"read"); @@ -1240,12 +1370,13 @@ globle void ReadNumberFunction( /* source is stdin, else just get token. */ /*=======================================*/ - if (strcmp(logicalName,"stdin") == 0) + if (strcmp(logicalName,STDIN) == 0) { ReadNumber(theEnv,logicalName,&theToken,TRUE); } else { ReadNumber(theEnv,logicalName,&theToken,FALSE); } - RouterData(theEnv)->CommandBufferInputCount = -1; + RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = FALSE; /*====================================================*/ /* Copy the token to the return value data structure. */ @@ -1276,22 +1407,22 @@ globle void ReadNumberFunction( return; } - + /********************************************/ /* ReadNumber: Special routine used by the */ /* read-number function to read a number. */ /********************************************/ static void ReadNumber( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken, int isStdin) { char *inputString; char *charPtr = NULL; - unsigned inputStringSize; + size_t inputStringSize; int inchar; - long theLong; + long long theLong; double theDouble; void *oldLocale; @@ -1304,14 +1435,15 @@ static void ReadNumber( inputString = NULL; RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; inputStringSize = 0; inchar = EnvGetcRouter(theEnv,logicalName); - + /*====================================*/ /* Skip whitespace before any number. */ /*====================================*/ - - while (isspace(inchar) && (inchar != EOF) && + + while (isspace(inchar) && (inchar != EOF) && (! GetHaltExecution(theEnv))) { inchar = EnvGetcRouter(theEnv,logicalName); } @@ -1320,7 +1452,7 @@ static void ReadNumber( /* (for anything other than stdin) or a CR/LF (for stdin). */ /*=============================================================*/ - while ((((! isStdin) && (! isspace(inchar))) || + while ((((! isStdin) && (! isspace(inchar))) || (isStdin && (inchar != '\n') && (inchar != '\r'))) && (inchar != EOF) && (! GetHaltExecution(theEnv))) @@ -1363,12 +1495,12 @@ static void ReadNumber( /* retrieved from stdin and extract the first token */ /* contained in the string. */ /*==================================================*/ - + /*=======================================*/ /* Change the locale so that numbers are */ /* converted using the localized format. */ /*=======================================*/ - + oldLocale = EnvAddSymbol(theEnv,setlocale(LC_NUMERIC,NULL)); setlocale(LC_NUMERIC,ValueToString(IOFunctionData(theEnv)->locale)); @@ -1378,8 +1510,13 @@ static void ReadNumber( /* white space or the string terminator. */ /*========================================*/ - theLong = strtol(inputString,&charPtr,10); - if ((charPtr != inputString) && +#if WIN_MVC + theLong = _strtoi64(inputString,&charPtr,10); +#else + theLong = strtoll(inputString,&charPtr,10); +#endif + + if ((charPtr != inputString) && (isspace(*charPtr) || (*charPtr == '\0'))) { theToken->type = INTEGER; @@ -1388,15 +1525,15 @@ static void ReadNumber( setlocale(LC_NUMERIC,ValueToString(oldLocale)); return; } - + /*==========================================*/ /* Try to parse the number as a double. The */ /* terminating character must either be */ /* white space or the string terminator. */ /*==========================================*/ - theDouble = strtod(inputString,&charPtr); - if ((charPtr != inputString) && + theDouble = strtod(inputString,&charPtr); + if ((charPtr != inputString) && (isspace(*charPtr) || (*charPtr == '\0'))) { theToken->type = FLOAT; @@ -1410,14 +1547,14 @@ static void ReadNumber( /* Restore the "C" locale so that any parsing */ /* of numbers uses the C format. */ /*============================================*/ - + setlocale(LC_NUMERIC,ValueToString(oldLocale)); /*=========================================*/ /* Return "*** READ ERROR ***" to indicate */ /* a number was not successfully parsed. */ /*=========================================*/ - + theToken->type = STRING; theToken->value = (void *) EnvAddSymbol(theEnv,"*** READ ERROR ***"); } diff --git a/src/iofun.h b/src/iofun.h index 19c1b34..4786668 100644 --- a/src/iofun.h +++ b/src/iofun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* I/O FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -15,11 +15,47 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.24: Added the get-char function. */ +/* */ +/* 6.24: Added the get-char, set-locale, and */ +/* read-number functions. */ +/* */ +/* Modified printing of floats in the format */ +/* function to use the locale from the set-locale */ +/* function. */ /* */ /* Moved IllegalLogicalNameMessage function to */ /* argacces.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Removed the undocumented use of t in the */ +/* printout command to perform the same function */ +/* as crlf. */ +/* */ +/* Replaced EXT_IO and BASIC_IO compiler flags */ +/* with IO_FUNCTIONS compiler flag. */ +/* */ +/* Added a+, w+, rb, ab, r+b, w+b, and a+b modes */ +/* for the open function. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added put-char function. */ +/* */ +/* Added SetFullCRLF which allows option to */ +/* specify crlf as \n or \r\n. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_iofun @@ -37,14 +73,14 @@ #endif LOCALE void IOFunctionDefinitions(void *); -#if BASIC_IO +#if IO_FUNCTIONS + LOCALE intBool SetFullCRLF(void *,intBool); LOCALE void PrintoutFunction(void *); LOCALE void ReadFunction(void *,DATA_OBJECT_PTR); LOCALE int OpenFunction(void *); LOCALE int CloseFunction(void *); LOCALE int GetCharFunction(void *); -#endif -#if EXT_IO + LOCALE void PutCharFunction(void *); LOCALE void ReadlineFunction(void *,DATA_OBJECT_PTR); LOCALE void *FormatFunction(void *); LOCALE int RemoveFunction(void *); @@ -53,7 +89,7 @@ LOCALE void ReadNumberFunction(void *,DATA_OBJECT_PTR); #endif -#endif +#endif /* _H_iofun */ diff --git a/src/lgcldpnd.c b/src/lgcldpnd.c index 827f653..9d888f3 100644 --- a/src/lgcldpnd.c +++ b/src/lgcldpnd.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* LOGICAL DEPENDENCIES MODULE */ /*******************************************************/ @@ -24,6 +24,8 @@ /* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ /*************************************************************/ #define _LGCLDPND_SOURCE_ @@ -55,7 +57,6 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct partialMatch *FindLogicalBind(struct joinNode *,struct partialMatch *); static struct dependency *DetachAssociatedDependencies(void *,struct dependency *,void *); /***********************************************************************/ @@ -94,16 +95,19 @@ globle intBool AddLogicalDependencies( else if (existingEntity && (theEntity->dependents == NULL)) { return(TRUE); } - /*============================================================*/ - /* Find the partial match in the logical join associated with */ - /* activation partial match. If the partial match cannot be */ - /* found, then the partial match must have been deleted by a */ - /* previous RHS action and the dependency link should not be */ - /* added. */ - /*============================================================*/ + /*===========================================================*/ + /* Retrieve the partial match in the logical join associated */ + /* with activation partial match (retrieved when the run */ + /* command was initiated). If the partial match's parent */ + /* links have been removed, then the partial match must have */ + /* been deleted by a previous RHS action and the dependency */ + /* link should not be added. */ + /*===========================================================*/ - theBinds = FindLogicalBind(EngineData(theEnv)->TheLogicalJoin,EngineData(theEnv)->GlobalLHSBinds); + theBinds = EngineData(theEnv)->TheLogicalBind; if (theBinds == NULL) return(FALSE); + if ((theBinds->leftParent == NULL) && (theBinds->rightParent == NULL)) + { return(FALSE); } /*==============================================================*/ /* Add a dependency link between the partial match and the data */ @@ -114,9 +118,8 @@ globle intBool AddLogicalDependencies( newDependency = get_struct(theEnv,dependency); newDependency->dPtr = (void *) theEntity; - newDependency->next = (struct dependency *) - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue; - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue = (void *) newDependency; + newDependency->next = (struct dependency *) theBinds->dependents; + theBinds->dependents = (void *) newDependency; /*================================================================*/ /* Add a dependency link between the entity and the partialMatch. */ @@ -139,59 +142,29 @@ globle intBool AddLogicalDependencies( /* CE which will provide logical support for a data entity asserted */ /* from the currently executing rule. The function is called when */ /* creating logical support links between the data entity and */ -/* supporting partial matches. It compares each partial match found */ -/* at a specified join to the partial match associated with a rule */ -/* activation until it finds the partial match that generated the */ -/* rule activation. */ +/* supporting partial matches. */ /************************************************************************/ -static struct partialMatch *FindLogicalBind( +globle struct partialMatch *FindLogicalBind( struct joinNode *theJoin, struct partialMatch *theBinds) { struct partialMatch *compPtr; - unsigned int i; - int found; - /*==================================*/ - /* Loop through each of the partial */ - /* matches in the beta memory. */ - /*==================================*/ + /*========================================================*/ + /* Follow the parent link of the activation back through */ + /* the join network until the join containing the logical */ + /* partial match is found. The partial match at this */ + /* join will have the dependency link assigned to it. */ + /*========================================================*/ - for (compPtr = theJoin->beta; + for (compPtr = theBinds; compPtr != NULL; - compPtr = compPtr->next) + compPtr = compPtr->leftParent) { - /*==================================================*/ - /* Compare each of the data entities in the partial */ - /* match being examined and the partial match used */ - /* in the dependency link. */ - /*==================================================*/ - - found = TRUE; - - for (i = 0; i < compPtr->bcount; i++) - { - if (compPtr->binds[i].gm.theMatch != theBinds->binds[i].gm.theMatch) - { - found = FALSE; - break; - } - } - - /*========================================================*/ - /* If all of the data entities in the partial match are */ - /* identical to the partial match in the dependency link, */ - /* then this is the partial match we're looking for. */ - /*========================================================*/ - - if (found) return(compPtr); + if (compPtr->owner == theJoin) + { return(compPtr); } } - /*========================================*/ - /* The partial match corresponding to the */ - /* logical dependency couldn't be found. */ - /*========================================*/ - return(NULL); } @@ -232,10 +205,9 @@ globle void RemoveEntityDependencies( /*================================================================*/ theBinds = (struct partialMatch *) fdPtr->dPtr; - theList = (struct dependency *) - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue; + theList = (struct dependency *) theBinds->dependents; theList = DetachAssociatedDependencies(theEnv,theList,(void *) theEntity); - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue = (void *) theList; + theBinds->dependents = (void *) theList; /*========================*/ /* Return the dependency. */ @@ -256,7 +228,7 @@ globle void RemoveEntityDependencies( theEntity->dependents = NULL; } - + /********************************************************************/ /* ReturnEntityDependencies: Removes all logical support links from */ /* a pattern entity. This is unidirectional. The links from the */ @@ -328,7 +300,7 @@ globle void RemovePMDependencies( struct dependency *fdPtr, *nextPtr, *theList; struct patternEntity *theEntity; - fdPtr = (struct dependency *) theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue; + fdPtr = (struct dependency *) theBinds->dependents; while (fdPtr != NULL) { @@ -344,7 +316,7 @@ globle void RemovePMDependencies( fdPtr = nextPtr; } - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue = NULL; + theBinds->dependents = NULL; } /************************************************************/ @@ -357,7 +329,7 @@ globle void DestroyPMDependencies( { struct dependency *fdPtr, *nextPtr; - fdPtr = (struct dependency *) theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue; + fdPtr = (struct dependency *) theBinds->dependents; while (fdPtr != NULL) { @@ -367,7 +339,7 @@ globle void DestroyPMDependencies( fdPtr = nextPtr; } - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue = NULL; + theBinds->dependents = NULL; } /************************************************************************/ @@ -392,14 +364,14 @@ globle void RemoveLogicalSupport( /* dependencies, then return. */ /*========================================*/ - if (theBinds->dependentsf == FALSE) return; + if (theBinds->dependents == NULL) return; /*=======================================*/ /* Loop through each of the dependencies */ /* attached to the partial match. */ /*=======================================*/ - dlPtr = (struct dependency *) theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue; + dlPtr = (struct dependency *) theBinds->dependents; while (dlPtr != NULL) { @@ -449,7 +421,7 @@ globle void RemoveLogicalSupport( /* dependencies associated with it. */ /*=====================================*/ - theBinds->binds[theBinds->bcount + theBinds->activationf].gm.theValue = NULL; + theBinds->dependents = NULL; } /********************************************************************/ @@ -561,7 +533,7 @@ globle void Dependents( struct dependency *fdPtr; struct partialMatch *theBinds; int found = FALSE; - + /*=================================*/ /* Loop through every data entity. */ /*=================================*/ diff --git a/src/lgcldpnd.h b/src/lgcldpnd.h index 7aa1781..2904232 100644 --- a/src/lgcldpnd.h +++ b/src/lgcldpnd.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* LOGICAL DEPENDENCIES HEADER FILE */ /*******************************************************/ @@ -17,7 +17,14 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Rule with exists CE has incorrect activation. */ +/* DR0867 */ +/* */ +/* 6.30: Added support for hashed memories. */ /* */ /*************************************************************/ @@ -58,8 +65,9 @@ struct dependency LOCALE void DependenciesCommand(void *); LOCALE void DependentsCommand(void *); LOCALE void ReturnEntityDependencies(void *,struct patternEntity *); + LOCALE struct partialMatch *FindLogicalBind(struct joinNode *,struct partialMatch *); -#endif +#endif /* _H_lgcldpnd */ diff --git a/src/main.c b/src/main.c deleted file mode 100644 index 37ec97e..0000000 --- a/src/main.c +++ /dev/null @@ -1,89 +0,0 @@ - /*******************************************************/ - /* "C" Language Integrated Production System */ - /* */ - /* CLIPS Version 6.24 07/01/05 */ - /* */ - /* MAIN MODULE */ - /*******************************************************/ - -/*************************************************************/ -/* Purpose: */ -/* */ -/* Principal Programmer(s): */ -/* Gary D. Riley */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* */ -/* 6.24: Moved UserFunctions and EnvUserFunctions to */ -/* the new userfunctions.c file. */ -/* */ -/*************************************************************/ - -/***************************************************************************/ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, and/or sell copies of the Software, and to permit persons */ -/* to whom the Software is furnished to do so. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS */ -/* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT */ -/* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY */ -/* CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES */ -/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN */ -/* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF */ -/* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -/* */ -/***************************************************************************/ - -#include <stdio.h> -#include "setup.h" -#include "sysdep.h" -#include "envrnmnt.h" -#include "extnfunc.h" -#include "commline.h" - -int main(int,char *[]); -void UserFunctions(void); -void EnvUserFunctions(void *); - -/****************************************/ -/* main: Starts execution of the expert */ -/* system development environment. */ -/****************************************/ -//int main( -// int argc, -// char *argv[]) -// { -// void *theEnv; -// -// theEnv = CreateEnvironment(); -// RerouteStdin(theEnv,argc,argv); -// CommandLoop(theEnv); -// -// /*==================================================================*/ -// /* Control does not normally return from the CommandLoop function. */ -// /* However if you are embedding CLIPS, have replaced CommandLoop */ -// /* with your own embedded calls that will return to this point, and */ -// /* are running software that helps detect memory leaks, you need to */ -// /* add function calls here to deallocate memory still being used by */ -// /* CLIPS. If you have a multi-threaded application, no environments */ -// /* can be currently executing. If the ALLOW_ENVIRONMENT_GLOBALS */ -// /* flag in setup.h has been set to TRUE (the default value), you */ -// /* call the DeallocateEnvironmentData function which will call */ -// /* DestroyEnvironment for each existing environment and then */ -// /* deallocate the remaining data used to keep track of allocated */ -// /* environments. Otherwise, you must explicitly call */ -// /* DestroyEnvironment for each environment you create. */ -// /*==================================================================*/ -// -// /* DeallocateEnvironmentData(); */ -// /* DestroyEnvironment(theEnv); */ -// -// return(-1); -// } diff --git a/src/match.h b/src/match.h index 51b000a..012316e 100644 --- a/src/match.h +++ b/src/match.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* MATCH HEADER FILE */ /*******************************************************/ @@ -16,6 +16,11 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ +/* Added additional members to partialMatch to */ +/* support changes to the matching algorithm. */ +/* */ /*************************************************************/ #ifndef _H_match @@ -65,14 +70,26 @@ struct genericMatch /************************************************************/ struct partialMatch { - unsigned int betaMemory : 1; - unsigned int busy : 1; - unsigned int activationf : 1; - unsigned int dependentsf : 1; - unsigned int notOriginf : 1; - unsigned int counterf : 1; - unsigned int bcount : 9; - struct partialMatch *next; + unsigned int betaMemory : 1; + unsigned int busy : 1; + unsigned int rhsMemory : 1; + unsigned short bcount; + unsigned long hashValue; + void *owner; + void *marker; + void *dependents; + struct partialMatch *nextInMemory; + struct partialMatch *prevInMemory; + struct partialMatch *children; + struct partialMatch *rightParent; + struct partialMatch *nextRightChild; + struct partialMatch *prevRightChild; + struct partialMatch *leftParent; + struct partialMatch *nextLeftChild; + struct partialMatch *prevLeftChild; + struct partialMatch *blockList; + struct partialMatch *nextBlocked; + struct partialMatch *prevBlocked; struct genericMatch binds[1]; }; @@ -84,6 +101,7 @@ struct alphaMatch struct patternEntity *matchingItem; struct multifieldMarker *markers; struct alphaMatch *next; + unsigned long bucket; }; /************************************************************/ @@ -111,7 +129,7 @@ struct multifieldMarker #define set_nth_pm_value(thePM,thePos,theVal) (thePM->binds[thePos].gm.theValue = (void *) theVal) #define set_nth_pm_match(thePM,thePos,theVal) (thePM->binds[thePos].gm.theMatch = theVal) -#endif +#endif /* _H_match */ diff --git a/src/memalloc.c b/src/memalloc.c index 0f60547..4c1be6a 100644 --- a/src/memalloc.c +++ b/src/memalloc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* MEMORY MODULE */ /*******************************************************/ @@ -13,7 +13,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -24,6 +24,22 @@ /* */ /* Corrected code to remove compiler warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed genlongalloc/genlongfree functions. */ +/* */ +/* Added get_mem and rtn_mem macros. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Removed deallocating message parameter from */ +/* EnvReleaseMem. */ +/* */ +/* Removed support for BLOCK_MEMORY. */ +/* */ /*************************************************************/ #define _MEMORY_SOURCE_ @@ -41,43 +57,26 @@ #include <stdlib.h> -#if IBM_TBC -#include <alloc.h> -#endif -#if IBM_MSC || IBM_ICB +#if WIN_MVC #include <malloc.h> #endif -#if IBM_ZTC || IBM_SC -#include <dos.h> -#endif #define STRICT_ALIGN_SIZE sizeof(double) #define SpecialMalloc(sz) malloc((STD_SIZE) sz) #define SpecialFree(ptr) free(ptr) -/***************************************/ -/* LOCAL INTERNAL FUNCTION DEFINITIONS */ -/***************************************/ - -#if BLOCK_MEMORY - static int InitializeBlockMemory(void *,unsigned int); - static int AllocateBlock(void *,struct blockInfo *,unsigned int); - static void AllocateChunk(void *,struct blockInfo *,struct chunkInfo *,unsigned int); -#endif - /********************************************/ /* InitializeMemory: Sets up memory tables. */ /********************************************/ globle void InitializeMemory( void *theEnv) { - int i; - AllocateEnvironmentData(theEnv,MEMORY_DATA,sizeof(struct memoryData),NULL); MemoryData(theEnv)->OutOfMemoryFunction = DefaultOutOfMemoryFunction; - + +#if (MEM_TABLE_SIZE > 0) MemoryData(theEnv)->MemoryTable = (struct memoryPtr **) malloc((STD_SIZE) (sizeof(struct memoryPtr *) * MEM_TABLE_SIZE)); @@ -87,8 +86,15 @@ globle void InitializeMemory( EnvPrintRouter(theEnv,WERROR,"Out of memory.\n"); EnvExitRouter(theEnv,EXIT_FAILURE); } + else + { + int i; - for (i = 0; i < MEM_TABLE_SIZE; i++) MemoryData(theEnv)->MemoryTable[i] = NULL; + for (i = 0; i < MEM_TABLE_SIZE; i++) MemoryData(theEnv)->MemoryTable[i] = NULL; + } +#else // MEM_TABLE_SIZE == 0 + MemoryData(theEnv)->MemoryTable = NULL; +#endif } /***************************************************/ @@ -96,48 +102,28 @@ globle void InitializeMemory( /***************************************************/ globle void *genalloc( void *theEnv, - unsigned int size) + size_t size) { char *memPtr; - -#if BLOCK_MEMORY - memPtr = (char *) RequestChunk(theEnv,size); - if (memPtr == NULL) - { - EnvReleaseMem(theEnv,(long) ((size * 5 > 4096) ? size * 5 : 4096),FALSE); - memPtr = (char *) RequestChunk(theEnv,size); - if (memPtr == NULL) - { - EnvReleaseMem(theEnv,-1L,TRUE); - memPtr = (char *) RequestChunk(theEnv,size); - while (memPtr == NULL) - { - if ((*MemoryData(theEnv)->OutOfMemoryFunction)(theEnv,(unsigned long) size)) - return(NULL); - memPtr = (char *) RequestChunk(theEnv,size); - } - } - } -#else - memPtr = (char *) malloc((STD_SIZE) size); - + + memPtr = (char *) malloc(size); + if (memPtr == NULL) { - EnvReleaseMem(theEnv,(long) ((size * 5 > 4096) ? size * 5 : 4096),FALSE); - memPtr = (char *) malloc((STD_SIZE) size); + EnvReleaseMem(theEnv,(long) ((size * 5 > 4096) ? size * 5 : 4096)); + memPtr = (char *) malloc(size); if (memPtr == NULL) { - EnvReleaseMem(theEnv,-1L,TRUE); - memPtr = (char *) malloc((STD_SIZE) size); + EnvReleaseMem(theEnv,-1L); + memPtr = (char *) malloc(size); while (memPtr == NULL) { - if ((*MemoryData(theEnv)->OutOfMemoryFunction)(theEnv,(unsigned long) size)) + if ((*MemoryData(theEnv)->OutOfMemoryFunction)(theEnv,size)) return(NULL); - memPtr = (char *) malloc((STD_SIZE) size); + memPtr = (char *) malloc(size); } } } -#endif MemoryData(theEnv)->MemoryAmount += (long) size; MemoryData(theEnv)->MemoryCalls++; @@ -149,14 +135,11 @@ globle void *genalloc( /* DefaultOutOfMemoryFunction: Function called */ /* when the KB runs out of memory. */ /***********************************************/ -#if IBM_TBC -#pragma argsused -#endif globle int DefaultOutOfMemoryFunction( void *theEnv, - unsigned long size) + size_t size) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(size) #endif @@ -170,9 +153,9 @@ globle int DefaultOutOfMemoryFunction( /* EnvSetOutOfMemoryFunction: Allows the function which is */ /* called when the KB runs out of memory to be changed. */ /***********************************************************/ -globle int (*EnvSetOutOfMemoryFunction(void *theEnv,int (*functionPtr)(void *,unsigned long)))(void *,unsigned long) +globle int (*EnvSetOutOfMemoryFunction(void *theEnv,int (*functionPtr)(void *,size_t)))(void *,size_t) { - int (*tmpPtr)(void *,unsigned long); + int (*tmpPtr)(void *,size_t); tmpPtr = MemoryData(theEnv)->OutOfMemoryFunction; MemoryData(theEnv)->OutOfMemoryFunction = functionPtr; @@ -185,18 +168,9 @@ globle int (*EnvSetOutOfMemoryFunction(void *theEnv,int (*functionPtr)(void *,un globle int genfree( void *theEnv, void *waste, - unsigned size) - { -#if BLOCK_MEMORY - if (ReturnChunk(theEnv,waste,size) == FALSE) - { - PrintErrorID(theEnv,"MEMORY",2,TRUE); - EnvPrintRouter(theEnv,WERROR,"Release error in genfree.\n"); - return(-1); - } -#else + size_t size) + { free(waste); -#endif MemoryData(theEnv)->MemoryAmount -= (long) size; MemoryData(theEnv)->MemoryCalls--; @@ -210,12 +184,12 @@ globle int genfree( globle void *genrealloc( void *theEnv, void *oldaddr, - unsigned oldsz, - unsigned newsz) + size_t oldsz, + size_t newsz) { char *newaddr; unsigned i; - unsigned limit; + size_t limit; newaddr = ((newsz != 0) ? (char *) gm2(theEnv,newsz) : NULL); @@ -232,153 +206,6 @@ globle void *genrealloc( return((void *) newaddr); } -/************************************************/ -/* genlongalloc: Allocates blocks of memory for */ -/* sizes expressed using long integers. */ -/************************************************/ -#if IBM_TBC -#pragma warn -rch -#pragma warn -ccc -#endif -globle void *genlongalloc( - void *theEnv, - unsigned long size) - { -#if (! MAC) && (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) && (! IBM_ZTC) && (! IBM_SC) && (! IBM_MCW) - unsigned int test; -#else - void *memPtr; -#endif -#if BLOCK_MEMORY - struct longMemoryPtr *theLongMemory; -#endif - - if (sizeof(int) == sizeof(long)) - { return(genalloc(theEnv,(unsigned) size)); } - -#if (! MAC) && (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) && (! IBM_ZTC) && (! IBM_SC) && (! IBM_MCW) - test = (unsigned int) size; - if (test != size) - { - PrintErrorID(theEnv,"MEMORY",3,TRUE); - EnvPrintRouter(theEnv,WERROR,"Unable to allocate memory block > 32K.\n"); - EnvExitRouter(theEnv,EXIT_FAILURE); - } - return((void *) genalloc(theEnv,(unsigned) test)); -#else - -#if BLOCK_MEMORY - size += sizeof(struct longMemoryPtr); -#endif - - memPtr = (void *) SpecialMalloc(size); - if (memPtr == NULL) - { - EnvReleaseMem(theEnv,(long) ((size * 5 > 4096) ? size * 5 : 4096),FALSE); - memPtr = (void *) SpecialMalloc(size); - if (memPtr == NULL) - { - EnvReleaseMem(theEnv,-1L,TRUE); - memPtr = (void *) SpecialMalloc(size); - while (memPtr == NULL) - { - if ((*MemoryData(theEnv)->OutOfMemoryFunction)(theEnv,size)) - return(NULL); - memPtr = (void *) SpecialMalloc(size); - } - } - } - MemoryData(theEnv)->MemoryAmount += (long) size; - MemoryData(theEnv)->MemoryCalls++; - -#if BLOCK_MEMORY - theLongMemory = (struct longMemoryPtr *) memPtr; - theLongMemory->next = MemoryData(theEnv)->TopLongMemoryPtr; - theLongMemory->prev = NULL; - theLongMemory->size = (long) size; - memPtr = (void *) (theLongMemory + 1); -#endif - - return(memPtr); -#endif - } -#if IBM_TBC -#pragma warn +rch -#pragma warn +ccc -#endif - -/*********************************************/ -/* genlongfree: Returns blocks of memory for */ -/* sizes expressed using long integers. */ -/*********************************************/ -#if IBM_TBC -#pragma warn -rch -#pragma warn -ccc -#endif -globle int genlongfree( - void *theEnv, - void *ptr, - unsigned long size) - { -#if (! MAC) && (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) && (! IBM_ZTC) && (! IBM_SC) && (! IBM_MCW) - unsigned int test; -#endif -#if BLOCK_MEMORY - struct longMemoryPtr *theLongMemory; -#endif - - if (sizeof(unsigned int) == sizeof(unsigned long)) - { return(genfree(theEnv,(void *) ptr,(unsigned) size)); } - -#if (! MAC) && (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) && (! IBM_ZTC) && (! IBM_SC) && (! IBM_MCW) - test = (unsigned int) size; - if (test != size) return(-1); - - return(genfree(theEnv,(void *) ptr,(unsigned) test)); -#endif - -#if BLOCK_MEMORY - size += sizeof(struct longMemoryPtr); - theLongMemory = ((struct longMemoryPtr *) ptr) - 1; - if (theLongMemory->prev == NULL) - { - MemoryData(theEnv)->TopLongMemoryPtr = MemoryData(theEnv)->TopLongMemoryPtr->next; - MemoryData(theEnv)->TopLongMemoryPtr->prev = NULL; - } - else - { - theLongMemory->prev->next = theLongMemory->next; - if (theLongMemory->next != NULL) - { theLongMemory->next->prev = theLongMemory->next; } - } -#endif - -#if MAC || IBM_ICB || IBM_MCW - MemoryData(theEnv)->MemoryAmount -= (long) size; - MemoryData(theEnv)->MemoryCalls--; - SpecialFree(ptr); - return(0); -#endif - -#if IBM_TBC || IBM_ZTC || IBM_SC - MemoryData(theEnv)->MemoryAmount -= size; - MemoryData(theEnv)->MemoryCalls--; - SpecialFree(ptr); - return(0); -#endif - -#if IBM_MSC - MemoryData(theEnv)->MemoryAmount -= size; - MemoryData(theEnv)->MemoryCalls--; - SpecialFree(ptr); - return(0); -#endif - } -#if IBM_TBC -#pragma warn +rch -#pragma warn +ccc -#endif - /********************************/ /* EnvMemUsed: C access routine */ /* for the mem-used command. */ @@ -429,17 +256,13 @@ globle long int UpdateMemoryRequests( /***********************************/ globle long int EnvReleaseMem( void *theEnv, - long int maximum, - int printMessage) + long int maximum) { struct memoryPtr *tmpPtr, *memPtr; int i; long int returns = 0; long int amount = 0; - if (printMessage == TRUE) - { EnvPrintRouter(theEnv,WDIALOG,"\n*** DEALLOCATING MEMORY ***\n"); } - for (i = (MEM_TABLE_SIZE - 1) ; i >= (int) sizeof(char *) ; i--) { YieldTime(theEnv); @@ -456,16 +279,9 @@ globle long int EnvReleaseMem( } MemoryData(theEnv)->MemoryTable[i] = NULL; if ((amount > maximum) && (maximum > 0)) - { - if (printMessage == TRUE) - { EnvPrintRouter(theEnv,WDIALOG,"*** MEMORY DEALLOCATED ***\n"); } - return(amount); - } + { return(amount); } } - if (printMessage == TRUE) - { EnvPrintRouter(theEnv,WDIALOG,"*** MEMORY DEALLOCATED ***\n"); } - return(amount); } @@ -474,11 +290,11 @@ globle long int EnvReleaseMem( /*****************************************************/ globle void *gm1( void *theEnv, - int size) + size_t size) { struct memoryPtr *memPtr; char *tmpPtr; - int i; + size_t i; if (size < (long) sizeof(char *)) size = sizeof(char *); @@ -513,23 +329,29 @@ globle void *gm1( /*****************************************************/ globle void *gm2( void *theEnv, - unsigned int size) + size_t size) { +#if (MEM_TABLE_SIZE > 0) struct memoryPtr *memPtr; - +#endif + if (size < sizeof(char *)) size = sizeof(char *); +#if (MEM_TABLE_SIZE > 0) if (size >= MEM_TABLE_SIZE) return(genalloc(theEnv,(unsigned) size)); memPtr = (struct memoryPtr *) MemoryData(theEnv)->MemoryTable[size]; if (memPtr == NULL) { - return(genalloc(theEnv,(unsigned) size)); + return(genalloc(theEnv,size)); } MemoryData(theEnv)->MemoryTable[size] = memPtr->next; return ((void *) memPtr); +#else + return(genalloc(theEnv,size)); +#endif } /*****************************************************/ @@ -537,23 +359,27 @@ globle void *gm2( /*****************************************************/ globle void *gm3( void *theEnv, - long size) + size_t size) { +#if (MEM_TABLE_SIZE > 0) struct memoryPtr *memPtr; +#endif if (size < (long) sizeof(char *)) size = sizeof(char *); - if (size >= MEM_TABLE_SIZE) return(genlongalloc(theEnv,(unsigned long) size)); +#if (MEM_TABLE_SIZE > 0) + if (size >= MEM_TABLE_SIZE) return(genalloc(theEnv,size)); memPtr = (struct memoryPtr *) MemoryData(theEnv)->MemoryTable[(int) size]; if (memPtr == NULL) - { - return(genalloc(theEnv,(unsigned int) size)); - } + { return(genalloc(theEnv,size)); } MemoryData(theEnv)->MemoryTable[(int) size] = memPtr->next; return ((void *) memPtr); +#else + return(genalloc(theEnv,size)); +#endif } /****************************************/ @@ -563,9 +389,11 @@ globle void *gm3( globle int rm( void *theEnv, void *str, - unsigned size) + size_t size) { +#if (MEM_TABLE_SIZE > 0) struct memoryPtr *memPtr; +#endif if (size == 0) { @@ -575,11 +403,16 @@ globle int rm( if (size < sizeof(char *)) size = sizeof(char *); - if (size >= MEM_TABLE_SIZE) return(genfree(theEnv,(void *) str,(unsigned) size)); +#if (MEM_TABLE_SIZE > 0) + if (size >= MEM_TABLE_SIZE) return(genfree(theEnv,(void *) str,size)); memPtr = (struct memoryPtr *) str; memPtr->next = MemoryData(theEnv)->MemoryTable[size]; MemoryData(theEnv)->MemoryTable[size] = memPtr; +#else + return(genfree(theEnv,(void *) str,size)); +#endif + return(1); } @@ -591,9 +424,11 @@ globle int rm( globle int rm3( void *theEnv, void *str, - long size) + size_t size) { +#if (MEM_TABLE_SIZE > 0) struct memoryPtr *memPtr; +#endif if (size == 0) { @@ -603,11 +438,16 @@ globle int rm3( if (size < (long) sizeof(char *)) size = sizeof(char *); - if (size >= MEM_TABLE_SIZE) return(genlongfree(theEnv,(void *) str,(unsigned long) size)); +#if (MEM_TABLE_SIZE > 0) + if (size >= MEM_TABLE_SIZE) return(genfree(theEnv,(void *) str,size)); memPtr = (struct memoryPtr *) str; memPtr->next = MemoryData(theEnv)->MemoryTable[(int) size]; MemoryData(theEnv)->MemoryTable[(int) size] = memPtr; +#else + return(genfree(theEnv,(void *) str,size)); +#endif + return(1); } @@ -617,9 +457,11 @@ globle int rm3( globle unsigned long PoolSize( void *theEnv) { + unsigned long cnt = 0; + +#if (MEM_TABLE_SIZE > 0) register int i; struct memoryPtr *memPtr; - unsigned long cnt = 0; for (i = sizeof(char *) ; i < MEM_TABLE_SIZE ; i++) { @@ -630,6 +472,8 @@ globle unsigned long PoolSize( memPtr = memPtr->next; } } +#endif + return(cnt); } @@ -641,30 +485,7 @@ globle unsigned long PoolSize( globle unsigned long ActualPoolSize( void *theEnv) { -#if IBM_TBC - register int i; - struct memoryPtr *memPtr; - unsigned long cnt = 0; - - for (i = sizeof(char *) ; i < MEM_TABLE_SIZE ; i++) - { - memPtr = MemoryData(theEnv)->MemoryTable[i]; - while (memPtr != NULL) - { - /*==============================================================*/ - /* For a block of size n, the Turbo-C Library routines require */ - /* a header of size 8 bytes and further require that all memory */ - /* allotments be paragraph (16-bytes) aligned. */ - /*==============================================================*/ - - cnt += (((unsigned long) i) + 19L) & 0xfffffff0L; - memPtr = memPtr->next; - } - } - return(cnt); -#else return(PoolSize(theEnv)); -#endif } /********************************************/ @@ -706,461 +527,43 @@ globle void genmemcpy( dst[i] = src[i]; } -/**************************/ -/* BLOCK MEMORY FUNCTIONS */ -/**************************/ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ -#if BLOCK_MEMORY +#if ALLOW_ENVIRONMENT_GLOBALS -/***************************************************/ -/* InitializeBlockMemory: Initializes block memory */ -/* management and allocates the first block. */ -/***************************************************/ -static int InitializeBlockMemory( - void *theEnv, - unsigned int requestSize) +globle intBool GetConserveMemory() { - struct chunkInfo *chunkPtr; - unsigned int initialBlockSize, usableBlockSize; - - /*===========================================*/ - /* The block memory routines depend upon the */ - /* size of a character being 1 byte. */ - /*===========================================*/ - - if (sizeof(char) != 1) - { - fprintf(stdout, "Size of character data is not 1\n"); - fprintf(stdout, "Memory allocation functions may not work\n"); - return(0); - } - - MemoryData(theEnv)->ChunkInfoSize = sizeof(struct chunkInfo); - MemoryData(theEnv)->ChunkInfoSize = (int) ((((MemoryData(theEnv)->ChunkInfoSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE); - - MemoryData(theEnv)->BlockInfoSize = sizeof(struct blockInfo); - MemoryData(theEnv)->BlockInfoSize = (int) ((((MemoryData(theEnv)->BlockInfoSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE); - - initialBlockSize = (INITBLOCKSIZE > requestSize ? INITBLOCKSIZE : requestSize); - initialBlockSize += MemoryData(theEnv)->ChunkInfoSize * 2 + MemoryData(theEnv)->BlockInfoSize; - initialBlockSize = (((initialBlockSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE; - - usableBlockSize = initialBlockSize - (2 * MemoryData(theEnv)->ChunkInfoSize) - MemoryData(theEnv)->BlockInfoSize; - - /* make sure we get a buffer big enough to be usable */ - if ((requestSize < INITBLOCKSIZE) && - (usableBlockSize <= requestSize + MemoryData(theEnv)->ChunkInfoSize)) - { - initialBlockSize = requestSize + MemoryData(theEnv)->ChunkInfoSize * 2 + MemoryData(theEnv)->BlockInfoSize; - initialBlockSize = (((initialBlockSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE; - usableBlockSize = initialBlockSize - (2 * MemoryData(theEnv)->ChunkInfoSize) - MemoryData(theEnv)->BlockInfoSize; - } - - MemoryData(theEnv)->TopMemoryBlock = (struct blockInfo *) malloc((STD_SIZE) initialBlockSize); - - if (MemoryData(theEnv)->TopMemoryBlock == NULL) - { - fprintf(stdout, "Unable to allocate initial memory pool\n"); - return(0); - } - - MemoryData(theEnv)->TopMemoryBlock->nextBlock = NULL; - MemoryData(theEnv)->TopMemoryBlock->prevBlock = NULL; - MemoryData(theEnv)->TopMemoryBlock->nextFree = (struct chunkInfo *) (((char *) MemoryData(theEnv)->TopMemoryBlock) + MemoryData(theEnv)->BlockInfoSize); - MemoryData(theEnv)->TopMemoryBlock->size = (long) usableBlockSize; - - chunkPtr = (struct chunkInfo *) (((char *) MemoryData(theEnv)->TopMemoryBlock) + MemoryData(theEnv)->BlockInfoSize + MemoryData(theEnv)->ChunkInfoSize + usableBlockSize); - chunkPtr->nextFree = NULL; - chunkPtr->lastFree = NULL; - chunkPtr->prevChunk = MemoryData(theEnv)->TopMemoryBlock->nextFree; - chunkPtr->size = 0; - - MemoryData(theEnv)->TopMemoryBlock->nextFree->nextFree = NULL; - MemoryData(theEnv)->TopMemoryBlock->nextFree->lastFree = NULL; - MemoryData(theEnv)->TopMemoryBlock->nextFree->prevChunk = NULL; - MemoryData(theEnv)->TopMemoryBlock->nextFree->size = (long) usableBlockSize; - - MemoryData(theEnv)->BlockMemoryInitialized = TRUE; - return(1); + return EnvGetConserveMemory(GetCurrentEnvironment()); } -/***************************************************************************/ -/* AllocateBlock: Adds a new block of memory to the list of memory blocks. */ -/***************************************************************************/ -static int AllocateBlock( - void *theEnv, - struct blockInfo *blockPtr, - unsigned int requestSize) +globle long int MemRequests() { - unsigned int blockSize, usableBlockSize; - struct blockInfo *newBlock; - struct chunkInfo *newTopChunk; - - /*============================================================*/ - /* Determine the size of the block that needs to be allocated */ - /* to satisfy the request. Normally, a default block size is */ - /* used, but if the requested size is larger than the default */ - /* size, then the requested size is used for the block size. */ - /*============================================================*/ - - blockSize = (BLOCKSIZE > requestSize ? BLOCKSIZE : requestSize); - blockSize += MemoryData(theEnv)->BlockInfoSize + MemoryData(theEnv)->ChunkInfoSize * 2; - blockSize = (((blockSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE; - - usableBlockSize = blockSize - MemoryData(theEnv)->BlockInfoSize - (2 * MemoryData(theEnv)->ChunkInfoSize); - - /*=========================*/ - /* Allocate the new block. */ - /*=========================*/ - - newBlock = (struct blockInfo *) malloc((STD_SIZE) blockSize); - if (newBlock == NULL) return(0); - - /*======================================*/ - /* Initialize the block data structure. */ - /*======================================*/ - - newBlock->nextBlock = NULL; - newBlock->prevBlock = blockPtr; - newBlock->nextFree = (struct chunkInfo *) (((char *) newBlock) + MemoryData(theEnv)->BlockInfoSize); - newBlock->size = (long) usableBlockSize; - blockPtr->nextBlock = newBlock; - - newTopChunk = (struct chunkInfo *) (((char *) newBlock) + MemoryData(theEnv)->BlockInfoSize + MemoryData(theEnv)->ChunkInfoSize + usableBlockSize); - newTopChunk->nextFree = NULL; - newTopChunk->lastFree = NULL; - newTopChunk->size = 0; - newTopChunk->prevChunk = newBlock->nextFree; - - newBlock->nextFree->nextFree = NULL; - newBlock->nextFree->lastFree = NULL; - newBlock->nextFree->prevChunk = NULL; - newBlock->nextFree->size = (long) usableBlockSize; - - return(1); + return EnvMemRequests(GetCurrentEnvironment()); } -/*******************************************************/ -/* RequestChunk: Allocates memory by returning a chunk */ -/* of memory from a larger block of memory. */ -/*******************************************************/ -globle void *RequestChunk( - void *theEnv, - unsigned int requestSize) +globle long int MemUsed() { - struct chunkInfo *chunkPtr; - struct blockInfo *blockPtr; - - /*==================================================*/ - /* Allocate initial memory pool block if it has not */ - /* already been allocated. */ - /*==================================================*/ - - if (MemoryData(theEnv)->BlockMemoryInitialized == FALSE) - { - if (InitializeBlockMemory(theEnv,requestSize) == 0) return(NULL); - } - - /*====================================================*/ - /* Make sure that the amount of memory requested will */ - /* fall on a boundary of strictest alignment */ - /*====================================================*/ - - requestSize = (((requestSize - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE; - - /*=====================================================*/ - /* Search through the list of free memory for a block */ - /* of the appropriate size. If a block is found, then */ - /* allocate and return a pointer to it. */ - /*=====================================================*/ - - blockPtr = MemoryData(theEnv)->TopMemoryBlock; - - while (blockPtr != NULL) - { - chunkPtr = blockPtr->nextFree; - - while (chunkPtr != NULL) - { - if ((chunkPtr->size == requestSize) || - (chunkPtr->size > (requestSize + MemoryData(theEnv)->ChunkInfoSize))) - { - AllocateChunk(theEnv,blockPtr,chunkPtr,requestSize); - - return((void *) (((char *) chunkPtr) + MemoryData(theEnv)->ChunkInfoSize)); - } - chunkPtr = chunkPtr->nextFree; - } - - if (blockPtr->nextBlock == NULL) - { - if (AllocateBlock(theEnv,blockPtr,requestSize) == 0) /* get another block */ - { return(NULL); } - } - blockPtr = blockPtr->nextBlock; - } - - SystemError(theEnv,"MEMORY",2); - EnvExitRouter(theEnv,EXIT_FAILURE); - return(NULL); /* Unreachable, but prevents warning. */ + return EnvMemUsed(GetCurrentEnvironment()); } -/********************************************/ -/* AllocateChunk: Allocates a chunk from an */ -/* existing chunk in a block of memory. */ -/********************************************/ -static void AllocateChunk( - void *theEnv, - struct blockInfo *parentBlock, - struct chunkInfo *chunkPtr, - unsigned int requestSize) +globle long int ReleaseMem( + long int maximum) { - struct chunkInfo *splitChunk, *nextChunk; - - /*=============================================================*/ - /* If the size of the memory chunk is an exact match for the */ - /* requested amount of memory, then the chunk can be allocated */ - /* without splitting it. */ - /*=============================================================*/ - - if (requestSize == chunkPtr->size) - { - chunkPtr->size = - (long int) requestSize; - if (chunkPtr->lastFree == NULL) - { - if (chunkPtr->nextFree != NULL) - { parentBlock->nextFree = chunkPtr->nextFree; } - else - { parentBlock->nextFree = NULL; } - } - else - { chunkPtr->lastFree->nextFree = chunkPtr->nextFree; } - - if (chunkPtr->nextFree != NULL) - { chunkPtr->nextFree->lastFree = chunkPtr->lastFree; } - - chunkPtr->lastFree = NULL; - chunkPtr->nextFree = NULL; - return; - } - - /*===========================================================*/ - /* If the size of the memory chunk is larger than the memory */ - /* request, then split the chunk into two pieces. */ - /*===========================================================*/ - - nextChunk = (struct chunkInfo *) - (((char *) chunkPtr) + MemoryData(theEnv)->ChunkInfoSize + chunkPtr->size); - - splitChunk = (struct chunkInfo *) - (((char *) chunkPtr) + (MemoryData(theEnv)->ChunkInfoSize + requestSize)); - - splitChunk->size = (long) (chunkPtr->size - (requestSize + MemoryData(theEnv)->ChunkInfoSize)); - splitChunk->prevChunk = chunkPtr; - - splitChunk->nextFree = chunkPtr->nextFree; - splitChunk->lastFree = chunkPtr->lastFree; - - nextChunk->prevChunk = splitChunk; - - if (splitChunk->lastFree == NULL) - { parentBlock->nextFree = splitChunk; } - else - { splitChunk->lastFree->nextFree = splitChunk; } - - if (splitChunk->nextFree != NULL) - { splitChunk->nextFree->lastFree = splitChunk; } - - chunkPtr->size = - (long int) requestSize; - chunkPtr->lastFree = NULL; - chunkPtr->nextFree = NULL; - - return; + return EnvReleaseMem(GetCurrentEnvironment(),maximum); } -/***********************************************************/ -/* ReturnChunk: Frees memory allocated using RequestChunk. */ -/***********************************************************/ -globle int ReturnChunk( - void *theEnv, - void *memPtr, - unsigned int size) +globle intBool SetConserveMemory( + intBool value) { - struct chunkInfo *chunkPtr, *lastChunk, *nextChunk, *topChunk; - struct blockInfo *blockPtr; - - /*=====================================================*/ - /* Determine if the expected size of the chunk matches */ - /* the size stored in the chunk's information record. */ - /*=====================================================*/ - - size = (((size - 1) / STRICT_ALIGN_SIZE) + 1) * STRICT_ALIGN_SIZE; - - chunkPtr = (struct chunkInfo *) (((char *) memPtr) - MemoryData(theEnv)->ChunkInfoSize); - - if (chunkPtr == NULL) - { return(FALSE); } - - if (chunkPtr->size >= 0) - { return(FALSE); } - - if (chunkPtr->size != - (long int) size) - { return(FALSE); } - - chunkPtr->size = - chunkPtr->size; - - /*=============================================*/ - /* Determine in which block the chunk resides. */ - /*=============================================*/ - - topChunk = chunkPtr; - while (topChunk->prevChunk != NULL) - { topChunk = topChunk->prevChunk; } - blockPtr = (struct blockInfo *) (((char *) topChunk) - MemoryData(theEnv)->BlockInfoSize); - - /*===========================================*/ - /* Determine the chunks physically preceding */ - /* and following the returned chunk. */ - /*===========================================*/ - - lastChunk = chunkPtr->prevChunk; - nextChunk = (struct chunkInfo *) (((char *) memPtr) + size); - - /*=========================================================*/ - /* Add the chunk to the list of free chunks for the block. */ - /*=========================================================*/ - - if (blockPtr->nextFree != NULL) - { blockPtr->nextFree->lastFree = chunkPtr; } - - chunkPtr->nextFree = blockPtr->nextFree; - chunkPtr->lastFree = NULL; - - blockPtr->nextFree = chunkPtr; - - /*=====================================================*/ - /* Combine this chunk with previous chunk if possible. */ - /*=====================================================*/ - - if (lastChunk != NULL) - { - if (lastChunk->size > 0) - { - lastChunk->size += (MemoryData(theEnv)->ChunkInfoSize + chunkPtr->size); - - if (nextChunk != NULL) - { nextChunk->prevChunk = lastChunk; } - else - { return(FALSE); } - - if (lastChunk->lastFree != NULL) - { lastChunk->lastFree->nextFree = lastChunk->nextFree; } - - if (lastChunk->nextFree != NULL) - { lastChunk->nextFree->lastFree = lastChunk->lastFree; } - - lastChunk->nextFree = chunkPtr->nextFree; - if (chunkPtr->nextFree != NULL) - { chunkPtr->nextFree->lastFree = lastChunk; } - lastChunk->lastFree = NULL; - - blockPtr->nextFree = lastChunk; - chunkPtr->lastFree = NULL; - chunkPtr->nextFree = NULL; - chunkPtr = lastChunk; - } - } - - /*=====================================================*/ - /* Combine this chunk with the next chunk if possible. */ - /*=====================================================*/ - - if (nextChunk == NULL) return(FALSE); - if (chunkPtr == NULL) return(FALSE); - - if (nextChunk->size > 0) - { - chunkPtr->size += (MemoryData(theEnv)->ChunkInfoSize + nextChunk->size); - - topChunk = (struct chunkInfo *) (((char *) nextChunk) + nextChunk->size + MemoryData(theEnv)->ChunkInfoSize); - if (topChunk != NULL) - { topChunk->prevChunk = chunkPtr; } - else - { return(FALSE); } - - if (nextChunk->lastFree != NULL) - { nextChunk->lastFree->nextFree = nextChunk->nextFree; } - - if (nextChunk->nextFree != NULL) - { nextChunk->nextFree->lastFree = nextChunk->lastFree; } - - } - - /*===========================================*/ - /* Free the buffer if we can, but don't free */ - /* the first buffer if it's the only one. */ - /*===========================================*/ - - if ((chunkPtr->prevChunk == NULL) && - (chunkPtr->size == blockPtr->size)) - { - if (blockPtr->prevBlock != NULL) - { - blockPtr->prevBlock->nextBlock = blockPtr->nextBlock; - if (blockPtr->nextBlock != NULL) - { blockPtr->nextBlock->prevBlock = blockPtr->prevBlock; } - free((char *) blockPtr); - } - else - { - if (blockPtr->nextBlock != NULL) - { - blockPtr->nextBlock->prevBlock = NULL; - MemoryData(theEnv)->TopMemoryBlock = blockPtr->nextBlock; - free((char *) blockPtr); - } - } - } - - return(TRUE); + return EnvSetConserveMemory(GetCurrentEnvironment(),value); } -/***********************************************/ -/* ReturnAllBlocks: Frees all allocated blocks */ -/* back to the operating system. */ -/***********************************************/ -globle void ReturnAllBlocks( - void *theEnv) +globle int (*SetOutOfMemoryFunction(int (*functionPtr)(void *,size_t)))(void *,size_t) { - struct blockInfo *theBlock, *nextBlock; - struct longMemoryPtr *theLongMemory, *nextLongMemory; - - /*======================================*/ - /* Free up int based memory allocation. */ - /*======================================*/ - - theBlock = MemoryData(theEnv)->TopMemoryBlock; - while (theBlock != NULL) - { - nextBlock = theBlock->nextBlock; - free((char *) theBlock); - theBlock = nextBlock; - } - - MemoryData(theEnv)->TopMemoryBlock = NULL; + return EnvSetOutOfMemoryFunction(GetCurrentEnvironment(),functionPtr); + } - /*=======================================*/ - /* Free up long based memory allocation. */ - /*=======================================*/ +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ - theLongMemory = MemoryData(theEnv)->TopLongMemoryPtr; - while (theLongMemory != NULL) - { - nextLongMemory = theLongMemory->next; - genlongfree(theEnv,theLongMemory,(unsigned long) theLongMemory->size); - theLongMemory = nextLongMemory; - } - - MemoryData(theEnv)->TopLongMemoryPtr = NULL; - } -#endif diff --git a/src/memalloc.h b/src/memalloc.h index 9665323..bb9f81c 100644 --- a/src/memalloc.h +++ b/src/memalloc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* MEMORY ALLOCATION HEADER FILE */ /*******************************************************/ @@ -16,7 +16,28 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed HaltExecution check from the */ +/* EnvReleaseMem function. DR0863 */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Corrected code to remove compiler warnings. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed genlongalloc/genlongfree functions. */ +/* */ +/* Added get_mem and rtn_mem macros. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Removed deallocating message parameter from */ +/* EnvReleaseMem. */ +/* */ +/* Removed support for BLOCK_MEMORY. */ /* */ /*************************************************************/ @@ -29,9 +50,10 @@ struct chunkInfo; struct blockInfo; struct memoryPtr; -struct longMemoryPtr; +#ifndef MEM_TABLE_SIZE #define MEM_TABLE_SIZE 500 +#endif #ifdef LOCALE #undef LOCALE @@ -64,16 +86,14 @@ struct memoryPtr struct memoryPtr *next; }; -struct longMemoryPtr - { - struct longMemoryPtr *prev; - struct longMemoryPtr *next; - long size; - }; +#if (MEM_TABLE_SIZE > 0) +/* + * Normal memory management case + */ #define get_struct(theEnv,type) \ ((MemoryData(theEnv)->MemoryTable[sizeof(struct type)] == NULL) ? \ - ((struct type *) genalloc(theEnv,(unsigned) sizeof(struct type))) :\ + ((struct type *) genalloc(theEnv,sizeof(struct type))) :\ ((MemoryData(theEnv)->TempMemoryPtr = MemoryData(theEnv)->MemoryTable[sizeof(struct type)]),\ MemoryData(theEnv)->MemoryTable[sizeof(struct type)] = MemoryData(theEnv)->TempMemoryPtr->next,\ ((struct type *) MemoryData(theEnv)->TempMemoryPtr))) @@ -91,7 +111,7 @@ struct longMemoryPtr #define get_var_struct(theEnv,type,vsize) \ ((((sizeof(struct type) + vsize) < MEM_TABLE_SIZE) ? \ (MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize] == NULL) : 1) ? \ - ((struct type *) genalloc(theEnv,(unsigned) (sizeof(struct type) + vsize))) :\ + ((struct type *) genalloc(theEnv,(sizeof(struct type) + vsize))) :\ ((MemoryData(theEnv)->TempMemoryPtr = MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize]),\ MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize] = MemoryData(theEnv)->TempMemoryPtr->next,\ ((struct type *) MemoryData(theEnv)->TempMemoryPtr))) @@ -102,23 +122,44 @@ struct longMemoryPtr (MemoryData(theEnv)->TempMemoryPtr = (struct memoryPtr *) struct_ptr,\ MemoryData(theEnv)->TempMemoryPtr->next = MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize], \ MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize] = MemoryData(theEnv)->TempMemoryPtr) : \ - (genfree(theEnv,(void *) struct_ptr,(unsigned) MemoryData(theEnv)->TempSize),(struct memoryPtr *) struct_ptr))) - -#define get_var_struct2(theEnv,type,vsize) \ - ((((sizeof(struct type) + vsize) < (unsigned long) MEM_TABLE_SIZE) ? \ - (MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize] == NULL) : 1) ? \ - ((struct type *) gm3(theEnv,(long) (sizeof(struct type) + vsize))) :\ - ((MemoryData(theEnv)->TempMemoryPtr = MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize]),\ - MemoryData(theEnv)->MemoryTable[sizeof(struct type) + vsize] = MemoryData(theEnv)->TempMemoryPtr->next,\ + (genfree(theEnv,(void *) struct_ptr,MemoryData(theEnv)->TempSize),(struct memoryPtr *) struct_ptr))) + +#define get_mem(theEnv,size) \ + (((size < MEM_TABLE_SIZE) ? \ + (MemoryData(theEnv)->MemoryTable[size] == NULL) : 1) ? \ + ((struct type *) genalloc(theEnv,(size_t) (size))) :\ + ((MemoryData(theEnv)->TempMemoryPtr = MemoryData(theEnv)->MemoryTable[size]),\ + MemoryData(theEnv)->MemoryTable[size] = MemoryData(theEnv)->TempMemoryPtr->next,\ ((struct type *) MemoryData(theEnv)->TempMemoryPtr))) -#define rtn_var_struct2(theEnv,type,vsize,struct_ptr) \ - (MemoryData(theEnv)->TempSize2 = sizeof(struct type) + vsize, \ - (((MemoryData(theEnv)->TempSize2 < (unsigned long) MEM_TABLE_SIZE) ? \ - (MemoryData(theEnv)->TempMemoryPtr = (struct memoryPtr *) struct_ptr,\ - MemoryData(theEnv)->TempMemoryPtr->next = MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize2], \ - MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize2] = MemoryData(theEnv)->TempMemoryPtr) : \ - (rm3(theEnv,(void *) struct_ptr,(long) (sizeof(struct type) + vsize)),(struct memoryPtr *) struct_ptr)))) +#define rtn_mem(theEnv,size,ptr) \ + (MemoryData(theEnv)->TempSize = size, \ + ((MemoryData(theEnv)->TempSize < MEM_TABLE_SIZE) ? \ + (MemoryData(theEnv)->TempMemoryPtr = (struct memoryPtr *) ptr,\ + MemoryData(theEnv)->TempMemoryPtr->next = MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize], \ + MemoryData(theEnv)->MemoryTable[MemoryData(theEnv)->TempSize] = MemoryData(theEnv)->TempMemoryPtr) : \ + (genfree(theEnv,(void *) ptr,MemoryData(theEnv)->TempSize),(struct memoryPtr *) ptr))) + +#else // MEM_TABLE_SIZE == 0 +/* + * Debug case (routes all memory management through genalloc/genfree to take advantage of + * platform, memory debugging aids) + */ +#define get_struct(theEnv,type) ((struct type *) genalloc(theEnv,sizeof(struct type))) + +#define rtn_struct(theEnv,type,struct_ptr) (genfree(theEnv,struct_ptr,sizeof(struct type))) + +#define rtn_sized_struct(theEnv,size,struct_ptr) (genfree(theEnv,struct_ptr,size)) + +#define get_var_struct(theEnv,type,vsize) ((struct type *) genalloc(theEnv,(sizeof(struct type) + vsize))) + +#define rtn_var_struct(theEnv,type,vsize,struct_ptr) (genfree(theEnv,struct_ptr,sizeof(struct type)+vsize)) + +#define get_mem(theEnv,size) ((struct type *) genalloc(theEnv,(size_t) (size))) + +#define rtn_mem(theEnv,size,ptr) (genfree(theEnv,ptr,size)) + +#endif #define GenCopyMemory(type,cnt,dst,src) \ memcpy((void *) (dst),(void *) (src),sizeof(type) * (size_t) (cnt)) @@ -126,70 +167,55 @@ struct longMemoryPtr #define MEMORY_DATA 59 struct memoryData - { + { long int MemoryAmount; long int MemoryCalls; intBool ConserveMemory; - int (*OutOfMemoryFunction)(void *,unsigned long); -#if BLOCK_MEMORY - struct longMemoryPtr *TopLongMemoryPtr; - struct blockInfo *TopMemoryBlock; - int BlockInfoSize; - int ChunkInfoSize; - int BlockMemoryInitialized; -#endif + int (*OutOfMemoryFunction)(void *,size_t); struct memoryPtr *TempMemoryPtr; struct memoryPtr **MemoryTable; - unsigned int TempSize; - unsigned long TempSize2; + size_t TempSize; }; #define MemoryData(theEnv) ((struct memoryData *) GetEnvironmentData(theEnv,MEMORY_DATA)) -#if ENVIRONMENT_API_ONLY -#define GetConserveMemory(theEnv) EnvGetConserveMemory(theEnv) -#define MemRequests(theEnv) EnvMemRequests(theEnv) -#define MemUsed(theEnv) EnvMemUsed(theEnv) -#define ReleaseMem(theEnv,a,b) EnvReleaseMem(theEnv,a,b) -#define SetConserveMemory(theEnv,a) EnvSetConserveMemory(theEnv,a) -#define SetOutOfMemoryFunction(theEnv,a) EnvSetOutOfMemoryFunction(theEnv,a) -#else -#define GetConserveMemory() EnvGetConserveMemory(GetCurrentEnvironment()) -#define MemRequests() EnvMemRequests(GetCurrentEnvironment()) -#define MemUsed() EnvMemUsed(GetCurrentEnvironment()) -#define ReleaseMem(a,b) EnvReleaseMem(GetCurrentEnvironment(),a,b) -#define SetConserveMemory(a) EnvSetConserveMemory(GetCurrentEnvironment(),a) -#define SetOutOfMemoryFunction(a) EnvSetOutOfMemoryFunction(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeMemory(void *); - LOCALE void *genalloc(void *,unsigned int); - LOCALE int DefaultOutOfMemoryFunction(void *,unsigned long); - LOCALE int (*EnvSetOutOfMemoryFunction(void *,int (*)(void *,unsigned long)))(void *,unsigned long); - LOCALE int genfree(void *,void *,unsigned int); - LOCALE void *genrealloc(void *,void *,unsigned int,unsigned int); + LOCALE void *genalloc(void *,size_t); + LOCALE int DefaultOutOfMemoryFunction(void *,size_t); + LOCALE int (*EnvSetOutOfMemoryFunction(void *,int (*)(void *,size_t)))(void *,size_t); + LOCALE int genfree(void *,void *,size_t); + LOCALE void *genrealloc(void *,void *,size_t,size_t); LOCALE long EnvMemUsed(void *); LOCALE long EnvMemRequests(void *); LOCALE long UpdateMemoryUsed(void *,long int); LOCALE long UpdateMemoryRequests(void *,long int); - LOCALE long EnvReleaseMem(void *,long,int); - LOCALE void *gm1(void *,int); - LOCALE void *gm2(void *,unsigned int); - LOCALE void *gm3(void *,long); - LOCALE int rm(void *,void *,unsigned); - LOCALE int rm3(void *,void *,long); + LOCALE long EnvReleaseMem(void *,long); + LOCALE void *gm1(void *,size_t); + LOCALE void *gm2(void *,size_t); + LOCALE void *gm3(void *,size_t); + LOCALE int rm(void *,void *,size_t); + LOCALE int rm3(void *,void *,size_t); LOCALE unsigned long PoolSize(void *); LOCALE unsigned long ActualPoolSize(void *); - LOCALE void *RequestChunk(void *,unsigned int); - LOCALE int ReturnChunk(void *,void *,unsigned int); - LOCALE void *genlongalloc(void *,unsigned long); - LOCALE int genlongfree(void *,void *,unsigned long); + LOCALE void *RequestChunk(void *,size_t); + LOCALE int ReturnChunk(void *,void *,size_t); LOCALE intBool EnvSetConserveMemory(void *,intBool); LOCALE intBool EnvGetConserveMemory(void *); LOCALE void genmemcpy(char *,char *,unsigned long); LOCALE void ReturnAllBlocks(void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool GetConserveMemory(void); + LOCALE long int MemRequests(void); + LOCALE long int MemUsed(void); + LOCALE long int ReleaseMem(long); + LOCALE intBool SetConserveMemory(intBool); + LOCALE int (*SetOutOfMemoryFunction(int (*)(void *,size_t)))(void *,size_t); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_memalloc */ diff --git a/src/miscfun.c b/src/miscfun.c index 58f6c55..ad5b7eb 100644 --- a/src/miscfun.c +++ b/src/miscfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.39 01/29/15 */ /* */ /* MISCELLANEOUS FUNCTIONS MODULE */ /*******************************************************/ @@ -13,9 +13,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -34,6 +35,34 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems. */ +/* */ +/* Renamed EX_MATH compiler flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the IO_FUNCTIONS compilation flag. */ +/* */ +/* Removed code associated with HELP_FUNCTIONS */ +/* and EMACS_EDITOR compiler flags. */ +/* */ +/* Added operating-system function. */ +/* */ +/* Added new function (for future use). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Removed deallocating message parameter from */ +/* EnvReleaseMem. */ +/* */ +/* Removed support for BLOCK_MEMORY. */ +/* */ /*************************************************************/ #define _MISCFUN_SOURCE_ @@ -62,8 +91,8 @@ #define MISCFUN_DATA 9 struct miscFunctionData - { - long int GensymNumber; + { + long long GensymNumber; }; #define MiscFunctionData(theEnv) ((struct miscFunctionData *) GetEnvironmentData(theEnv,MISCFUN_DATA)) @@ -74,6 +103,7 @@ struct miscFunctionData static void ExpandFuncMultifield(void *,DATA_OBJECT *,EXPRESSION *, EXPRESSION **,void *); + static int FindLanguageType(void *,const char *); /*****************************************************************/ /* MiscFunctionDefinitions: Initializes miscellaneous functions. */ @@ -83,24 +113,25 @@ globle void MiscFunctionDefinitions( { AllocateEnvironmentData(theEnv,MISCFUN_DATA,sizeof(struct miscFunctionData),NULL); MiscFunctionData(theEnv)->GensymNumber = 1; - + #if ! RUN_TIME EnvDefineFunction2(theEnv,"gensym", 'w', PTIEF GensymFunction, "GensymFunction", "00"); EnvDefineFunction2(theEnv,"gensym*", 'w', PTIEF GensymStarFunction, "GensymStarFunction", "00"); - EnvDefineFunction2(theEnv,"setgen", 'l', PTIEF SetgenFunction, "SetgenFunction", "11i"); + EnvDefineFunction2(theEnv,"setgen", 'g', PTIEF SetgenFunction, "SetgenFunction", "11i"); EnvDefineFunction2(theEnv,"system", 'v', PTIEF gensystem, "gensystem", "1*k"); - EnvDefineFunction2(theEnv,"length", 'l', PTIEF LengthFunction, "LengthFunction", "11q"); - EnvDefineFunction2(theEnv,"length$", 'l', PTIEF LengthFunction, "LengthFunction", "11q"); + EnvDefineFunction2(theEnv,"length", 'g', PTIEF LengthFunction, "LengthFunction", "11q"); + EnvDefineFunction2(theEnv,"length$", 'g', PTIEF LengthFunction, "LengthFunction", "11q"); EnvDefineFunction2(theEnv,"time", 'd', PTIEF TimeFunction, "TimeFunction", "00"); - EnvDefineFunction2(theEnv,"random", 'l', PTIEF RandomFunction, "RandomFunction", "02i"); + EnvDefineFunction2(theEnv,"random", 'g', PTIEF RandomFunction, "RandomFunction", "02i"); EnvDefineFunction2(theEnv,"seed", 'v', PTIEF SeedFunction, "SeedFunction", "11i"); EnvDefineFunction2(theEnv,"conserve-mem", 'v', PTIEF ConserveMemCommand, "ConserveMemCommand", "11w"); - EnvDefineFunction2(theEnv,"release-mem", 'l', PTIEF ReleaseMemCommand, "ReleaseMemCommand", "00"); + EnvDefineFunction2(theEnv,"release-mem", 'g', PTIEF ReleaseMemCommand, "ReleaseMemCommand", "00"); #if DEBUGGING_FUNCTIONS - EnvDefineFunction2(theEnv,"mem-used", 'l', PTIEF MemUsedCommand, "MemUsedCommand", "00"); - EnvDefineFunction2(theEnv,"mem-requests", 'l', PTIEF MemRequestsCommand, "MemRequestsCommand", "00"); + EnvDefineFunction2(theEnv,"mem-used", 'g', PTIEF MemUsedCommand, "MemUsedCommand", "00"); + EnvDefineFunction2(theEnv,"mem-requests", 'g', PTIEF MemRequestsCommand, "MemRequestsCommand", "00"); #endif EnvDefineFunction2(theEnv,"options", 'v', PTIEF OptionsCommand, "OptionsCommand", "00"); + EnvDefineFunction2(theEnv,"operating-system", 'w', PTIEF OperatingSystemFunction,"OperatingSystemFunction", "00"); EnvDefineFunction2(theEnv,"(expansion-call)", 'u', PTIEF ExpandFuncCall, "ExpandFuncCall",NULL); EnvDefineFunction2(theEnv,"expand$",'u', PTIEF DummyExpandFuncMultifield, "DummyExpandFuncMultifield","11m"); @@ -118,6 +149,8 @@ globle void MiscFunctionDefinitions( EnvDefineFunction2(theEnv,"apropos", 'v', PTIEF AproposCommand, "AproposCommand", "11w"); EnvDefineFunction2(theEnv,"get-function-list", 'm', PTIEF GetFunctionListFunction, "GetFunctionListFunction", "00"); EnvDefineFunction2(theEnv,"funcall",'u', PTIEF FuncallFunction,"FuncallFunction","1**k"); + EnvDefineFunction2(theEnv,"new",'u', PTIEF NewFunction,"NewFunction","1*uw"); + EnvDefineFunction2(theEnv,"call",'u', PTIEF CallFunction,"CallFunction","1*u"); EnvDefineFunction2(theEnv,"timer",'d', PTIEF TimerFunction,"TimerFunction","**"); #endif } @@ -135,10 +168,10 @@ globle void CreateFunction( /*****************************************************************/ /* SetgenFunction: H/L access routine for the setgen function. */ /*****************************************************************/ -globle long int SetgenFunction( +globle long long SetgenFunction( void *theEnv) { - long theLong; + long long theLong; DATA_OBJECT theValue; /*==========================================================*/ @@ -154,7 +187,7 @@ globle long int SetgenFunction( theLong = ValueToLong(theValue.value); - if (theLong < 1L) + if (theLong < 1LL) { ExpectedTypeError1(theEnv,"setgen",1,"number (greater than or equal to 1)"); return(MiscFunctionData(theEnv)->GensymNumber); @@ -176,8 +209,8 @@ globle long int SetgenFunction( globle void *GensymFunction( void *theEnv) { - char genstring[15]; - + char genstring[128]; + /*===========================================*/ /* The gensym function accepts no arguments. */ /*===========================================*/ @@ -189,7 +222,7 @@ globle void *GensymFunction( /* as the postfix. */ /*================================================*/ - sprintf(genstring,"gen%ld",MiscFunctionData(theEnv)->GensymNumber); + gensprintf(genstring,"gen%lld",MiscFunctionData(theEnv)->GensymNumber); MiscFunctionData(theEnv)->GensymNumber++; /*====================*/ @@ -226,8 +259,8 @@ globle void *GensymStarFunction( globle void *GensymStar( void *theEnv) { - char genstring[15]; - + char genstring[128]; + /*=======================================================*/ /* Create a symbol using the current gensym index as the */ /* postfix. If the symbol is already present in the */ @@ -237,7 +270,7 @@ globle void *GensymStar( do { - sprintf(genstring,"gen%ld",MiscFunctionData(theEnv)->GensymNumber); + gensprintf(genstring,"gen%lld",MiscFunctionData(theEnv)->GensymNumber); MiscFunctionData(theEnv)->GensymNumber++; } while (FindSymbolHN(theEnv,genstring) != NULL); @@ -253,13 +286,13 @@ globle void *GensymStar( /* RandomFunction: H/L access routine for */ /* the random function. */ /********************************************/ -globle long RandomFunction( +globle long long RandomFunction( void *theEnv) { int argCount; - long rv; + long long rv; DATA_OBJECT theValue; - long begin, end; + long long begin, end; /*====================================*/ /* The random function accepts either */ @@ -267,11 +300,11 @@ globle long RandomFunction( /*====================================*/ argCount = EnvRtnArgCount(theEnv); - + if ((argCount != 0) && (argCount != 2)) { PrintErrorID(theEnv,"MISCFUN",2,FALSE); - EnvPrintRouter(theEnv,WERROR,"Function random expected either 0 or 2 arguments\n"); + EnvPrintRouter(theEnv,WERROR,"Function random expected either 0 or 2 arguments\n"); } /*========================================*/ @@ -279,7 +312,7 @@ globle long RandomFunction( /*========================================*/ rv = genrand(); - + if (argCount == 2) { if (EnvArgTypeCheck(theEnv,"random",1,INTEGER,&theValue) == FALSE) return(rv); @@ -289,14 +322,14 @@ globle long RandomFunction( if (end < begin) { PrintErrorID(theEnv,"MISCFUN",3,FALSE); - EnvPrintRouter(theEnv,WERROR,"Function random expected argument #1 to be less than argument #2\n"); + EnvPrintRouter(theEnv,WERROR,"Function random expected argument #1 to be less than argument #2\n"); return(rv); } - + rv = begin + (rv % ((end - begin) + 1)); } - - + + return(rv); } @@ -327,7 +360,7 @@ globle void SeedFunction( /* LengthFunction: H/L access routine for */ /* the length$ function. */ /********************************************/ -globle long int LengthFunction( +globle long long LengthFunction( void *theEnv) { DATA_OBJECT item; @@ -369,21 +402,21 @@ globle long int LengthFunction( /* ReleaseMemCommand: H/L access routine */ /* for the release-mem function. */ /*******************************************/ -globle long ReleaseMemCommand( +globle long long ReleaseMemCommand( void *theEnv) { /*================================================*/ /* The release-mem function accepts no arguments. */ /*================================================*/ - if (EnvArgCountCheck(theEnv,"release-mem",EXACTLY,0) == -1) return(0); + if (EnvArgCountCheck(theEnv,"release-mem",EXACTLY,0) == -1) return(0LL); /*========================================*/ /* Release memory to the operating system */ /* and return the amount of memory freed. */ /*========================================*/ - return(EnvReleaseMem(theEnv,-1L,FALSE)); + return(EnvReleaseMem(theEnv,-1L)); } /******************************************/ @@ -393,7 +426,7 @@ globle long ReleaseMemCommand( globle void ConserveMemCommand( void *theEnv) { - char *argument; + const char *argument; DATA_OBJECT theValue; /*===================================*/ @@ -444,7 +477,7 @@ globle void ConserveMemCommand( /* MemUsedCommand: H/L access routine */ /* for the mem-used command. */ /****************************************/ -globle long int MemUsedCommand( +globle long long MemUsedCommand( void *theEnv) { /*=============================================*/ @@ -465,7 +498,7 @@ globle long int MemUsedCommand( /* MemRequestsCommand: H/L access routine */ /* for the mem-requests command. */ /********************************************/ -globle long int MemRequestsCommand( +globle long long MemRequestsCommand( void *theEnv) { /*=================================================*/ @@ -491,7 +524,7 @@ globle long int MemRequestsCommand( globle void AproposCommand( void *theEnv) { - char *argument; + const char *argument; DATA_OBJECT argPtr; struct symbolHashNode *hashPtr = NULL; size_t theLength; @@ -553,32 +586,23 @@ globle void OptionsCommand( #if UNIX_V EnvPrintRouter(theEnv,WDISPLAY,"UNIX System V or 4.2BSD "); #endif +#if DARWIN + EnvPrintRouter(theEnv,WDISPLAY,"Darwin "); +#endif +#if LINUX + EnvPrintRouter(theEnv,WDISPLAY,"Linux "); +#endif #if UNIX_7 EnvPrintRouter(theEnv,WDISPLAY,"UNIX System III Version 7 or Sun Unix "); #endif -#if MAC_MCW - EnvPrintRouter(theEnv,WDISPLAY,"Apple Macintosh with CodeWarrior"); -#endif #if MAC_XCD EnvPrintRouter(theEnv,WDISPLAY,"Apple Macintosh with Xcode"); #endif -#if IBM_MSC - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Microsoft C"); -#endif -#if IBM_ZTC - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Zortech C"); +#if WIN_MVC + EnvPrintRouter(theEnv,WDISPLAY,"Microsoft Windows with Microsoft Visual C++"); #endif -#if IBM_SC - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Symantec C++"); -#endif -#if IBM_ICB - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Intel C Code Builder"); -#endif -#if IBM_TBC - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Turbo C"); -#endif -#if IBM_MCW - EnvPrintRouter(theEnv,WDISPLAY,"IBM PC with Metrowerks CodeWarrior"); +#if WIN_GCC + EnvPrintRouter(theEnv,WDISPLAY,"Microsoft Windows with DJGPP"); #endif EnvPrintRouter(theEnv,WDISPLAY,"\n"); @@ -681,27 +705,20 @@ EnvPrintRouter(theEnv,WDISPLAY," Binary saving of instances is "); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Extended math package is "); -#if EX_MATH +EnvPrintRouter(theEnv,WDISPLAY,"Extended math function package is "); +#if EXTENDED_MATH_FUNCTIONS EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); #else EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Text processing package is "); +EnvPrintRouter(theEnv,WDISPLAY,"Text processing function package is "); #if TEXTPRO_FUNCTIONS EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); #else EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Help system is "); -#if HELP_FUNCTIONS - EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); -#else - EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); -#endif - EnvPrintRouter(theEnv,WDISPLAY,"Bload capability is "); #if BLOAD_ONLY EnvPrintRouter(theEnv,WDISPLAY,"BLOAD ONLY"); @@ -717,13 +734,6 @@ EnvPrintRouter(theEnv,WDISPLAY,"Bload capability is "); #endif EnvPrintRouter(theEnv,WDISPLAY,"\n"); -EnvPrintRouter(theEnv,WDISPLAY,"EMACS Editor is "); -#if EMACS_EDITOR - EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); -#else - EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); -#endif - EnvPrintRouter(theEnv,WDISPLAY,"Construct compiler is "); #if CONSTRUCT_COMPILER EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); @@ -731,15 +741,8 @@ EnvPrintRouter(theEnv,WDISPLAY,"Construct compiler is "); EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Basic I/O is "); -#if BASIC_IO - EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); -#else - EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); -#endif - -EnvPrintRouter(theEnv,WDISPLAY,"Extended I/O is "); -#if EXT_IO +EnvPrintRouter(theEnv,WDISPLAY,"I/O function package is "); +#if IO_FUNCTIONS EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); #else EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); @@ -759,20 +762,13 @@ EnvPrintRouter(theEnv,WDISPLAY,"Multifield function package is "); EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Debugging functions are "); +EnvPrintRouter(theEnv,WDISPLAY,"Debugging function package is "); #if DEBUGGING_FUNCTIONS EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); #else EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); #endif -EnvPrintRouter(theEnv,WDISPLAY,"Block memory is "); -#if BLOCK_MEMORY - EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); -#else - EnvPrintRouter(theEnv,WDISPLAY,"OFF\n"); -#endif - EnvPrintRouter(theEnv,WDISPLAY,"Window Interface flag is "); #if WINDOW_INTERFACE EnvPrintRouter(theEnv,WDISPLAY,"ON\n"); @@ -795,6 +791,54 @@ EnvPrintRouter(theEnv,WDISPLAY,"Run time module is "); #endif } +/***********************************************/ +/* OperatingSystemFunction: H/L access routine */ +/* for the operating system function. */ +/***********************************************/ +globle void *OperatingSystemFunction( + void *theEnv) + { + EnvArgCountCheck(theEnv,"operating-system",EXACTLY,0); + +#if GENERIC + return(EnvAddSymbol(theEnv,"UNKNOWN")); +#endif + +#if VAX_VMS + return(EnvAddSymbol(theEnv,"VMS")); +#endif + +#if UNIX_V + return(EnvAddSymbol(theEnv,"UNIX-V")); +#endif + +#if UNIX_7 + return(EnvAddSymbol(theEnv,"UNIX-7")); +#endif + +#if LINUX + return(EnvAddSymbol(theEnv,"LINUX")); +#endif + +#if DARWIN + return(EnvAddSymbol(theEnv,"DARWIN")); +#endif + +#if MAC_XCD + return(EnvAddSymbol(theEnv,"MAC-OS-X")); +#endif + +#if IBM && (! WINDOW_INTERFACE) + return(EnvAddSymbol(theEnv,"DOS")); +#endif + +#if IBM && WINDOW_INTERFACE + return(EnvAddSymbol(theEnv,"WINDOWS")); +#endif + + return(EnvAddSymbol(theEnv,"UNKNOWN")); + } + /******************************************************************** NAME : ExpandFuncCall DESCRIPTION : This function is a wrap-around for a normal @@ -1093,31 +1137,32 @@ globle void FuncallFunction( int argCount, i, j; DATA_OBJECT theValue; FUNCTION_REFERENCE theReference; - char *name; + const char *name; struct multifield *theMultifield; struct expr *lastAdd = NULL, *nextAdd, *multiAdd; - + struct FunctionDefinition *theFunction; + /*==================================*/ /* Set up the default return value. */ /*==================================*/ - + SetpType(returnValue,SYMBOL); SetpValue(returnValue,EnvFalseSymbol(theEnv)); - + /*=================================================*/ /* The funcall function has at least one argument: */ /* the name of the function being called. */ /*=================================================*/ - + if ((argCount = EnvArgCountCheck(theEnv,"funcall",AT_LEAST,1)) == -1) return; - + /*============================================*/ /* Get the name of the function to be called. */ /*============================================*/ - - if (EnvArgTypeCheck(theEnv,"funcall",1,SYMBOL_OR_STRING,&theValue) == FALSE) + + if (EnvArgTypeCheck(theEnv,"funcall",1,SYMBOL_OR_STRING,&theValue) == FALSE) { return; } - + /*====================*/ /* Find the function. */ /*====================*/ @@ -1126,24 +1171,39 @@ globle void FuncallFunction( if (! GetFunctionReference(theEnv,name,&theReference)) { ExpectedTypeError1(theEnv,"funcall",1,"function, deffunction, or generic function name"); - return; + return; } - - ExpressionInstall(theEnv,&theReference); - + + /*====================================*/ + /* Functions with specialized parsers */ + /* cannot be used with funcall. */ + /*====================================*/ + + if (theReference.type == FCALL) + { + theFunction = FindFunction(theEnv,name); + if (theFunction->parser != NULL) + { + ExpectedTypeError1(theEnv,"funcall",1,"function without specialized parser"); + return; + } + } + /*======================================*/ /* Add the arguments to the expression. */ /*======================================*/ - + + ExpressionInstall(theEnv,&theReference); + for (i = 2; i <= argCount; i++) { EnvRtnUnknown(theEnv,i,&theValue); if (GetEvaluationError(theEnv)) - { + { ExpressionDeinstall(theEnv,&theReference); - return; + return; } - + switch(GetType(theValue)) { case MULTIFIELD: @@ -1169,7 +1229,7 @@ globle void FuncallFunction( ExpressionInstall(theEnv,lastAdd); break; - + default: nextAdd = GenConstant(theEnv,GetType(theValue),GetValue(theValue)); if (lastAdd == NULL) @@ -1178,7 +1238,7 @@ globle void FuncallFunction( { lastAdd->nextArg = nextAdd; } lastAdd = nextAdd; ExpressionInstall(theEnv,lastAdd); - break; + break; } } @@ -1195,27 +1255,188 @@ globle void FuncallFunction( EnvPrintRouter(theEnv,WERROR,"Function funcall called with the wrong number of arguments for deffunction "); EnvPrintRouter(theEnv,WERROR,EnvGetDeffunctionName(theEnv,theReference.value)); EnvPrintRouter(theEnv,WERROR,"\n"); - ExpressionDeinstall(theEnv,&theReference); + ExpressionDeinstall(theEnv,&theReference); ReturnExpression(theEnv,theReference.argList); return; } } #endif - + /*======================*/ /* Call the expression. */ /*======================*/ - + EvaluateExpression(theEnv,&theReference,returnValue); - + /*========================================*/ /* Return the expression data structures. */ /*========================================*/ - + ExpressionDeinstall(theEnv,&theReference); ReturnExpression(theEnv,theReference.argList); } - + +/***********************************/ +/* NewFunction: H/L access routine */ +/* for the new function. */ +/***********************************/ +globle void NewFunction( + void *theEnv, + DATA_OBJECT *returnValue) + { + int theType; + DATA_OBJECT theValue; + const char *name; + + /*==================================*/ + /* Set up the default return value. */ + /*==================================*/ + + SetpType(returnValue,SYMBOL); + SetpValue(returnValue,EnvFalseSymbol(theEnv)); + + /*================================================================*/ + /* The new function has at least two arguments: the language type */ + /* of the class (e.g. java, .net, c++) and the name of the class. */ + /*================================================================*/ + + if (EnvArgCountCheck(theEnv,"new",AT_LEAST,1) == -1) return; + + /*====================================*/ + /* Get the name of the language type. */ + /*====================================*/ + + if (EnvArgTypeCheck(theEnv,"new",1,SYMBOL,&theValue) == FALSE) + { return; } + + /*=========================*/ + /* Find the language type. */ + /*=========================*/ + + name = DOToString(theValue); + + theType = FindLanguageType(theEnv,name); + + if (theType == -1) + { + ExpectedTypeError1(theEnv,"new",1,"external language"); + return; + } + + /*====================================================*/ + /* Invoke the new function for the specific language. */ + /*====================================================*/ + + if ((EvaluationData(theEnv)->ExternalAddressTypes[theType] != NULL) && + (EvaluationData(theEnv)->ExternalAddressTypes[theType]->newFunction != NULL)) + { (*EvaluationData(theEnv)->ExternalAddressTypes[theType]->newFunction)(theEnv,returnValue); } + } + +/************************************/ +/* CallFunction: H/L access routine */ +/* for the new function. */ +/************************************/ +globle void CallFunction( + void *theEnv, + DATA_OBJECT *returnValue) + { + int theType; + DATA_OBJECT theValue; + const char *name; + int argumentCount; + struct externalAddressHashNode *theEA; + + /*==================================*/ + /* Set up the default return value. */ + /*==================================*/ + + SetpType(returnValue,SYMBOL); + SetpValue(returnValue,EnvFalseSymbol(theEnv)); + + /*=====================================================*/ + /* The call function has at least one argument: either */ + /* an external address or the language type of the */ + /* method being called (e.g. java, .net, c++). */ + /*=====================================================*/ + + if ((argumentCount = EnvArgCountCheck(theEnv,"call",AT_LEAST,1)) == -1) return; + + /*=========================*/ + /* Get the first argument. */ + /*=========================*/ + + EnvRtnUnknown(theEnv,1,&theValue); + + /*============================================*/ + /* If the first argument is a symbol, then it */ + /* should be an external language type. */ + /*============================================*/ + + if (GetType(theValue) == SYMBOL) + { + name = DOToString(theValue); + + theType = FindLanguageType(theEnv,name); + + if (theType == -1) + { + ExpectedTypeError1(theEnv,"call",1,"external language symbol or external address"); + return; + } + + /*====================================================================*/ + /* Invoke the call function for the specific language. Typically this */ + /* will invoke a static method of a class (specified with the third */ + /* and second arguments to the call function. */ + /*====================================================================*/ + + if ((EvaluationData(theEnv)->ExternalAddressTypes[theType] != NULL) && + (EvaluationData(theEnv)->ExternalAddressTypes[theType]->callFunction != NULL)) + { (*EvaluationData(theEnv)->ExternalAddressTypes[theType]->callFunction)(theEnv,&theValue,returnValue); } + + return; + } + + /*===============================================*/ + /* If the first argument is an external address, */ + /* then we can determine the external language */ + /* type be examining the pointer. */ + /*===============================================*/ + + if (GetType(theValue) == EXTERNAL_ADDRESS) + { + theEA = (struct externalAddressHashNode *) GetValue(theValue); + + theType = theEA->type; + + if ((EvaluationData(theEnv)->ExternalAddressTypes[theType] != NULL) && + (EvaluationData(theEnv)->ExternalAddressTypes[theType]->callFunction != NULL)) + { (*EvaluationData(theEnv)->ExternalAddressTypes[theType]->callFunction)(theEnv,&theValue,returnValue); } + + return; + } + + ExpectedTypeError1(theEnv,"call",1,"external language symbol or external address"); + } + +/************************************/ +/* FindLanguageType: */ +/************************************/ +static int FindLanguageType( + void *theEnv, + const char *languageName) + { + int theType; + + for (theType = 0; theType < EvaluationData(theEnv)->numberOfAddressTypes; theType++) + { + if (strcmp(EvaluationData(theEnv)->ExternalAddressTypes[theType]->name,languageName) == 0) + { return(theType); } + } + + return -1; + } + /************************************/ /* TimeFunction: H/L access routine */ /* for the time function. */ @@ -1248,7 +1469,7 @@ globle double TimerFunction( DATA_OBJECT returnValue; startTime = gentime(); - + numa = EnvRtnArgCount(theEnv); i = 1; diff --git a/src/miscfun.h b/src/miscfun.h index c48a7da..1a5c7e9 100644 --- a/src/miscfun.h +++ b/src/miscfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* MISCELLANEOUS FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -15,10 +15,47 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES, */ +/* DYNAMIC_SALIENCE, INCREMENTAL_RESET, */ +/* LOGICAL_DEPENDENCIES, IMPERATIVE_METHODS */ +/* INSTANCE_PATTERN_MATCHING, */ +/* IMPERATIVE_MESSAGE_HANDLERS, and */ +/* AUXILIARY_MESSAGE_HANDLERS compilation flags. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems. */ +/* */ +/* Renamed EX_MATH compiler flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the IO_FUNCTIONS compilation flag. */ +/* */ +/* Removed code associated with HELP_FUNCTIONS */ +/* and EMACS_EDITOR compiler flags. */ +/* */ +/* Added operating-system function. */ +/* */ +/* Added new function (for future use). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ /* */ /*************************************************************/ @@ -38,17 +75,18 @@ LOCALE void MiscFunctionDefinitions(void *); LOCALE void CreateFunction(void *,DATA_OBJECT_PTR); - LOCALE long int SetgenFunction(void *); + LOCALE long long SetgenFunction(void *); LOCALE void *GensymFunction(void *); LOCALE void *GensymStarFunction(void *); - LOCALE long RandomFunction(void *); + LOCALE long long RandomFunction(void *); LOCALE void SeedFunction(void *); - LOCALE long int LengthFunction(void *); + LOCALE long long LengthFunction(void *); LOCALE void ConserveMemCommand(void *); - LOCALE long int ReleaseMemCommand(void *); - LOCALE long int MemUsedCommand(void *); - LOCALE long int MemRequestsCommand(void *); + LOCALE long long ReleaseMemCommand(void *); + LOCALE long long MemUsedCommand(void *); + LOCALE long long MemRequestsCommand(void *); LOCALE void OptionsCommand(void *); + LOCALE void *OperatingSystemFunction(void *); LOCALE void ExpandFuncCall(void *,DATA_OBJECT *); LOCALE void DummyExpandFuncMultifield(void *,DATA_OBJECT *); LOCALE void *CauseEvaluationError(void *); @@ -58,10 +96,12 @@ LOCALE void *GensymStar(void *); LOCALE void GetFunctionListFunction(void *,DATA_OBJECT *); LOCALE void FuncallFunction(void *,DATA_OBJECT *); + LOCALE void NewFunction(void *,DATA_OBJECT *); + LOCALE void CallFunction(void *,DATA_OBJECT *); LOCALE double TimerFunction(void *); LOCALE double TimeFunction(void *); -#endif +#endif /* _H_miscfun */ diff --git a/src/modulbin.c b/src/modulbin.c index bf26112..00ae446 100644 --- a/src/modulbin.c +++ b/src/modulbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -14,10 +14,12 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #define _MODULBIN_SOURCE_ @@ -230,12 +232,12 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; space = sizeof(long) * 2; - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); - GenWrite(&DefmoduleData(theEnv)->BNumberOfDefmodules,(unsigned long) sizeof(long int),fp); - GenWrite(&DefmoduleData(theEnv)->NumberOfPortItems,(unsigned long) sizeof(long int),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&DefmoduleData(theEnv)->BNumberOfDefmodules,sizeof(long int),fp); + GenWrite(&DefmoduleData(theEnv)->NumberOfPortItems,sizeof(long int),fp); } /*********************************************/ @@ -246,7 +248,7 @@ static void BsaveBinaryItem( void *theEnv, FILE *fp) { - unsigned long int space; + size_t space; struct defmodule *defmodulePtr; struct bsaveDefmodule newDefmodule; struct bsavePortItem newPortItem; @@ -259,7 +261,7 @@ static void BsaveBinaryItem( space = DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct bsaveDefmodule); space += DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct bsavePortItem); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*==========================================*/ /* Write out each defmodule data structure. */ @@ -302,7 +304,7 @@ static void BsaveBinaryItem( } newDefmodule.bsaveID = defmodulePtr->bsaveID; - GenWrite(&newDefmodule,(unsigned long) sizeof(struct bsaveDefmodule),fp); + GenWrite(&newDefmodule,sizeof(struct bsaveDefmodule),fp); } /*==========================================*/ @@ -330,7 +332,7 @@ static void BsaveBinaryItem( if (theList->next == NULL) newPortItem.next = -1L; else newPortItem.next = DefmoduleData(theEnv)->NumberOfPortItems; - GenWrite(&newPortItem,(unsigned long) sizeof(struct bsavePortItem),fp); + GenWrite(&newPortItem,sizeof(struct bsavePortItem),fp); } for (theList = defmodulePtr->exportList; @@ -350,7 +352,7 @@ static void BsaveBinaryItem( if (theList->next == NULL) newPortItem.next = -1L; else newPortItem.next = DefmoduleData(theEnv)->NumberOfPortItems; - GenWrite(&newPortItem,(unsigned long) sizeof(struct bsavePortItem),fp); + GenWrite(&newPortItem,sizeof(struct bsavePortItem),fp); } defmodulePtr = (struct defmodule *) EnvGetNextDefmodule(theEnv,defmodulePtr); @@ -376,16 +378,16 @@ static void BsaveBinaryItem( static void BloadStorage( void *theEnv) { - unsigned long int space; + size_t space; /*=======================================*/ /* Determine the number of defmodule and */ /* port item data structures to be read. */ /*=======================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&DefmoduleData(theEnv)->BNumberOfDefmodules,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DefmoduleData(theEnv)->NumberOfPortItems,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&DefmoduleData(theEnv)->BNumberOfDefmodules,sizeof(long int)); + GenReadBinary(theEnv,&DefmoduleData(theEnv)->NumberOfPortItems,sizeof(long int)); /*================================*/ /* Allocate the space needed for */ @@ -398,8 +400,8 @@ static void BloadStorage( return; } - space = (unsigned long) (DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct defmodule)); - DefmoduleData(theEnv)->DefmoduleArray = (struct defmodule *) genlongalloc(theEnv,space); + space = (DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct defmodule)); + DefmoduleData(theEnv)->DefmoduleArray = (struct defmodule *) genalloc(theEnv,space); /*================================*/ /* Allocate the space needed for */ @@ -412,8 +414,8 @@ static void BloadStorage( return; } - space = (unsigned long) (DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct portItem)); - DefmoduleData(theEnv)->PortItemArray = (struct portItem *) genlongalloc(theEnv,space); + space = (DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct portItem)); + DefmoduleData(theEnv)->PortItemArray = (struct portItem *) genalloc(theEnv,space); } /********************************************/ @@ -423,13 +425,13 @@ static void BloadStorage( static void BloadBinaryItem( void *theEnv) { - unsigned long int space; + size_t space; - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); if (DefmoduleData(theEnv)->BNumberOfDefmodules == 0) return; - BloadandRefresh(theEnv,DefmoduleData(theEnv)->BNumberOfDefmodules,(unsigned) sizeof(struct bsaveDefmodule),UpdateDefmodule); - BloadandRefresh(theEnv,DefmoduleData(theEnv)->NumberOfPortItems,(unsigned) sizeof(struct bsavePortItem),UpdatePortItem); + BloadandRefresh(theEnv,DefmoduleData(theEnv)->BNumberOfDefmodules,sizeof(struct bsaveDefmodule),UpdateDefmodule); + BloadandRefresh(theEnv,DefmoduleData(theEnv)->NumberOfPortItems,sizeof(struct bsavePortItem),UpdatePortItem); SetListOfDefmodules(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray); EnvSetCurrentModule(theEnv,(void *) EnvGetNextDefmodule(theEnv,NULL)); @@ -460,7 +462,7 @@ static void UpdateDefmodule( { DefmoduleData(theEnv)->DefmoduleArray[obji].itemsArray = NULL; } else { - DefmoduleData(theEnv)->DefmoduleArray[obji].itemsArray = + DefmoduleData(theEnv)->DefmoduleArray[obji].itemsArray = (struct defmoduleItemHeader **) gm2(theEnv,sizeof(void *) * GetNumberOfModuleItems(theEnv)); } @@ -543,7 +545,7 @@ static void ClearBload( void *theEnv) { long i; - unsigned long space; + size_t space; struct portItem *theList; /*===========================*/ @@ -581,18 +583,18 @@ static void ClearBload( /*================================*/ space = DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct defmodule); - if (space != 0) genlongfree(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray,space); + if (space != 0) genfree(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray,space); DefmoduleData(theEnv)->BNumberOfDefmodules = 0; - + /*================================*/ /* Deallocate the space used for */ /* the port item data structures. */ /*================================*/ space = DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct portItem); - if (space != 0) genlongfree(theEnv,(void *) DefmoduleData(theEnv)->PortItemArray,space); + if (space != 0) genfree(theEnv,(void *) DefmoduleData(theEnv)->PortItemArray,space); DefmoduleData(theEnv)->NumberOfPortItems = 0; - + /*===========================*/ /* Reset module information. */ /*===========================*/ diff --git a/src/modulbin.h b/src/modulbin.h index 835403b..29acf5e 100644 --- a/src/modulbin.h +++ b/src/modulbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE BSAVE/BLOAD HEADER FILE */ /*******************************************************/ @@ -13,10 +13,12 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ /*************************************************************/ #ifndef _H_modulbin @@ -74,7 +76,7 @@ struct bsavePortItem struct defmoduleItemHeader *); #endif -#endif +#endif /* _H_modulbin */ diff --git a/src/modulbsc.c b/src/modulbsc.c index 5c32546..5732a90 100644 --- a/src/modulbsc.c +++ b/src/modulbsc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* DEFMODULE BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -15,10 +15,19 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _MODULBSC_SOURCE_ @@ -37,6 +46,7 @@ #include "router.h" #include "argacces.h" #include "bload.h" +#include "multifld.h" #include "envrnmnt.h" #include "modulbsc.h" @@ -47,7 +57,7 @@ static void ClearDefmodules(void *); #if DEFMODULE_CONSTRUCT - static void SaveDefmodules(void *,void *,char *); + static void SaveDefmodules(void *,void *,const char *); #endif /*****************************************************************/ @@ -96,7 +106,7 @@ static void ClearDefmodules( CreateMainModule(theEnv); DefmoduleData(theEnv)->MainModuleRedefinable = TRUE; #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -111,9 +121,9 @@ static void ClearDefmodules( static void SaveDefmodules( void *theEnv, void *theModule, - char *logicalName) + const char *logicalName) { - char *ppform; + const char *ppform; ppform = EnvGetDefmodulePPForm(theEnv,theModule); if (ppform != NULL) @@ -131,7 +141,47 @@ globle void EnvGetDefmoduleList( void *theEnv, DATA_OBJECT_PTR returnValue) { - OldGetConstructList(theEnv,returnValue,EnvGetNextDefmodule,EnvGetDefmoduleName); + void *theConstruct; + unsigned long count = 0; + struct multifield *theList; + + /*====================================*/ + /* Determine the number of constructs */ + /* of the specified type. */ + /*====================================*/ + + for (theConstruct = EnvGetNextDefmodule(theEnv,NULL); + theConstruct != NULL; + theConstruct = EnvGetNextDefmodule(theEnv,theConstruct)) + { count++; } + + /*===========================*/ + /* Create a multifield large */ + /* enough to store the list. */ + /*===========================*/ + + SetpType(returnValue,MULTIFIELD); + SetpDOBegin(returnValue,1); + SetpDOEnd(returnValue,(long) count); + theList = (struct multifield *) EnvCreateMultifield(theEnv,count); + SetpValue(returnValue,(void *) theList); + + /*====================================*/ + /* Store the names in the multifield. */ + /*====================================*/ + + for (theConstruct = EnvGetNextDefmodule(theEnv,NULL), count = 1; + theConstruct != NULL; + theConstruct = EnvGetNextDefmodule(theEnv,theConstruct), count++) + { + if (EvaluationData(theEnv)->HaltExecution == TRUE) + { + EnvSetMultifieldErrorValue(theEnv,returnValue); + return; + } + SetMFType(theList,count,SYMBOL); + SetMFValue(theList,count,EnvAddSymbol(theEnv,EnvGetDefmoduleName(theEnv,theConstruct))); + } } #if DEBUGGING_FUNCTIONS @@ -143,7 +193,7 @@ globle void EnvGetDefmoduleList( globle void PPDefmoduleCommand( void *theEnv) { - char *defmoduleName; + const char *defmoduleName; defmoduleName = GetConstructName(theEnv,"ppdefmodule","defmodule name"); if (defmoduleName == NULL) return; @@ -159,8 +209,8 @@ globle void PPDefmoduleCommand( /*************************************/ globle int PPDefmodule( void *theEnv, - char *defmoduleName, - char *logicalName) + const char *defmoduleName, + const char *logicalName) { void *defmodulePtr; @@ -194,7 +244,7 @@ globle void ListDefmodulesCommand( /***************************************/ globle void EnvListDefmodules( void *theEnv, - char *logicalName) + const char *logicalName) { void *theModule; int count = 0; @@ -213,6 +263,30 @@ globle void EnvListDefmodules( #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void GetDefmoduleList( + DATA_OBJECT_PTR returnValue) + { + EnvGetDefmoduleList(GetCurrentEnvironment(),returnValue); + } + +#if DEBUGGING_FUNCTIONS + +globle void ListDefmodules( + const char *logicalName) + { + EnvListDefmodules(GetCurrentEnvironment(),logicalName); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFMODULE_CONSTRUCT */ diff --git a/src/modulbsc.h b/src/modulbsc.h index 4cee00c..7d9e6ca 100644 --- a/src/modulbsc.h +++ b/src/modulbsc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -15,10 +15,19 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_modulbsc @@ -38,20 +47,21 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetDefmoduleList(theEnv,a) EnvGetDefmoduleList(theEnv,a) -#define ListDefmodules(theEnv,a) EnvListDefmodules(theEnv,a) -#else -#define GetDefmoduleList(a) EnvGetDefmoduleList(GetCurrentEnvironment(),a) -#define ListDefmodules(a) EnvListDefmodules(GetCurrentEnvironment(),a) -#endif - LOCALE void DefmoduleBasicCommands(void *); LOCALE void EnvGetDefmoduleList(void *,DATA_OBJECT_PTR); LOCALE void PPDefmoduleCommand(void *); - LOCALE int PPDefmodule(void *,char *,char *); + LOCALE int PPDefmodule(void *,const char *,const char *); LOCALE void ListDefmodulesCommand(void *); - LOCALE void EnvListDefmodules(void *,char *); + LOCALE void EnvListDefmodules(void *,const char *); + +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE void GetDefmoduleList(DATA_OBJECT_PTR); +#if DEBUGGING_FUNCTIONS + LOCALE void ListDefmodules(const char *); #endif +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_modulbsc */ + diff --git a/src/modulcmp.c b/src/modulcmp.c index 4b2bbf2..22458ed 100644 --- a/src/modulcmp.c +++ b/src/modulcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -19,6 +19,16 @@ /* */ /* 6.24: Added environment parameter to GenClose. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _MODULCMP_SOURCE_ @@ -49,11 +59,11 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int ConstructToCode(void *,char *,int,FILE *,int,int); + static int ConstructToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void InitDefmoduleCode(void *,FILE *,int,int); static struct portItem *GetNextPortItem(void *,struct defmodule **,struct portItem **, int *,int *); - static int PortItemsToCode(void *,char *,int,FILE *,int,int,int *); + static int PortItemsToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int *); static void BeforeDefmodulesToCode(void *); /***************************************************************/ @@ -63,7 +73,7 @@ globle void DefmoduleCompilerSetup( void *theEnv) { - DefmoduleData(theEnv)->DefmoduleCodeItem = + DefmoduleData(theEnv)->DefmoduleCodeItem = AddCodeGeneratorItem(theEnv,"defmodule",200,BeforeDefmodulesToCode, InitDefmoduleCode,ConstructToCode,3); } @@ -104,16 +114,13 @@ globle void PrintDefmoduleReference( /* InitDefmoduleCode: Writes out initialization */ /* code for defmodules for a run-time module. */ /************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void InitDefmoduleCode( void *theEnv, FILE *initFP, int imageID, int maxIndices) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(maxIndices) #endif @@ -130,7 +137,9 @@ static void InitDefmoduleCode( /***********************************************************/ static int ConstructToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -158,7 +167,7 @@ static int ConstructToCode( /* the maximum number of indices is ignored. */ /*============================================*/ - if ((itemsFile = NewCFile(theEnv,fileName,fileID,1,FALSE)) == NULL) + if ((itemsFile = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,1,FALSE)) == NULL) { return(FALSE); } fprintf(itemsFile,"struct defmoduleItemHeader *%s%d_%d[] = {\n",ItemPrefix(),imageID,1); fprintf(headerFP,"extern struct defmoduleItemHeader *%s%d_%d[];\n",ItemPrefix(),imageID,1); @@ -176,7 +185,7 @@ static int ConstructToCode( /* Open a new file to write to if necessary. */ /*===========================================*/ - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID, &fileCount,moduleArrayVersion,headerFP, "struct defmodule",DefmodulePrefix(), FALSE,NULL); @@ -303,7 +312,7 @@ static int ConstructToCode( /*=========================================*/ if (portItemCount == 0) return(TRUE); - return(PortItemsToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,&fileCount)); + return(PortItemsToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,&fileCount)); } /************************************************************/ @@ -312,7 +321,9 @@ static int ConstructToCode( /************************************************************/ static int PortItemsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -340,7 +351,7 @@ static int PortItemsToCode( /* Open a new file to write to if necessary. */ /*===========================================*/ - portItemsFile = OpenFileIfNeeded(theEnv,portItemsFile,fileName,fileID,imageID, + portItemsFile = OpenFileIfNeeded(theEnv,portItemsFile,fileName,pathName,fileNameBuffer,fileID,imageID, fileCount,portItemArrayVersion,headerFP, "struct portItem",PortPrefix(), FALSE,NULL); diff --git a/src/modulcmp.h b/src/modulcmp.h index 5fb1e12..6230ef5 100644 --- a/src/modulcmp.h +++ b/src/modulcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -17,6 +17,18 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added environment parameter to GenClose. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_modulcmp @@ -45,4 +57,4 @@ LOCALE void DefmoduleCompilerSetup(void *); LOCALE void PrintDefmoduleReference(void *,FILE *,struct defmodule *); -#endif +#endif /* _H_modulcmp */ diff --git a/src/moduldef.c b/src/moduldef.c index 5e2ecf5..e0848fd 100644 --- a/src/moduldef.c +++ b/src/moduldef.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* DEFMODULE MODULE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Corrected compilation errors for files */ @@ -25,6 +26,17 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _MODULDEF_SOURCE_ @@ -90,28 +102,28 @@ static void DeallocateDefmoduleData( #endif #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) int i; - unsigned long space; + size_t space; #endif #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) for (i = 0; i < DefmoduleData(theEnv)->BNumberOfDefmodules; i++) { if (DefmoduleData(theEnv)->DefmoduleArray[i].itemsArray != NULL) - { + { rm(theEnv,DefmoduleData(theEnv)->DefmoduleArray[i].itemsArray, sizeof(void *) * GetNumberOfModuleItems(theEnv)); } } space = DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct defmodule); - if (space != 0) + if (space != 0) { - genlongfree(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray,space); + genfree(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray,space); DefmoduleData(theEnv)->ListOfDefmodules = NULL; } space = DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct portItem); - if (space != 0) genlongfree(theEnv,(void *) DefmoduleData(theEnv)->PortItemArray,space); + if (space != 0) genfree(theEnv,(void *) DefmoduleData(theEnv)->PortItemArray,space); #endif #if (! RUN_TIME) && (! BLOAD_ONLY) @@ -147,13 +159,13 @@ static void DeallocateDefmoduleData( rtn_struct(theEnv,moduleItem,tmpMIPtr); tmpMIPtr = nextMIPtr; } - + #if (! RUN_TIME) && (! BLOAD_ONLY) DeallocateCallList(theEnv,DefmoduleData(theEnv)->AfterModuleDefinedFunctions); #endif DeallocateCallList(theEnv,DefmoduleData(theEnv)->AfterModuleChangeFunctions); } - + /**************************************************************/ /* InitializeDefmodules: Initializes the defmodule construct. */ /**************************************************************/ @@ -188,12 +200,12 @@ globle void InitializeDefmodules( /******************************************************/ globle int RegisterModuleItem( void *theEnv, - char *theItem, + const char *theItem, void *(*allocateFunction)(void *), void (*freeFunction)(void *,void *), void *(*bloadModuleReference)(void *,int), void (*constructsToCModuleReference)(void *,FILE *,int,int,int), - void *(*findFunction)(void *,char *)) + void *(*findFunction)(void *,const char *)) { struct moduleItem *newModuleItem; @@ -245,7 +257,7 @@ globle int GetNumberOfModuleItems( /********************************************************/ globle struct moduleItem *FindModuleItem( void *theEnv, - char *theName) + const char *theName) { struct moduleItem *theModuleItem; @@ -272,9 +284,9 @@ globle void *EnvGetCurrentModule( /**************************************************************/ globle void *EnvSetCurrentModule( void *theEnv, - void *xNewValue) + void *vNewValue) { - struct defmodule *newValue = (struct defmodule *) xNewValue; + struct defmodule *newValue = (struct defmodule *) vNewValue; struct callFunctionItem *changeFunctions; void *rv; @@ -495,36 +507,30 @@ globle void *EnvGetNextDefmodule( /* EnvGetDefmoduleName: Returns the name */ /* of the specified defmodule. */ /*****************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetDefmoduleName( +globle const char *EnvGetDefmoduleName( void *theEnv, void *defmodulePtr) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(ValueToString(((struct defmodule *) defmodulePtr)->name)); + return(ValueToString(((struct defmodule *) defmodulePtr)->name)); } /***************************************************/ /* EnvGetDefmodulePPForm: Returns the pretty print */ /* representation of the specified defmodule. */ /***************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetDefmodulePPForm( +globle const char *EnvGetDefmodulePPForm( void *theEnv, void *defmodulePtr) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(((struct defmodule *) defmodulePtr)->ppForm); + return(((struct defmodule *) defmodulePtr)->ppForm); } #if (! RUN_TIME) @@ -567,7 +573,7 @@ static void ReturnDefmodule( /*=====================================================*/ if (theDefmodule == NULL) return; - + if (! environmentClear) { EnvSetCurrentModule(theEnv,(void *) theDefmodule); } @@ -644,13 +650,13 @@ static void ReturnDefmodule( rm(theEnv,theDefmodule->ppForm, (int) sizeof(char) * (strlen(theDefmodule->ppForm) + 1)); } - + /*=======================*/ /* Return the user data. */ /*=======================*/ ClearUserDataList(theEnv,theDefmodule->usrData); - + /*======================================*/ /* Return the defmodule data structure. */ /*======================================*/ @@ -666,7 +672,7 @@ static void ReturnDefmodule( /**********************************************************************/ globle void *EnvFindDefmodule( void *theEnv, - char *defmoduleName) + const char *defmoduleName) { struct defmodule *defmodulePtr; SYMBOL_HN *findValue; @@ -711,7 +717,7 @@ globle void *SetCurrentModuleCommand( void *theEnv) { DATA_OBJECT argPtr; - char *argument; + const char *argument; struct defmodule *theModule; SYMBOL_HN *defaultReturn; @@ -760,7 +766,7 @@ globle void *SetCurrentModuleCommand( /*************************************************/ globle void AddAfterModuleChangeFunction( void *theEnv, - char *name, + const char *name, void (*func)(void *), int priority) { @@ -779,4 +785,46 @@ globle void IllegalModuleSpecifierMessage( EnvPrintRouter(theEnv,WERROR,"Illegal use of the module specifier.\n"); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *FindDefmodule( + const char *defmoduleName) + { + return EnvFindDefmodule(GetCurrentEnvironment(),defmoduleName); + } + +globle void *GetCurrentModule() + { + return EnvGetCurrentModule(GetCurrentEnvironment()); + } + +globle const char *GetDefmoduleName( + void *defmodulePtr) + { + return EnvGetDefmoduleName(GetCurrentEnvironment(),defmodulePtr); + } + +globle const char *GetDefmodulePPForm( + void *defmodulePtr) + { + return EnvGetDefmodulePPForm(GetCurrentEnvironment(),defmodulePtr); + } + +globle void *GetNextDefmodule( + void *defmodulePtr) + { + return EnvGetNextDefmodule(GetCurrentEnvironment(),defmodulePtr); + } + +globle void *SetCurrentModule( + void *vNewValue) + { + return EnvSetCurrentModule(GetCurrentEnvironment(),vNewValue); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ diff --git a/src/moduldef.h b/src/moduldef.h index 54dbffa..0a62964 100644 --- a/src/moduldef.h +++ b/src/moduldef.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* DEFMODULE HEADER FILE */ /*******************************************************/ @@ -15,14 +15,28 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ -/* 6.23: Corrected compilation errors for files */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_moduldef @@ -139,13 +153,13 @@ struct defmoduleItemHeader struct moduleItem { - char *name; + const char *name; int moduleIndex; void *(*allocateFunction)(void *); void (*freeFunction)(void *,void *); void *(*bloadModuleReference)(void *,int); void (*constructsToCModuleReference)(void *,FILE *,int,int,int); - void *(*findFunction)(void *,char *); + void *(*findFunction)(void *,const char *); struct moduleItem *next; }; @@ -159,7 +173,7 @@ typedef struct moduleStackItem #define DEFMODULE_DATA 4 struct defmoduleData - { + { struct moduleItem *LastModuleItem; struct callFunctionItem *AfterModuleChangeFunctions; MODULE_STACK_ITEM *ModuleStack; @@ -186,7 +200,7 @@ struct defmoduleData struct defmodule *DefmoduleArray; #endif }; - + #define DefmoduleData(theEnv) ((struct defmoduleData *) GetEnvironmentData(theEnv,DEFMODULE_DATA)) #ifdef LOCALE @@ -199,35 +213,19 @@ struct defmoduleData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define FindDefmodule(theEnv,a) EnvFindDefmodule(theEnv,a) -#define GetCurrentModule(theEnv) EnvGetCurrentModule(theEnv) -#define GetDefmoduleName(theEnv,a) EnvGetDefmoduleName(theEnv,a) -#define GetDefmodulePPForm(theEnv,a) EnvGetDefmodulePPForm(theEnv,a) -#define GetNextDefmodule(theEnv,a) EnvGetNextDefmodule(theEnv,a) -#define SetCurrentModule(theEnv,a) EnvSetCurrentModule(theEnv,a) -#else -#define FindDefmodule(a) EnvFindDefmodule(GetCurrentEnvironment(),a) -#define GetCurrentModule() EnvGetCurrentModule(GetCurrentEnvironment()) -#define GetDefmoduleName(a) EnvGetDefmoduleName(GetCurrentEnvironment(),a) -#define GetDefmodulePPForm(a) EnvGetDefmodulePPForm(GetCurrentEnvironment(),a) -#define GetNextDefmodule(a) EnvGetNextDefmodule(GetCurrentEnvironment(),a) -#define SetCurrentModule(a) EnvSetCurrentModule(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeDefmodules(void *); - LOCALE void *EnvFindDefmodule(void *,char *); - LOCALE char *EnvGetDefmoduleName(void *,void *); - LOCALE char *EnvGetDefmodulePPForm(void *,void *); + LOCALE void *EnvFindDefmodule(void *,const char *); + LOCALE const char *EnvGetDefmoduleName(void *,void *); + LOCALE const char *EnvGetDefmodulePPForm(void *,void *); LOCALE void *EnvGetNextDefmodule(void *,void *); LOCALE void RemoveAllDefmodules(void *); LOCALE int AllocateModuleStorage(void); - LOCALE int RegisterModuleItem(void *,char *, + LOCALE int RegisterModuleItem(void *,const char *, void *(*)(void *), void (*)(void *,void *), void *(*)(void *,int), void (*)(void *,FILE *,int,int,int), - void *(*)(void *,char *)); + void *(*)(void *,const char *)); LOCALE void *GetModuleItem(void *,struct defmodule *,int); LOCALE void SetModuleItem(void *,struct defmodule *,int,void *); LOCALE void *EnvGetCurrentModule(void *); @@ -238,13 +236,24 @@ struct defmoduleData LOCALE void CreateMainModule(void *); LOCALE void SetListOfDefmodules(void *,void *); LOCALE struct moduleItem *GetListOfModuleItems(void *); - LOCALE struct moduleItem *FindModuleItem(void *,char *); + LOCALE struct moduleItem *FindModuleItem(void *,const char *); LOCALE void SaveCurrentModule(void *); LOCALE void RestoreCurrentModule(void *); - LOCALE void AddAfterModuleChangeFunction(void *,char *,void (*)(void *),int); + LOCALE void AddAfterModuleChangeFunction(void *,const char *,void (*)(void *),int); LOCALE void IllegalModuleSpecifierMessage(void *); LOCALE void AllocateDefmoduleGlobals(void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void *FindDefmodule(const char *); + LOCALE void *GetCurrentModule(void); + LOCALE const char *GetDefmoduleName(void *); + LOCALE const char *GetDefmodulePPForm(void *); + LOCALE void *GetNextDefmodule(void *); + LOCALE void *SetCurrentModule(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_moduldef */ diff --git a/src/modulpsr.c b/src/modulpsr.c index 1fa763a..deeef8f 100644 --- a/src/modulpsr.c +++ b/src/modulpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE PARSER MODULE */ /*******************************************************/ @@ -13,12 +13,20 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when DEFMODULE_CONSTRUCT */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #define _MODULPSR_SOURCE_ @@ -53,26 +61,16 @@ /***************************************/ static int ParsePortSpecifications(void *, - char *,struct token *, + const char *,struct token *, struct defmodule *); - static int ParseImportSpec(void *,char *,struct token *, + static int ParseImportSpec(void *,const char *,struct token *, struct defmodule *); - static int ParseExportSpec(void *,char *,struct token *, + static int ParseExportSpec(void *,const char *,struct token *, struct defmodule *, struct defmodule *); static intBool DeleteDefmodule(void *,void *); static int FindMultiImportConflict(void *,struct defmodule *); - static void NotExportedErrorMessage(void *,char *,char *,char *); - -/*********************************************/ -/* GetNumberOfDefmodules: Returns the number */ -/* of defmodules currently defined. */ -/*********************************************/ -globle long GetNumberOfDefmodules( - void *theEnv) - { - return(DefmoduleData(theEnv)->NumberOfDefmodules); - } + static void NotExportedErrorMessage(void *,const char *,const char *,const char *); /******************************************/ /* SetNumberOfDefmodules: Sets the number */ @@ -92,7 +90,7 @@ globle void SetNumberOfDefmodules( /****************************************************/ globle void AddAfterModuleDefinedFunction( void *theEnv, - char *name, + const char *name, void (*func)(void *), int priority) { @@ -106,7 +104,7 @@ globle void AddAfterModuleDefinedFunction( /******************************************************/ globle void AddPortConstructItem( void *theEnv, - char *theName, + const char *theName, int theType) { struct portConstructItem *newItem; @@ -125,7 +123,7 @@ globle void AddPortConstructItem( /******************************************************/ globle int ParseDefmodule( void *theEnv, - char *readSource) + const char *readSource) { SYMBOL_HN *defmoduleName; struct defmodule *newDefmodule; @@ -171,7 +169,7 @@ globle int ParseDefmodule( defmoduleName = GetConstructNameAndComment(theEnv,readSource,&inputToken,"defmodule", EnvFindDefmodule,DeleteDefmodule,"+", - TRUE,TRUE,FALSE); + TRUE,TRUE,FALSE,FALSE); if (defmoduleName == NULL) { return(TRUE); } if (strcmp(ValueToString(defmoduleName),"MAIN") == 0) @@ -376,7 +374,7 @@ static intBool DeleteDefmodule( /*********************************************************/ static int ParsePortSpecifications( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, struct defmodule *theDefmodule) { @@ -475,7 +473,7 @@ static int ParsePortSpecifications( /**********************************************************/ static int ParseImportSpec( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, struct defmodule *newModule) { @@ -636,7 +634,7 @@ static int ParseImportSpec( /**********************************************************/ static int ParseExportSpec( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, struct defmodule *newModule, struct defmodule *importModule) @@ -644,7 +642,7 @@ static int ParseExportSpec( struct portItem *newPort; SYMBOL_HN *theConstruct, *moduleName; struct portConstructItem *thePortConstruct; - char *errorMessage; + const char *errorMessage; /*===========================================*/ /* Set up some variables for error messages. */ @@ -914,7 +912,7 @@ static int ParseExportSpec( /*************************************************************/ globle struct portConstructItem *ValidPortConstructItem( void *theEnv, - char *theName) + const char *theName) { struct portConstructItem *theItem; @@ -1024,9 +1022,9 @@ static int FindMultiImportConflict( /******************************************************/ static void NotExportedErrorMessage( void *theEnv, - char *theModule, - char *theConstruct, - char *theName) + const char *theModule, + const char *theConstruct, + const char *theName) { PrintErrorID(theEnv,"MODULPSR",1,TRUE); EnvPrintRouter(theEnv,WERROR,"Module "); @@ -1060,9 +1058,9 @@ static void NotExportedErrorMessage( /*************************************************************/ globle int FindImportExportConflict( void *theEnv, - char *constructName, + const char *constructName, struct defmodule *matchModule, - char *findName) + const char *findName) { struct defmodule *theModule; struct moduleItem *theModuleItem; @@ -1131,4 +1129,18 @@ globle int FindImportExportConflict( #endif /* DEFMODULE_CONSTRUCT && (! RUN_TIME) && (! BLOAD_ONLY) */ +/*********************************************/ +/* GetNumberOfDefmodules: Returns the number */ +/* of defmodules currently defined. */ +/*********************************************/ +globle long GetNumberOfDefmodules( + void *theEnv) + { +#if DEFMODULE_CONSTRUCT && (! RUN_TIME) && (! BLOAD_ONLY) + return(DefmoduleData(theEnv)->NumberOfDefmodules); +#else + return 1L; +#endif + } + diff --git a/src/modulpsr.h b/src/modulpsr.h index 3318a2e..ed3c761 100644 --- a/src/modulpsr.h +++ b/src/modulpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE PARSER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,16 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: GetConstructNameAndComment API change. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when DEFMODULE_CONSTRUCT */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #ifndef _H_modulpsr @@ -23,7 +33,7 @@ struct portConstructItem { - char *constructName; + const char *constructName; int typeExpected; struct portConstructItem *next; }; @@ -50,12 +60,12 @@ struct portConstructItem LOCALE long GetNumberOfDefmodules(void *); LOCALE void SetNumberOfDefmodules(void *,long); - LOCALE void AddAfterModuleDefinedFunction(void *,char *,void (*)(void *),int); - LOCALE int ParseDefmodule(void *,char *); - LOCALE void AddPortConstructItem(void *,char *,int); - LOCALE struct portConstructItem *ValidPortConstructItem(void *,char *); - LOCALE int FindImportExportConflict(void *,char *,struct defmodule *,char *); + LOCALE void AddAfterModuleDefinedFunction(void *,const char *,void (*)(void *),int); + LOCALE int ParseDefmodule(void *,const char *); + LOCALE void AddPortConstructItem(void *,const char *,int); + LOCALE struct portConstructItem *ValidPortConstructItem(void *,const char *); + LOCALE int FindImportExportConflict(void *,const char *,struct defmodule *,const char *); -#endif +#endif /* _H_modulpsr */ diff --git a/src/modulutl.c b/src/modulutl.c index a4744cf..c070ed2 100644 --- a/src/modulutl.c +++ b/src/modulutl.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE UTILITY MODULE */ /*******************************************************/ @@ -15,10 +15,15 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Used genstrncpy instead of strncpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _MODULUTL_SOURCE_ @@ -28,6 +33,7 @@ #include "memalloc.h" #include "router.h" #include "envrnmnt.h" +#include "sysdep.h" #include "modulpsr.h" #include "modulutl.h" @@ -48,7 +54,7 @@ /* position of the second colon within the string is returned. */ /********************************************************************/ globle unsigned FindModuleSeparator( - char *theString) + const char *theString) { unsigned i, foundColon; @@ -75,7 +81,7 @@ globle unsigned FindModuleSeparator( globle SYMBOL_HN *ExtractModuleName( void *theEnv, unsigned thePosition, - char *theString) + const char *theString) { char *newString; SYMBOL_HN *returnValue; @@ -97,7 +103,7 @@ globle SYMBOL_HN *ExtractModuleName( /* Copy the entire module/construct name to the string. */ /*======================================================*/ - strncpy(newString,theString, + genstrncpy(newString,theString, (STD_SIZE) thePosition - 1); /*========================================================*/ @@ -135,7 +141,7 @@ globle SYMBOL_HN *ExtractModuleName( globle SYMBOL_HN *ExtractConstructName( void *theEnv, unsigned thePosition, - char *theString) + const char *theString) { size_t theLength; char *newString; @@ -173,7 +179,7 @@ globle SYMBOL_HN *ExtractConstructName( /* module/construct name to the temporary string. */ /*================================================*/ - strncpy(newString,&theString[thePosition+1], + genstrncpy(newString,&theString[thePosition+1], (STD_SIZE) theLength - thePosition); /*=============================================*/ @@ -200,9 +206,9 @@ globle SYMBOL_HN *ExtractConstructName( /* module and construct name from a string. Sets */ /* the current module to the specified module. */ /****************************************************/ -globle char *ExtractModuleAndConstructName( +globle const char *ExtractModuleAndConstructName( void *theEnv, - char *theName) + const char *theName) { unsigned separatorPosition; SYMBOL_HN *moduleName, *shortName; @@ -240,6 +246,7 @@ globle char *ExtractModuleAndConstructName( /*=============================*/ shortName = ExtractConstructName(theEnv,separatorPosition,theName); + if (shortName == NULL) return(NULL); return(ValueToString(shortName)); } @@ -250,9 +257,9 @@ globle char *ExtractModuleAndConstructName( /************************************************************/ globle void *FindImportedConstruct( void *theEnv, - char *constructName, + const char *constructName, struct defmodule *matchModule, - char *findName, + const char *findName, int *count, int searchCurrent, struct defmodule *notYetDefinedInModule) @@ -339,8 +346,8 @@ globle void *FindImportedConstruct( /*********************************************************/ globle void AmbiguousReferenceErrorMessage( void *theEnv, - char *constructName, - char *findName) + const char *constructName, + const char *findName) { EnvPrintRouter(theEnv,WERROR,"Ambiguous reference to "); EnvPrintRouter(theEnv,WERROR,constructName); @@ -538,23 +545,84 @@ static void *SearchImportedConstructModules( return(arv); } +/**************************************************************/ +/* ConstructExported: Returns TRUE if the specified construct */ +/* is exported from the specified module. */ +/**************************************************************/ +globle intBool ConstructExported( + void *theEnv, + const char *constructTypeStr, + struct symbolHashNode *moduleName, + struct symbolHashNode *findName) + { + struct symbolHashNode *constructType; + struct defmodule *theModule; + struct portItem *theExportList; + + constructType = FindSymbolHN(theEnv,constructTypeStr); + theModule = (struct defmodule *) EnvFindDefmodule(theEnv,ValueToString(moduleName)); + + if ((constructType == NULL) || (theModule == NULL) || (findName == NULL)) + { return(FALSE); } + + theExportList = theModule->exportList; + while (theExportList != NULL) + { + if ((theExportList->constructType == NULL) || + (theExportList->constructType == constructType)) + { + if ((theExportList->constructName == NULL) || + (theExportList->constructName == findName)) + { return TRUE; } + } + + theExportList = theExportList->next; + } + + return FALSE; + } + +/*********************************************************/ +/* AllImportedModulesVisited: Returns TRUE if all of the */ +/* imported modules for a module have been visited. */ +/*********************************************************/ +globle intBool AllImportedModulesVisited( + void *theEnv, + struct defmodule *theModule) + { + struct portItem *theImportList; + struct defmodule *theImportModule; + + theImportList = theModule->importList; + while (theImportList != NULL) + { + theImportModule = (struct defmodule *) EnvFindDefmodule(theEnv,ValueToString(theImportList->moduleName)); + + if (! theImportModule->visitedFlag) return FALSE; + + theImportList = theImportList->next; + } + + return TRUE; + } + /***************************************/ /* ListItemsDriver: Driver routine for */ /* listing items in a module. */ /***************************************/ globle void ListItemsDriver( void *theEnv, - char *logicalName, + const char *logicalName, struct defmodule *theModule, - char *singleName, - char *pluralName, + const char *singleName, + const char *pluralName, void *(*nextFunction)(void *,void *), - char *(*nameFunction)(void *), - void (*printFunction)(void *,char *,void *), + const char *(*nameFunction)(void *), + void (*printFunction)(void *,const char *,void *), int (*doItFunction)(void *,void *)) { void *constructPtr; - char *constructName; + const char *constructName; long count = 0; int allModules = FALSE; int doIt; diff --git a/src/modulutl.h b/src/modulutl.h index dbdb209..8745e19 100644 --- a/src/modulutl.h +++ b/src/modulutl.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFMODULE UTILITY HEADER FILE */ /*******************************************************/ @@ -15,10 +15,15 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Used genstrncpy instead of strncpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_modulutl @@ -41,26 +46,28 @@ #define LOCALE extern #endif - LOCALE unsigned FindModuleSeparator(char *); - LOCALE SYMBOL_HN *ExtractModuleName(void *,unsigned,char *); - LOCALE SYMBOL_HN *ExtractConstructName(void *,unsigned,char *); - LOCALE char *ExtractModuleAndConstructName(void *,char *); - LOCALE void *FindImportedConstruct(void *,char *,struct defmodule *, - char *,int *,int,struct defmodule *); - LOCALE void AmbiguousReferenceErrorMessage(void *,char *,char *); + LOCALE unsigned FindModuleSeparator(const char *); + LOCALE SYMBOL_HN *ExtractModuleName(void *,unsigned,const char *); + LOCALE SYMBOL_HN *ExtractConstructName(void *,unsigned,const char *); + LOCALE const char *ExtractModuleAndConstructName(void *,const char *); + LOCALE void *FindImportedConstruct(void *,const char *,struct defmodule *, + const char *,int *,int,struct defmodule *); + LOCALE void AmbiguousReferenceErrorMessage(void *,const char *,const char *); LOCALE void MarkModulesAsUnvisited(void *); + LOCALE intBool AllImportedModulesVisited(void *,struct defmodule *); LOCALE void ListItemsDriver(void *, - char *,struct defmodule *, - char *,char *, - void *(*)(void *,void *), - char *(*)(void *), - void (*)(void *,char *,void *), - int (*)(void *,void *)); + const char *,struct defmodule *, + const char *,const char *, + void *(*)(void *,void *), + const char *(*)(void *), + void (*)(void *,const char *,void *), + int (*)(void *,void *)); LOCALE long DoForAllModules(void *, void (*)(struct defmodule *,void *), int,void *); + LOCALE intBool ConstructExported(void *,const char *,struct symbolHashNode *,struct symbolHashNode *); -#endif +#endif /* _H_modulutl */ diff --git a/src/msgcom.c b/src/msgcom.c index e7a3e4b..64d71af 100644 --- a/src/msgcom.c +++ b/src/msgcom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* OBJECT MESSAGE COMMANDS */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable log to logName */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -25,6 +26,20 @@ /* Corrected code to remove run-time program */ /* compiler warnings. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added DeallocateMessageHandlerData to */ +/* deallocate message handler environment data. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ /* ========================================= @@ -46,6 +61,8 @@ #include "insfun.h" #include "insmoddp.h" #include "msgfun.h" +#include "msgpass.h" +#include "memalloc.h" #include "prccode.h" #include "router.h" @@ -80,22 +97,24 @@ static void CreateSystemHandlers(void *); #endif #if (! BLOAD_ONLY) && (! RUN_TIME) -static int WildDeleteHandler(void *,DEFCLASS *,SYMBOL_HN *,char *); +static int WildDeleteHandler(void *,DEFCLASS *,SYMBOL_HN *,const char *); #endif #if DEBUGGING_FUNCTIONS static unsigned DefmessageHandlerWatchAccess(void *,int,unsigned,EXPRESSION *); -static unsigned DefmessageHandlerWatchPrint(void *,char *,int,EXPRESSION *); -static unsigned DefmessageHandlerWatchSupport(void *,char *,char *,int, - void (*)(void *,char *,void *,unsigned), - void (*)(void *,int,void *,unsigned), +static unsigned DefmessageHandlerWatchPrint(void *,const char *,int,EXPRESSION *); +static unsigned DefmessageHandlerWatchSupport(void *,const char *,const char *,int, + void (*)(void *,const char *,void *,int), + void (*)(void *,int,void *,int), EXPRESSION *); -static unsigned WatchClassHandlers(void *,void *,char *,int,char *,int,int, - void (*)(void *,char *,void *,unsigned), - void (*)(void *,int,void *,unsigned)); -static void PrintHandlerWatchFlag(void *,char *,void *,unsigned); +static unsigned WatchClassHandlers(void *,void *,const char *,int,const char *,int,int, + void (*)(void *,const char *,void *,int), + void (*)(void *,int,void *,int)); +static void PrintHandlerWatchFlag(void *,const char *,void *,int); #endif +static void DeallocateMessageHandlerData(void *); + /* ========================================= ***************************************** EXTERNALLY VISIBLE FUNCTIONS @@ -123,17 +142,17 @@ globle void SetupMessageHandlers( PrintHandlerSlotGetFunction, PrintHandlerSlotGetFunction,NULL, HandlerSlotGetFunction, - NULL,NULL,NULL,NULL,NULL,NULL }, + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }, handlerPutInfo = { "HANDLER_PUT", HANDLER_PUT,0,1,1, PrintHandlerSlotPutFunction, PrintHandlerSlotPutFunction,NULL, HandlerSlotPutFunction, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; - AllocateEnvironmentData(theEnv,MESSAGE_HANDLER_DATA,sizeof(struct messageHandlerData),NULL); - memcpy(&MessageHandlerData(theEnv)->HandlerGetInfo,&handlerGetInfo,sizeof(struct entityRecord)); - memcpy(&MessageHandlerData(theEnv)->HandlerPutInfo,&handlerPutInfo,sizeof(struct entityRecord)); + AllocateEnvironmentData(theEnv,MESSAGE_HANDLER_DATA,sizeof(struct messageHandlerData),DeallocateMessageHandlerData); + memcpy(&MessageHandlerData(theEnv)->HandlerGetInfo,&handlerGetInfo,sizeof(struct entityRecord)); + memcpy(&MessageHandlerData(theEnv)->HandlerPutInfo,&handlerPutInfo,sizeof(struct entityRecord)); MessageHandlerData(theEnv)->hndquals[0] = "around"; MessageHandlerData(theEnv)->hndquals[1] = "before"; @@ -149,10 +168,10 @@ globle void SetupMessageHandlers( MessageHandlerData(theEnv)->DELETE_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,DELETE_STRING); IncrementSymbolCount(MessageHandlerData(theEnv)->DELETE_SYMBOL); - + MessageHandlerData(theEnv)->CREATE_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,CREATE_STRING); IncrementSymbolCount(MessageHandlerData(theEnv)->CREATE_SYMBOL); - + EnvAddClearFunction(theEnv,"defclass",CreateSystemHandlers,-100); #if ! BLOAD_ONLY @@ -199,6 +218,38 @@ globle void SetupMessageHandlers( #endif } +/*******************************************************/ +/* DeallocateMessageHandlerData: Deallocates environment */ +/* data for the message handler functionality. */ +/******************************************************/ +static void DeallocateMessageHandlerData( + void *theEnv) + { + HANDLER_LINK *tmp, *mhead, *chead; + + mhead = MessageHandlerData(theEnv)->TopOfCore; + while (mhead != NULL) + { + tmp = mhead; + mhead = mhead->nxt; + rtn_struct(theEnv,messageHandlerLink,tmp); + } + + chead = MessageHandlerData(theEnv)->OldCore; + while (chead != NULL) + { + mhead = chead; + chead = chead->nxtInStack; + + while (mhead != NULL) + { + tmp = mhead; + mhead = mhead->nxt; + rtn_struct(theEnv,messageHandlerLink,tmp); + } + } + } + /***************************************************** NAME : EnvGetDefmessageHandlerName DESCRIPTION : Gets the name of a message-handler @@ -209,15 +260,12 @@ globle void SetupMessageHandlers( SIDE EFFECTS : None NOTES : None *****************************************************/ -#if IBM_TBC -#pragma argsused -#endif -char *EnvGetDefmessageHandlerName( +globle const char *EnvGetDefmessageHandlerName( void *theEnv, void *ptr, - unsigned theIndex) + int theIndex) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -234,10 +282,10 @@ char *EnvGetDefmessageHandlerName( SIDE EFFECTS : None NOTES : None *****************************************************/ -globle char *EnvGetDefmessageHandlerType( +globle const char *EnvGetDefmessageHandlerType( void *theEnv, void *ptr, - unsigned theIndex) + int theIndex) { return(MessageHandlerData(theEnv)->hndquals[((DEFCLASS *) ptr)->handlers[theIndex-1].type]); } @@ -253,22 +301,19 @@ globle char *EnvGetDefmessageHandlerType( NOTES : If index == 0, the first handler array index (i.e. 1) returned **************************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle unsigned EnvGetNextDefmessageHandler( +globle int EnvGetNextDefmessageHandler( void *theEnv, void *ptr, - unsigned theIndex) + int theIndex) { DEFCLASS *cls; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif cls = (DEFCLASS *) ptr; if (theIndex == 0) - return((cls->handlers != NULL) ? 1U : 0U); + return((cls->handlers != NULL) ? 1 : 0); if (theIndex == cls->handlerCount) return(0); return(theIndex+1); @@ -286,7 +331,7 @@ globle unsigned EnvGetNextDefmessageHandler( *****************************************************/ globle HANDLER *GetDefmessageHandlerPointer( void *ptr, - unsigned theIndex) + int theIndex) { return(&((DEFCLASS *) ptr)->handlers[theIndex-1]); } @@ -304,15 +349,12 @@ globle HANDLER *GetDefmessageHandlerPointer( SIDE EFFECTS : None NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefmessageHandlerWatch( void *theEnv, void *theClass, - unsigned theIndex) + int theIndex) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -331,16 +373,13 @@ globle unsigned EnvGetDefmessageHandlerWatch( SIDE EFFECTS : Watch flag for the handler set NOTES : None *********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefmessageHandlerWatch( void *theEnv, int newState, void *theClass, - unsigned theIndex) + int theIndex) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -365,8 +404,8 @@ globle void EnvSetDefmessageHandlerWatch( globle unsigned EnvFindDefmessageHandler( void *theEnv, void *ptr, - char *hname, - char *htypestr) + const char *hname, + const char *htypestr) { unsigned htype; SYMBOL_HN *hsym; @@ -397,7 +436,7 @@ globle unsigned EnvFindDefmessageHandler( globle int EnvIsDefmessageHandlerDeletable( void *theEnv, void *ptr, - unsigned theIndex) + int theIndex) { DEFCLASS *cls; @@ -431,7 +470,7 @@ globle void UndefmessageHandlerCommand( EnvPrintRouter(theEnv,WERROR,"Unable to delete message-handlers.\n"); #else SYMBOL_HN *mname; - char *tname; + const char *tname; DATA_OBJECT tmp; DEFCLASS *cls; @@ -480,13 +519,8 @@ globle void UndefmessageHandlerCommand( globle int EnvUndefmessageHandler( void *theEnv, void *vptr, - unsigned mhi) + int mhi) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(vptr) -#pragma unused(mhi) -#endif - #if RUN_TIME || BLOAD_ONLY PrintErrorID(theEnv,"MSGCOM",3,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to delete message-handlers.\n"); @@ -541,7 +575,7 @@ globle void PPDefmessageHandlerCommand( { DATA_OBJECT temp; SYMBOL_HN *csym,*msym; - char *tname; + const char *tname; DEFCLASS *cls = NULL; unsigned mtype; HANDLER *hnd; @@ -653,15 +687,12 @@ globle void PreviewSendCommand( SIDE EFFECTS : None NOTES : None ********************************************************/ -#if IBM_TBC -#pragma argsused -#endif -globle char *EnvGetDefmessageHandlerPPForm( +globle const char *EnvGetDefmessageHandlerPPForm( void *theEnv, void *ptr, - unsigned theIndex) + int theIndex) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -681,7 +712,7 @@ globle char *EnvGetDefmessageHandlerPPForm( *******************************************************************/ globle void EnvListDefmessageHandlers( void *theEnv, - char *logName, + const char *logName, void *vptr, int inhp) { @@ -729,9 +760,9 @@ globle void EnvListDefmessageHandlers( ********************************************************************/ globle void EnvPreviewSend( void *theEnv, - char *logicalName, + const char *logicalName, void *clsptr, - char *msgname) + const char *msgname) { HANDLER_LINK *core; SYMBOL_HN *msym; @@ -760,11 +791,11 @@ globle void EnvPreviewSend( ****************************************************/ globle long DisplayHandlersInLinks( void *theEnv, - char *logName, + const char *logName, PACKED_CLASS_LINKS *plinks, - unsigned theIndex) + int theIndex) { - register unsigned i; + long i; long cnt; cnt = (long) plinks->classArray[theIndex]->handlerCount; @@ -829,7 +860,7 @@ static int WildDeleteHandler( void *theEnv, DEFCLASS *cls, SYMBOL_HN *msym, - char *tname) + const char *tname) { int mtype; @@ -875,24 +906,25 @@ static int WildDeleteHandler( SIDE EFFECTS : Watch flags set in specified classes NOTES : Accessory function for AddWatchItem() ******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefmessageHandlerWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif - return(DefmessageHandlerWatchSupport(theEnv,(char *) (newState ? "watch" : "unwatch"),NULL,(int) newState, + if (newState) + return(DefmessageHandlerWatchSupport(theEnv,"watch",NULL,newState, + NULL,EnvSetDefmessageHandlerWatch,argExprs)); + else + return(DefmessageHandlerWatchSupport(theEnv,"unwatch",NULL,newState, NULL,EnvSetDefmessageHandlerWatch,argExprs)); } /*********************************************************************** - NAME : DefclassWatchPrint + NAME : DefmessageHandlerWatchPrint DESCRIPTION : Parses a list of class names passed by AddWatchItem() and displays the traces accordingly INPUTS : 1) The logical name of the output @@ -905,16 +937,13 @@ static unsigned DefmessageHandlerWatchAccess( SIDE EFFECTS : Watch flags displayed for specified classes NOTES : Accessory function for AddWatchItem() ***********************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static unsigned DefmessageHandlerWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif return(DefmessageHandlerWatchSupport(theEnv,"list-watch-items",logName,-1, @@ -938,16 +967,16 @@ static unsigned DefmessageHandlerWatchPrint( *******************************************************/ static unsigned DefmessageHandlerWatchSupport( void *theEnv, - char *funcName, - char *logName, + const char *funcName, + const char *logName, int newState, - void (*printFunc)(void *,char *,void *,unsigned), - void (*traceFunc)(void *,int,void *,unsigned), + void (*printFunc)(void *,const char *,void *,int), + void (*traceFunc)(void *,int,void *,int), EXPRESSION *argExprs) { struct defmodule *theModule; void *theClass; - char *theHandlerStr; + const char *theHandlerStr; int theType; int argIndex = 2; DATA_OBJECT tmpData; @@ -1066,13 +1095,13 @@ static unsigned DefmessageHandlerWatchSupport( static unsigned WatchClassHandlers( void *theEnv, void *theClass, - char *theHandlerStr, + const char *theHandlerStr, int theType, - char *logName, + const char *logName, int newState, int indentp, - void (*printFunc)(void *,char *,void *,unsigned), - void (*traceFunc)(void *,int,void *,unsigned)) + void (*printFunc)(void *,const char *,void *,int), + void (*traceFunc)(void *,int,void *,int)) { unsigned theHandler; int found = FALSE; @@ -1116,18 +1145,116 @@ static unsigned WatchClassHandlers( ***************************************************/ static void PrintHandlerWatchFlag( void *theEnv, - char *logName, + const char *logName, void *theClass, - unsigned theHandler) + int theHandler) { EnvPrintRouter(theEnv,logName,EnvGetDefclassName(theEnv,theClass)); EnvPrintRouter(theEnv,logName," "); EnvPrintRouter(theEnv,logName,EnvGetDefmessageHandlerName(theEnv,theClass,theHandler)); EnvPrintRouter(theEnv,logName," "); EnvPrintRouter(theEnv,logName,EnvGetDefmessageHandlerType(theEnv,theClass,theHandler)); - EnvPrintRouter(theEnv,logName,(char *) (EnvGetDefmessageHandlerWatch(theEnv,theClass,theHandler) ? " = on\n" : " = off\n")); + + if (EnvGetDefmessageHandlerWatch(theEnv,theClass,theHandler)) + EnvPrintRouter(theEnv,logName," = on\n"); + else + EnvPrintRouter(theEnv,logName," = off\n"); } #endif /* DEBUGGING_FUNCTIONS */ -#endif + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle unsigned FindDefmessageHandler( + void *ptr, + const char *hname, + const char *htypestr) + { + return EnvFindDefmessageHandler(GetCurrentEnvironment(),ptr,hname,htypestr); + } + +globle const char *GetDefmessageHandlerName( + void *ptr, + int theIndex) + { + return EnvGetDefmessageHandlerName(GetCurrentEnvironment(),ptr,theIndex); + } + +globle const char *GetDefmessageHandlerType( + void *ptr, + int theIndex) + { + return EnvGetDefmessageHandlerType(GetCurrentEnvironment(),ptr,theIndex); + } + +globle int GetNextDefmessageHandler( + void *ptr, + int theIndex) + { + return EnvGetNextDefmessageHandler(GetCurrentEnvironment(),ptr,theIndex); + } + +globle int IsDefmessageHandlerDeletable( + void *ptr, + int theIndex) + { + return EnvIsDefmessageHandlerDeletable(GetCurrentEnvironment(),ptr,theIndex); + } + +globle int UndefmessageHandler( + void *vptr, + int mhi) + { + return EnvUndefmessageHandler(GetCurrentEnvironment(),vptr,mhi); + } + +#if DEBUGGING_FUNCTIONS + +globle const char *GetDefmessageHandlerPPForm( + void *ptr, + int theIndex) + { + return EnvGetDefmessageHandlerPPForm(GetCurrentEnvironment(),ptr,theIndex); + } + +globle unsigned GetDefmessageHandlerWatch( + void *theClass, + int theIndex) + { + return EnvGetDefmessageHandlerWatch(GetCurrentEnvironment(),theClass,theIndex); + } + +globle void ListDefmessageHandlers( + const char *logName, + void *vptr, + int inhp) + { + EnvListDefmessageHandlers(GetCurrentEnvironment(),logName,vptr,inhp); + } + +globle void PreviewSend( + const char *logicalName, + void *clsptr, + const char *msgname) + { + EnvPreviewSend(GetCurrentEnvironment(),logicalName,clsptr,msgname); + } + +globle void SetDefmessageHandlerWatch( + int newState, + void *theClass, + int theIndex) + { + EnvSetDefmessageHandlerWatch(GetCurrentEnvironment(),newState,theClass,theIndex); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* OBJECT_SYSTEM */ diff --git a/src/msgcom.h b/src/msgcom.h index 17b1250..8264afa 100644 --- a/src/msgcom.h +++ b/src/msgcom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,36 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS */ +/* compilation flag. */ +/* */ +/* Corrected code to remove run-time program */ +/* compiler warnings. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added DeallocateMessageHandlerData to */ +/* deallocate message handler environment data. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_msgcom @@ -32,7 +56,7 @@ #define MESSAGE_HANDLER_DATA 32 struct messageHandlerData - { + { ENTITY_RECORD HandlerGetInfo; ENTITY_RECORD HandlerPutInfo; SYMBOL_HN *INIT_SYMBOL; @@ -42,12 +66,13 @@ struct messageHandlerData unsigned WatchHandlers; unsigned WatchMessages; #endif - char *hndquals[4]; + const char *hndquals[4]; SYMBOL_HN *SELF_SYMBOL; SYMBOL_HN *CurrentMessageName; HANDLER_LINK *CurrentCore; HANDLER_LINK *TopOfCore; HANDLER_LINK *NextInCore; + HANDLER_LINK *OldCore; }; #define MessageHandlerData(theEnv) ((struct messageHandlerData *) GetEnvironmentData(theEnv,MESSAGE_HANDLER_DATA)) @@ -68,57 +93,48 @@ struct messageHandlerData #define PRINT_STRING "print" #define CREATE_STRING "create" -#if ENVIRONMENT_API_ONLY -#define FindDefmessageHandler(theEnv,a,b,c) EnvFindDefmessageHandler(theEnv,a,b,c) -#define GetDefmessageHandlerName(theEnv,a,b) EnvGetDefmessageHandlerName(theEnv,a,b) -#define GetDefmessageHandlerPPForm(theEnv,a,b) EnvGetDefmessageHandlerPPForm(theEnv,a,b) -#define GetDefmessageHandlerType(theEnv,a,b) EnvGetDefmessageHandlerType(theEnv,a,b) -#define GetDefmessageHandlerWatch(theEnv,a,b) EnvGetDefmessageHandlerWatch(theEnv,a,b) -#define GetNextDefmessageHandler(theEnv,a,b) EnvGetNextDefmessageHandler(theEnv,a,b) -#define IsDefmessageHandlerDeletable(theEnv,a,b) EnvIsDefmessageHandlerDeletable(theEnv,a,b) -#define ListDefmessageHandlers(theEnv,a,b,c) EnvListDefmessageHandler(theEnv,a,b,c) -#define PreviewSend(theEnv,a,b,c) EnvPreviewSend(theEnv,a,b,c) -#define SetDefmessageHandlerWatch(theEnv,a,b,c) EnvSetDefmessageHandlerWatch(theEnv,a,b,c) -#define UndefmessageHandler(theEnv,a,b) EnvUndefmessageHandler(theEnv,a,b) -#else -#define FindDefmessageHandler(a,b,c) EnvFindDefmessageHandler(GetCurrentEnvironment(),a,b,c) -#define GetDefmessageHandlerName(a,b) EnvGetDefmessageHandlerName(GetCurrentEnvironment(),a,b) -#define GetDefmessageHandlerPPForm(a,b) EnvGetDefmessageHandlerPPForm(GetCurrentEnvironment(),a,b) -#define GetDefmessageHandlerType(a,b) EnvGetDefmessageHandlerType(GetCurrentEnvironment(),a,b) -#define GetDefmessageHandlerWatch(a,b) EnvGetDefmessageHandlerWatch(GetCurrentEnvironment(),a,b) -#define GetNextDefmessageHandler(a,b) EnvGetNextDefmessageHandler(GetCurrentEnvironment(),a,b) -#define IsDefmessageHandlerDeletable(a,b) EnvIsDefmessageHandlerDeletable(GetCurrentEnvironment(),a,b) -#define ListDefmessageHandlers(a,b,c) EnvListDefmessageHandlers(GetCurrentEnvironment(),a,b,c) -#define PreviewSend(a,b,c) EnvPreviewSend(GetCurrentEnvironment(),a,b,c) -#define SetDefmessageHandlerWatch(a,b,c) EnvSetDefmessageHandlerWatch(GetCurrentEnvironment(),a,b,c) -#define UndefmessageHandler(a,b) EnvUndefmessageHandler(GetCurrentEnvironment(),a,b) -#endif - LOCALE void SetupMessageHandlers(void *); - LOCALE char *EnvGetDefmessageHandlerName(void *,void *,unsigned); - LOCALE char *EnvGetDefmessageHandlerType(void *,void *,unsigned); - LOCALE unsigned EnvGetNextDefmessageHandler(void *,void *,unsigned); - LOCALE HANDLER *GetDefmessageHandlerPointer(void *,unsigned); + LOCALE const char *EnvGetDefmessageHandlerName(void *,void *,int); + LOCALE const char *EnvGetDefmessageHandlerType(void *,void *,int); + LOCALE int EnvGetNextDefmessageHandler(void *,void *,int); + LOCALE HANDLER *GetDefmessageHandlerPointer(void *,int); #if DEBUGGING_FUNCTIONS - LOCALE unsigned EnvGetDefmessageHandlerWatch(void *,void *,unsigned); - LOCALE void EnvSetDefmessageHandlerWatch(void *,int,void *,unsigned); + LOCALE unsigned EnvGetDefmessageHandlerWatch(void *,void *,int); + LOCALE void EnvSetDefmessageHandlerWatch(void *,int,void *,int); #endif - LOCALE unsigned EnvFindDefmessageHandler(void *,void *,char *,char *); - LOCALE int EnvIsDefmessageHandlerDeletable(void *,void *,unsigned); + LOCALE unsigned EnvFindDefmessageHandler(void *,void *,const char *,const char *); + LOCALE int EnvIsDefmessageHandlerDeletable(void *,void *,int); LOCALE void UndefmessageHandlerCommand(void *); - LOCALE int EnvUndefmessageHandler(void *,void *,unsigned); - + LOCALE int EnvUndefmessageHandler(void *,void *,int); #if DEBUGGING_FUNCTIONS LOCALE void PPDefmessageHandlerCommand(void *); LOCALE void ListDefmessageHandlersCommand(void *); - LOCALE void PreviewSendCommand(void *); - LOCALE char *EnvGetDefmessageHandlerPPForm(void *,void *,unsigned); - LOCALE void EnvListDefmessageHandlers(void *,char *,void *,int); - LOCALE void EnvPreviewSend(void *,char *,void *,char *); - LOCALE long DisplayHandlersInLinks(void *,char *,PACKED_CLASS_LINKS *,unsigned); + LOCALE void PreviewSendCommand(void *); + LOCALE const char *EnvGetDefmessageHandlerPPForm(void *,void *,int); + LOCALE void EnvListDefmessageHandlers(void *,const char *,void *,int); + LOCALE void EnvPreviewSend(void *,const char *,void *,const char *); + LOCALE long DisplayHandlersInLinks(void *,const char *,PACKED_CLASS_LINKS *,int); #endif -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE unsigned FindDefmessageHandler(void *,const char *,const char *); + LOCALE const char *GetDefmessageHandlerName(void *,int); + LOCALE const char *GetDefmessageHandlerType(void *,int); + LOCALE int GetNextDefmessageHandler(void *,int); + LOCALE int IsDefmessageHandlerDeletable(void *,int); + LOCALE int UndefmessageHandler(void *,int); +#if DEBUGGING_FUNCTIONS + LOCALE const char *GetDefmessageHandlerPPForm(void *,int); + LOCALE unsigned GetDefmessageHandlerWatch(void *,int); + LOCALE void ListDefmessageHandlers(const char *,void *,int); + LOCALE void PreviewSend(const char *,void *,const char *); + LOCALE void SetDefmessageHandlerWatch(int,void *,int); +#endif /* DEBUGGING_FUNCTIONS */ + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_msgcom */ diff --git a/src/msgfun.c b/src/msgfun.c index abf7498..81a3930 100644 --- a/src/msgfun.c +++ b/src/msgfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* OBJECT MESSAGE FUNCTIONS */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable log to logName */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -24,6 +25,13 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -55,8 +63,8 @@ ***************************************** */ #if DEBUGGING_FUNCTIONS -static HANDLER_LINK *DisplayPrimaryCore(void *,char *,HANDLER_LINK *,int); -static void PrintPreviewHandler(void *,char *,HANDLER_LINK *,int,char *); +static HANDLER_LINK *DisplayPrimaryCore(void *,const char *,HANDLER_LINK *,int); +static void PrintPreviewHandler(void *,const char *,HANDLER_LINK *,int,const char *); #endif /* ========================================= @@ -92,7 +100,7 @@ globle void UnboundHandlerErr( *****************************************************************/ globle void PrintNoHandlerError( void *theEnv, - char *msg) + const char *msg) { PrintErrorID(theEnv,"MSGFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"No applicable primary message-handlers found for "); @@ -128,8 +136,11 @@ globle int CheckHandlerArgCount( EnvPrintRouter(theEnv,WERROR," in class "); EnvPrintRouter(theEnv,WERROR,EnvGetDefclassName(theEnv,(void *) hnd->cls)); EnvPrintRouter(theEnv,WERROR," expected "); - EnvPrintRouter(theEnv,WERROR,(char *) ((hnd->maxParams == -1) ? "at least " : "exactly ")); - PrintLongInteger(theEnv,WERROR,(long) (hnd->minParams-1)); + if (hnd->maxParams == -1) + EnvPrintRouter(theEnv,WERROR,"at least "); + else + EnvPrintRouter(theEnv,WERROR,"exactly "); + PrintLongInteger(theEnv,WERROR,(long long) (hnd->minParams-1)); EnvPrintRouter(theEnv,WERROR," argument(s).\n"); return(FALSE); } @@ -152,7 +163,7 @@ globle int CheckHandlerArgCount( ***************************************************/ globle void SlotAccessViolationError( void *theEnv, - char *slotName, + const char *slotName, intBool instanceFlag, void *theInstanceOrClass) { @@ -219,9 +230,9 @@ globle void SlotVisibilityViolationError( *******************************************************************************/ globle void NewSystemHandler( void *theEnv, - char *cname, - char *mname, - char *fname, + const char *cname, + const char *mname, + const char *fname, int extraargs) { DEFCLASS *cls; @@ -231,7 +242,7 @@ globle void NewSystemHandler( hnd = InsertHandlerHeader(theEnv,cls,(SYMBOL_HN *) EnvAddSymbol(theEnv,mname),MPRIMARY); IncrementSymbolCount(hnd->name); hnd->system = 1; - hnd->minParams = hnd->maxParams = extraargs + 1; + hnd->minParams = hnd->maxParams = (short) (extraargs + 1); hnd->localVarCount = 0; hnd->actions = get_struct(theEnv,expr); hnd->actions->argList = NULL; @@ -262,8 +273,8 @@ globle HANDLER *InsertHandlerHeader( { HANDLER *nhnd,*hnd; unsigned *narr,*arr; - unsigned i; - register int j,ni = -1; + long i; + long j,ni = -1; hnd = cls->handlers; arr = cls->handlerOrderMap; @@ -277,7 +288,7 @@ globle HANDLER *InsertHandlerHeader( if ((hnd[arr[i]].name->bucket > mname->bucket) ? TRUE : (hnd[arr[i]].name == mname)) { - ni = (int) i; + ni = i; j++; } } @@ -329,7 +340,7 @@ globle HANDLER *InsertHandlerHeader( globle int HandlersExecuting( DEFCLASS *cls) { - register unsigned i; + long i; for (i = 0 ; i < cls->handlerCount ; i++) if (cls->handlers[i].busy > 0) @@ -364,7 +375,7 @@ globle int DeleteHandler( int mtype, int indicate_missing) { - register unsigned i; + long i; HANDLER *hnd; int found,success = 1; @@ -459,10 +470,10 @@ globle void DeallocateMarkedHandlers( void *theEnv, DEFCLASS *cls) { - unsigned count; + short count; HANDLER *hnd,*nhnd; unsigned *arr,*narr; - register unsigned i,j; + long i,j; for (i = 0 , count = 0 ; i < cls->handlerCount ; i++) { @@ -497,7 +508,7 @@ globle void DeallocateMarkedHandlers( } else { - count = cls->handlerCount - count; + count = (short) (cls->handlerCount - count); hnd = cls->handlers; arr = cls->handlerOrderMap; nhnd = (HANDLER *) gm2(theEnv,(sizeof(HANDLER) * count)); @@ -549,8 +560,8 @@ globle void DeallocateMarkedHandlers( *****************************************************/ globle unsigned HandlerType( void *theEnv, - char *func, - char *str) + const char *func, + const char *str) { register unsigned i; @@ -581,7 +592,7 @@ globle unsigned HandlerType( *****************************************************************/ globle int CheckCurrentMessage( void *theEnv, - char *func, + const char *func, int ins_reqd) { register DATA_OBJECT *activeMsgArg; @@ -626,7 +637,7 @@ globle int CheckCurrentMessage( ***************************************************/ globle void PrintHandler( void *theEnv, - char *logName, + const char *logName, HANDLER *theHandler, int crtn) { @@ -657,7 +668,7 @@ globle HANDLER *FindHandlerByAddress( unsigned type) { register int b; - unsigned i; + long i; HANDLER *hnd; unsigned *arr; @@ -676,7 +687,7 @@ globle HANDLER *FindHandlerByAddress( } /*********************************************************** - NAME : FindHandlerByAddress + NAME : FindHandlerByIndex DESCRIPTION : Uses a binary search on a class's handler header array INPUTS : 1) The class address @@ -695,7 +706,7 @@ globle int FindHandlerByIndex( unsigned type) { register int b; - unsigned i; + long i; HANDLER *hnd; unsigned *arr; @@ -784,7 +795,7 @@ globle int FindHandlerNameGroup( ***************************************************/ globle void HandlerDeleteError( void *theEnv, - char *cname) + const char *cname) { PrintErrorID(theEnv,"MSGFUN",8,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to delete message-handler(s) from class "); @@ -815,7 +826,7 @@ globle void HandlerDeleteError( ********************************************************************/ globle void DisplayCore( void *theEnv, - char *logicalName, + const char *logicalName, HANDLER_LINK *core, int sdepth) { @@ -888,15 +899,15 @@ globle HANDLER_LINK *FindPreviewApplicableHandlers( ***********************************************************/ globle void WatchMessage( void *theEnv, - char *logName, - char *tstring) + const char *logName, + const char *tstring) { EnvPrintRouter(theEnv,logName,"MSG "); EnvPrintRouter(theEnv,logName,tstring); EnvPrintRouter(theEnv,logName," "); EnvPrintRouter(theEnv,logName,ValueToString(MessageHandlerData(theEnv)->CurrentMessageName)); EnvPrintRouter(theEnv,logName," ED:"); - PrintLongInteger(theEnv,logName,(long) EvaluationData(theEnv)->CurrentEvaluationDepth); + PrintLongInteger(theEnv,logName,(long long) EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,logName); } @@ -914,19 +925,19 @@ globle void WatchMessage( ***********************************************************/ globle void WatchHandler( void *theEnv, - char *logName, + const char *logName, HANDLER_LINK *hndl, - char *tstring) + const char *tstring) { HANDLER *hnd; - + EnvPrintRouter(theEnv,logName,"HND "); EnvPrintRouter(theEnv,logName,tstring); EnvPrintRouter(theEnv,logName," "); hnd = hndl->hnd; PrintHandler(theEnv,WTRACE,hnd,TRUE); EnvPrintRouter(theEnv,logName," ED:"); - PrintLongInteger(theEnv,logName,(long) EvaluationData(theEnv)->CurrentEvaluationDepth); + PrintLongInteger(theEnv,logName,(long long) EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,logName); } @@ -961,7 +972,7 @@ globle void WatchHandler( ********************************************************************/ static HANDLER_LINK *DisplayPrimaryCore( void *theEnv, - char *logicalName, + const char *logicalName, HANDLER_LINK *core, int pdepth) { @@ -989,10 +1000,10 @@ static HANDLER_LINK *DisplayPrimaryCore( ***************************************************/ static void PrintPreviewHandler( void *theEnv, - char *logicalName, + const char *logicalName, HANDLER_LINK *cptr, int sdepth, - char *tstr) + const char *tstr) { register int i; diff --git a/src/msgfun.h b/src/msgfun.h index e491b0c..f744503 100644 --- a/src/msgfun.h +++ b/src/msgfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,13 +10,27 @@ /* Purpose: Message-passing support functions */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.23: Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS and */ +/* AUXILIARY_MESSAGE_HANDLERS compilation flags. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ /* */ /*************************************************************/ @@ -25,8 +39,8 @@ typedef struct handlerSlotReference { - unsigned short classID; - unsigned slotID; + long classID; + long slotID; } HANDLER_SLOT_REFERENCE; #ifndef _H_object @@ -60,13 +74,13 @@ typedef struct handlerSlotReference #endif LOCALE void UnboundHandlerErr(void *); - LOCALE void PrintNoHandlerError(void *,char *); + LOCALE void PrintNoHandlerError(void *,const char *); LOCALE int CheckHandlerArgCount(void *); - LOCALE void SlotAccessViolationError(void *,char *,intBool,void *); + LOCALE void SlotAccessViolationError(void *,const char *,intBool,void *); LOCALE void SlotVisibilityViolationError(void *,SLOT_DESC *,DEFCLASS *); #if ! RUN_TIME - LOCALE void NewSystemHandler(void *,char *,char *,char *,int); + LOCALE void NewSystemHandler(void *,const char *,const char *,const char *,int); LOCALE HANDLER *InsertHandlerHeader(void *,DEFCLASS *,SYMBOL_HN *,int); #endif @@ -76,22 +90,22 @@ typedef struct handlerSlotReference LOCALE int DeleteHandler(void *,DEFCLASS *,SYMBOL_HN *,int,int); LOCALE void DeallocateMarkedHandlers(void *,DEFCLASS *); #endif - LOCALE unsigned HandlerType(void *,char *,char *); - LOCALE int CheckCurrentMessage(void *,char *,int); - LOCALE void PrintHandler(void *,char *,HANDLER *,int); + LOCALE unsigned HandlerType(void *,const char *,const char *); + LOCALE int CheckCurrentMessage(void *,const char *,int); + LOCALE void PrintHandler(void *,const char *,HANDLER *,int); LOCALE HANDLER *FindHandlerByAddress(DEFCLASS *,SYMBOL_HN *,unsigned); LOCALE int FindHandlerByIndex(DEFCLASS *,SYMBOL_HN *,unsigned); LOCALE int FindHandlerNameGroup(DEFCLASS *,SYMBOL_HN *); - LOCALE void HandlerDeleteError(void *,char *); + LOCALE void HandlerDeleteError(void *,const char *); #if DEBUGGING_FUNCTIONS - LOCALE void DisplayCore(void *,char *,HANDLER_LINK *,int); + LOCALE void DisplayCore(void *,const char *,HANDLER_LINK *,int); LOCALE HANDLER_LINK *FindPreviewApplicableHandlers(void *,DEFCLASS *,SYMBOL_HN *); - LOCALE void WatchMessage(void *,char *,char *); - LOCALE void WatchHandler(void *,char *,HANDLER_LINK *,char *); + LOCALE void WatchMessage(void *,const char *,const char *); + LOCALE void WatchHandler(void *,const char *,HANDLER_LINK *,const char *); #endif -#endif +#endif /* _H_msgfun */ diff --git a/src/msgpass.c b/src/msgpass.c index 3a8a2ba..34bdb0d 100644 --- a/src/msgpass.c +++ b/src/msgpass.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 01/13/15 */ /* */ /* OBJECT MESSAGE DISPATCH CODE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS and */ @@ -22,6 +23,24 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: The return value of DirectMessage indicates */ +/* whether an execution error has occurred. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* It's no longer necessary for a defclass to be */ +/* in scope in order to sent a message to an */ +/* instance of that class. */ +/* */ /*************************************************************/ /* ========================================= @@ -69,7 +88,7 @@ ========================================= ***************************************** */ -static void PerformMessage(void *,DATA_OBJECT *,EXPRESSION *,SYMBOL_HN *); +static intBool PerformMessage(void *,DATA_OBJECT *,EXPRESSION *,SYMBOL_HN *); static HANDLER_LINK *FindApplicableHandlers(void *,DEFCLASS *,SYMBOL_HN *); static void CallHandlers(void *,DATA_OBJECT *); static void EarlySlotBindError(void *,INSTANCE_TYPE *,DEFCLASS *,unsigned); @@ -89,11 +108,12 @@ static void EarlySlotBindError(void *,INSTANCE_TYPE *,DEFCLASS *,unsigned); 3) Address of DATA_OBJECT buffer (NULL if don't care) 4) Message argument expressions - RETURNS : Nothing useful + RETURNS : Returns FALSE is an execution error occurred + or execution is halted, otherwise TRUE SIDE EFFECTS : Side effects of message execution NOTES : None *****************************************************/ -globle void DirectMessage( +globle intBool DirectMessage( void *theEnv, SYMBOL_HN *msg, INSTANCE_TYPE *ins, @@ -109,7 +129,7 @@ globle void DirectMessage( args.argList = NULL; args.type = INSTANCE_ADDRESS; args.value = (void *) ins; - PerformMessage(theEnv,resultbuf,&args,msg); + return PerformMessage(theEnv,resultbuf,&args,msg); } /*************************************************** @@ -129,17 +149,20 @@ globle void DirectMessage( globle void EnvSend( void *theEnv, DATA_OBJECT *idata, - char *msg, - char *args, + const char *msg, + const char *args, DATA_OBJECT *result) { int error; EXPRESSION *iexp; SYMBOL_HN *msym; - if ((EvaluationData(theEnv)->CurrentEvaluationDepth == 0) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && - (EvaluationData(theEnv)->CurrentExpression == NULL)) - { PeriodicCleanup(theEnv,TRUE,FALSE); } + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } SetEvaluationError(theEnv,FALSE); result->type = SYMBOL; @@ -526,12 +549,9 @@ globle HANDLER_LINK *JoinHandlerLinks( SIDE EFFECTS : Expression printed NOTES : None ***************************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintHandlerSlotGetFunction( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -547,7 +567,7 @@ globle void PrintHandlerSlotGetFunction( sd = theDefclass->instanceTemplate[theDefclass->slotNameMap[theReference->slotID] - 1]; EnvPrintRouter(theEnv,logicalName,ValueToString(sd->slotName->name)); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -649,12 +669,9 @@ HandlerGetError: SIDE EFFECTS : Expression printed NOTES : None ***************************************************/ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif globle void PrintHandlerSlotPutFunction( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -676,7 +693,7 @@ globle void PrintHandlerSlotPutFunction( } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -929,31 +946,41 @@ globle void DynamicHandlerPutSlot( 2) Message argument expressions (including implicit object) 3) Message name - RETURNS : Nothing useful + RETURNS : Returns FALSE is an execution error occurred + or execution is halted, otherwise TRUE SIDE EFFECTS : Any side-effects of message execution and caller's result buffer set - NOTES : None + NOTES : It's no longer necessary for a defclass + to be in scope in order to sent a message + to an instance of that class. *****************************************************/ -static void PerformMessage( +static intBool PerformMessage( void *theEnv, DATA_OBJECT *result, EXPRESSION *args, SYMBOL_HN *mname) { int oldce; - HANDLER_LINK *oldCore; + /* HANDLER_LINK *oldCore; */ DEFCLASS *cls = NULL; INSTANCE_TYPE *ins = NULL; SYMBOL_HN *oldName; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; #endif + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); EvaluationData(theEnv)->EvaluationError = FALSE; if (EvaluationData(theEnv)->HaltExecution) - return; + return FALSE; + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + oldce = ExecutingConstruct(theEnv); SetExecutingConstruct(theEnv,TRUE); oldName = MessageHandlerData(theEnv)->CurrentMessageName; @@ -969,9 +996,12 @@ static void PerformMessage( { EvaluationData(theEnv)->CurrentEvaluationDepth--; MessageHandlerData(theEnv)->CurrentMessageName = oldName; - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); - return; + return FALSE; } if (ProceduralPrimitiveData(theEnv)->ProcParamArray->type == INSTANCE_ADDRESS) @@ -982,8 +1012,8 @@ static void PerformMessage( StaleInstanceAddress(theEnv,"send",0); SetEvaluationError(theEnv,TRUE); } - else if (DefclassInScope(theEnv,ins->cls,(struct defmodule *) EnvGetCurrentModule(theEnv)) == FALSE) - NoInstanceError(theEnv,ValueToString(ins->name),"send"); + //else if (DefclassInScope(theEnv,ins->cls,(struct defmodule *) EnvGetCurrentModule(theEnv)) == FALSE) + // NoInstanceError(theEnv,ValueToString(ins->name),"send"); else { cls = ins->cls; @@ -1019,12 +1049,20 @@ static void PerformMessage( PopProcParameters(theEnv); EvaluationData(theEnv)->CurrentEvaluationDepth--; MessageHandlerData(theEnv)->CurrentMessageName = oldName; - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); - return; + return FALSE; } - oldCore = MessageHandlerData(theEnv)->TopOfCore; + /* oldCore = MessageHandlerData(theEnv)->TopOfCore; */ + + if (MessageHandlerData(theEnv)->TopOfCore != NULL) + { MessageHandlerData(theEnv)->TopOfCore->nxtInStack = MessageHandlerData(theEnv)->OldCore; } + MessageHandlerData(theEnv)->OldCore = MessageHandlerData(theEnv)->TopOfCore; + MessageHandlerData(theEnv)->TopOfCore = FindApplicableHandlers(theEnv,cls,mname); if (MessageHandlerData(theEnv)->TopOfCore != NULL) @@ -1091,7 +1129,11 @@ static void PerformMessage( MessageHandlerData(theEnv)->NextInCore = oldNext; } - MessageHandlerData(theEnv)->TopOfCore = oldCore; + /* MessageHandlerData(theEnv)->TopOfCore = oldCore; */ + MessageHandlerData(theEnv)->TopOfCore = MessageHandlerData(theEnv)->OldCore; + if (MessageHandlerData(theEnv)->OldCore != NULL) + { MessageHandlerData(theEnv)->OldCore = MessageHandlerData(theEnv)->OldCore->nxtInStack; } + ProcedureFunctionData(theEnv)->ReturnFlag = FALSE; if (ins != NULL) @@ -1103,15 +1145,20 @@ static void PerformMessage( PopProcParameters(theEnv); EvaluationData(theEnv)->CurrentEvaluationDepth--; MessageHandlerData(theEnv)->CurrentMessageName = oldName; - PropagateReturnValue(theEnv,result); - PeriodicCleanup(theEnv,FALSE,TRUE); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); + SetExecutingConstruct(theEnv,oldce); if (EvaluationData(theEnv)->EvaluationError) { result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); + return FALSE; } + + return TRUE; } /***************************************************************************** @@ -1175,11 +1222,7 @@ static void CallHandlers( void *theEnv, DATA_OBJECT *result) { -#if IBM_TBC - HANDLER_LINK *oldCurrent,*oldNext; /* prevents warning */ -#else HANDLER_LINK *oldCurrent = NULL,*oldNext = NULL; /* prevents warning */ -#endif DATA_OBJECT temp; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; @@ -1361,5 +1404,22 @@ static void EarlySlotBindError( PrintInstanceNameAndClass(theEnv,WERROR,theInstance,TRUE); } -#endif +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void Send( + DATA_OBJECT *idata, + const char *msg, + const char *args, + DATA_OBJECT *result) + { + EnvSend(GetCurrentEnvironment(),idata,msg,args,result); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* OBJECT_SYSTEM */ diff --git a/src/msgpass.h b/src/msgpass.h index 616d051..fe33ac8 100644 --- a/src/msgpass.h +++ b/src/msgpass.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,17 +10,33 @@ /* Purpose: Message-passing support functions */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS */ -/* compilation flag. */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS and */ +/* AUXILIARY_MESSAGE_HANDLERS compilation flags. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: The return value of DirectMessage indicates */ +/* whether an execution error has occurred. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_msgpass @@ -36,6 +52,7 @@ typedef struct messageHandlerLink { HANDLER *hnd; struct messageHandlerLink *nxt; + struct messageHandlerLink *nxtInStack; } HANDLER_LINK; #ifdef LOCALE @@ -48,15 +65,9 @@ typedef struct messageHandlerLink #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Send(theEnv,a,b,c,d) EnvSend(theEnv,a,b,c,d) -#else -#define Send(a,b,c,d) EnvSend(GetCurrentEnvironment(),a,b,c,d) -#endif - - LOCALE void DirectMessage(void *,SYMBOL_HN *,INSTANCE_TYPE *, + LOCALE intBool DirectMessage(void *,SYMBOL_HN *,INSTANCE_TYPE *, DATA_OBJECT *,EXPRESSION *); - LOCALE void EnvSend(void *,DATA_OBJECT *,char *,char *,DATA_OBJECT *); + LOCALE void EnvSend(void *,DATA_OBJECT *,const char *,const char *,DATA_OBJECT *); LOCALE void DestroyHandlerLinks(void *,HANDLER_LINK *); LOCALE void SendCommand(void *,DATA_OBJECT *); LOCALE DATA_OBJECT *GetNthMessageArgument(void *,int); @@ -68,14 +79,20 @@ typedef struct messageHandlerLink HANDLER_LINK *[],SYMBOL_HN *); LOCALE HANDLER_LINK *JoinHandlerLinks(void *,HANDLER_LINK *[],HANDLER_LINK *[],SYMBOL_HN *); - LOCALE void PrintHandlerSlotGetFunction(void *,char *,void *); + LOCALE void PrintHandlerSlotGetFunction(void *,const char *,void *); LOCALE intBool HandlerSlotGetFunction(void *,void *,DATA_OBJECT *); - LOCALE void PrintHandlerSlotPutFunction(void *,char *,void *); + LOCALE void PrintHandlerSlotPutFunction(void *,const char *,void *); LOCALE intBool HandlerSlotPutFunction(void *,void *,DATA_OBJECT *); LOCALE void DynamicHandlerGetSlot(void *,DATA_OBJECT *); LOCALE void DynamicHandlerPutSlot(void *,DATA_OBJECT *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void Send(DATA_OBJECT *,const char *,const char *,DATA_OBJECT *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_object */ diff --git a/src/msgpsr.c b/src/msgpsr.c index 3002a37..fe91f5e 100644 --- a/src/msgpsr.c +++ b/src/msgpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* MESSAGE-HANDLER PARSER FUNCTIONS */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -22,7 +23,19 @@ /* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS */ /* compilation flag. */ /* */ -/* Renamed BOOLEAN macro type to intBool. */ +/* 6.30: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_AND_SAVE */ +/* compiler flag is set to 0. */ /* */ /*************************************************************/ @@ -57,6 +70,7 @@ #include "router.h" #include "scanner.h" #include "strngrtr.h" +#include "sysdep.h" #define _MSGPSR_SOURCE_ #include "msgpsr.h" @@ -75,7 +89,7 @@ ========================================= ***************************************** */ -static intBool IsParameterSlotReference(void *,char *); +static intBool IsParameterSlotReference(void *,const char *); static int SlotReferenceVar(void *,EXPRESSION *,void *); static int BindSlotReference(void *,EXPRESSION *,void *); static SLOT_DESC *CheckSlotReference(void *,DEFCLASS *,int,void *,intBool,EXPRESSION *); @@ -103,7 +117,7 @@ static void GenHandlerSlotReference(void *,EXPRESSION *,unsigned short,SLOT_DESC ***********************************************************************/ globle int ParseDefmessageHandler( void *theEnv, - char *readSource) + const char *readSource) { DEFCLASS *cls; SYMBOL_HN *cname,*mname,*wildcard; @@ -125,7 +139,7 @@ globle int ParseDefmessageHandler( } #endif cname = GetConstructNameAndComment(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken,"defmessage-handler", - NULL,NULL,"~",TRUE,FALSE,TRUE); + NULL,NULL,"~",TRUE,FALSE,TRUE,FALSE); if (cname == NULL) return(TRUE); cls = LookupDefclassByMdlOrScope(theEnv,ValueToString(cname)); @@ -203,7 +217,10 @@ globle int ParseDefmessageHandler( EnvPrintRouter(theEnv,WDIALOG,ValueToString(mname)); EnvPrintRouter(theEnv,WDIALOG," "); EnvPrintRouter(theEnv,WDIALOG,MessageHandlerData(theEnv)->hndquals[mtype]); - EnvPrintRouter(theEnv,WDIALOG,(char *) ((hnd == NULL) ? " defined.\n" : " redefined.\n")); + if (hnd == NULL) + EnvPrintRouter(theEnv,WDIALOG," defined.\n"); + else + EnvPrintRouter(theEnv,WDIALOG," redefined.\n"); } if ((hnd != NULL) ? hnd->system : FALSE) @@ -268,9 +285,9 @@ globle int ParseDefmessageHandler( } ReturnExpression(theEnv,hndParams); - hnd->minParams = min; - hnd->maxParams = max; - hnd->localVarCount = lvars; + hnd->minParams = (short) min; + hnd->maxParams = (short) max; + hnd->localVarCount = (short) lvars; hnd->actions = actions; ExpressionInstall(theEnv,hnd->actions); #if DEBUGGING_FUNCTIONS @@ -313,11 +330,12 @@ globle void CreateGetAndPutHandlers( void *theEnv, SLOT_DESC *sd) { - char *className,*slotName; - unsigned bufsz; - char *buf,*handlerRouter = "*** Default Public Handlers ***"; + const char *className,*slotName; + size_t bufsz; + char *buf; + const char *handlerRouter = "*** Default Public Handlers ***"; int oldPWL,oldCM; - char *oldRouter; + const char *oldRouter; char *oldString; long oldIndex; @@ -335,16 +353,16 @@ globle void CreateGetAndPutHandlers( if (sd->createReadAccessor) { - sprintf(buf,"%s get-%s () ?self:%s)",className,slotName,slotName); - + gensprintf(buf,"%s get-%s () ?self:%s)",className,slotName,slotName); + oldRouter = RouterData(theEnv)->FastCharGetRouter; oldString = RouterData(theEnv)->FastCharGetString; oldIndex = RouterData(theEnv)->FastCharGetIndex; - + RouterData(theEnv)->FastCharGetRouter = handlerRouter; RouterData(theEnv)->FastCharGetIndex = 0; RouterData(theEnv)->FastCharGetString = buf; - + ParseDefmessageHandler(theEnv,handlerRouter); DestroyPPBuffer(theEnv); /* @@ -362,28 +380,28 @@ globle void CreateGetAndPutHandlers( if (sd->createWriteAccessor) { - sprintf(buf,"%s put-%s ($?value) (bind ?self:%s ?value))", + gensprintf(buf,"%s put-%s ($?value) (bind ?self:%s ?value))", className,slotName,slotName); - + oldRouter = RouterData(theEnv)->FastCharGetRouter; oldString = RouterData(theEnv)->FastCharGetString; oldIndex = RouterData(theEnv)->FastCharGetIndex; - + RouterData(theEnv)->FastCharGetRouter = handlerRouter; RouterData(theEnv)->FastCharGetIndex = 0; RouterData(theEnv)->FastCharGetString = buf; - + ParseDefmessageHandler(theEnv,handlerRouter); DestroyPPBuffer(theEnv); -/* +/* if (OpenStringSource(theEnv,handlerRouter,buf,0)) { ParseDefmessageHandler(handlerRouter); DestroyPPBuffer(); CloseStringSource(theEnv,handlerRouter); } -*/ +*/ RouterData(theEnv)->FastCharGetRouter = oldRouter; RouterData(theEnv)->FastCharGetIndex = oldIndex; RouterData(theEnv)->FastCharGetString = oldString; @@ -414,7 +432,7 @@ globle void CreateGetAndPutHandlers( *****************************************************************/ static intBool IsParameterSlotReference( void *theEnv, - char *pname) + const char *pname) { if ((strncmp(pname,SELF_STRING,SELF_LEN) == 0) ? (pname[SELF_LEN] == SELF_SLOT_REF) : FALSE) @@ -503,7 +521,7 @@ static int BindSlotReference( EXPRESSION *bindExp, void *userBuffer) { - char *bindName; + const char *bindName; struct token itkn; int oldpp; SLOT_DESC *sd; @@ -663,17 +681,8 @@ static void GenHandlerSlotReference( handlerReference.classID = (unsigned short) sd->cls->id; handlerReference.slotID = (unsigned) sd->slotName->id; theExp->type = theType; - theExp->value = AddBitMap(theEnv,(void *) &handlerReference, + theExp->value = EnvAddBitMap(theEnv,(void *) &handlerReference, (int) sizeof(HANDLER_SLOT_REFERENCE)); } #endif - -/*************************************************** - NAME : - DESCRIPTION : - INPUTS : - RETURNS : - SIDE EFFECTS : - NOTES : - ***************************************************/ diff --git a/src/msgpsr.h b/src/msgpsr.h index b1c0260..044c76e 100644 --- a/src/msgpsr.h +++ b/src/msgpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,33 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS */ +/* compilation flag. */ +/* */ +/* 6.30: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_AND_SAVE */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #ifndef _H_msgpsr @@ -39,12 +60,12 @@ #define LOCALE extern #endif -LOCALE int ParseDefmessageHandler(void *,char *); -LOCALE void CreateGetAndPutHandlers(void *,SLOT_DESC *); + LOCALE int ParseDefmessageHandler(void *,const char *); + LOCALE void CreateGetAndPutHandlers(void *,SLOT_DESC *); -#endif +#endif /* OBJECT_SYSTEM && (! BLOAD_ONLY) && (! RUN_TIME) */ -#endif +#endif /* _H_msgpsr */ diff --git a/src/multifld.c b/src/multifld.c index 2347725..a96d1e3 100644 --- a/src/multifld.c +++ b/src/multifld.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/19/14 */ /* */ /* MULTIFIELD MODULE */ /*******************************************************/ @@ -13,7 +13,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -23,6 +23,23 @@ /* */ /* Moved ImplodeMultifield from multifun.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used DataObjectToString instead of */ +/* ValueToString in implode$ to handle */ +/* print representation of external addresses. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed issue with StoreInMultifield when */ +/* asserting void values in implied deftemplate */ +/* facts. */ +/* */ /*************************************************************/ #define _MULTIFLD_SOURCE_ @@ -46,65 +63,30 @@ #include "multifld.h" -/***************************************/ -/* LOCAL INTERNAL FUNCTION DEFINITIONS */ -/***************************************/ - - static void DeallocateMultifieldData(void *); - -/***************************************************/ -/* InitializeMultifieldData: Allocates environment */ -/* data for multifield values. */ -/***************************************************/ -globle void InitializeMultifieldData( - void *theEnv) - { - AllocateEnvironmentData(theEnv,MULTIFIELD_DATA,sizeof(struct multifieldData),DeallocateMultifieldData); - } - -/*****************************************************/ -/* DeallocateMultifieldData: Deallocates environment */ -/* data for multifield values. */ -/*****************************************************/ -static void DeallocateMultifieldData( - void *theEnv) - { - struct multifield *tmpPtr, *nextPtr; - - tmpPtr = MultifieldData(theEnv)->ListOfMultifields; - while (tmpPtr != NULL) - { - nextPtr = tmpPtr->next; - ReturnMultifield(theEnv,tmpPtr); - tmpPtr = nextPtr; - } - } - -/***********************************************************/ -/* CreateMultifield2: */ -/***********************************************************/ +/**********************/ +/* CreateMultifield2: */ +/**********************/ globle void *CreateMultifield2( void *theEnv, - unsigned long size) + long size) { struct multifield *theSegment; - unsigned long newSize = size; + long newSize = size; if (size <= 0) newSize = 1; - theSegment = get_var_struct2(theEnv,multifield,(long) sizeof(struct field) * (newSize - 1L)); + theSegment = get_var_struct(theEnv,multifield,(long) sizeof(struct field) * (newSize - 1L)); theSegment->multifieldLength = size; - theSegment->depth = (short) EvaluationData(theEnv)->CurrentEvaluationDepth; theSegment->busyCount = 0; theSegment->next = NULL; return((void *) theSegment); } -/*****************************************************************/ -/* ReturnMultifield: */ -/*****************************************************************/ +/*********************/ +/* ReturnMultifield: */ +/*********************/ globle void ReturnMultifield( void *theEnv, struct multifield *theSegment) @@ -116,12 +98,12 @@ globle void ReturnMultifield( if (theSegment->multifieldLength == 0) newSize = 1; else newSize = theSegment->multifieldLength; - rtn_var_struct2(theEnv,multifield,sizeof(struct field) * (newSize - 1),theSegment); + rtn_var_struct(theEnv,multifield,sizeof(struct field) * (newSize - 1),theSegment); } -/******************************/ -/* MultifieldInstall: */ -/******************************/ +/**********************/ +/* MultifieldInstall: */ +/**********************/ globle void MultifieldInstall( void *theEnv, struct multifield *theSegment) @@ -140,9 +122,9 @@ globle void MultifieldInstall( { AtomInstall(theEnv,theFields[i].type,theFields[i].value); } } -/******************************/ -/* MultifieldDeinstall: */ -/******************************/ +/************************/ +/* MultifieldDeinstall: */ +/************************/ globle void MultifieldDeinstall( void *theEnv, struct multifield *theSegment) @@ -161,12 +143,12 @@ globle void MultifieldDeinstall( } /*******************************************************/ -/* StringToMultifield: Returns a multifield structure */ +/* StringToMultifield: Returns a multifield structure */ /* that represents the string sent as the argument. */ /*******************************************************/ globle struct multifield *StringToMultifield( void *theEnv, - char *theString) + const char *theString) { struct token theToken; struct multifield *theSegment; @@ -234,40 +216,39 @@ globle struct multifield *StringToMultifield( return(theSegment); } - + /**************************************************************/ /* EnvCreateMultifield: Creates a multifield of the specified */ /* size and adds it to the list of segments. */ /**************************************************************/ globle void *EnvCreateMultifield( void *theEnv, - unsigned long size) + long size) { struct multifield *theSegment; - unsigned long newSize; + long newSize; if (size <= 0) newSize = 1; else newSize = size; - theSegment = get_var_struct2(theEnv,multifield,(long) sizeof(struct field) * (newSize - 1L)); + theSegment = get_var_struct(theEnv,multifield,(long) sizeof(struct field) * (newSize - 1L)); theSegment->multifieldLength = size; - theSegment->depth = (short) EvaluationData(theEnv)->CurrentEvaluationDepth; theSegment->busyCount = 0; theSegment->next = NULL; - theSegment->next = MultifieldData(theEnv)->ListOfMultifields; - MultifieldData(theEnv)->ListOfMultifields = theSegment; - - UtilityData(theEnv)->EphemeralItemCount++; - UtilityData(theEnv)->EphemeralItemSize += sizeof(struct multifield) + (sizeof(struct field) * newSize); + theSegment->next = UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields; + UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields = theSegment; + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + if (UtilityData(theEnv)->CurrentGarbageFrame->LastMultifield == NULL) + { UtilityData(theEnv)->CurrentGarbageFrame->LastMultifield = theSegment; } return((void *) theSegment); } -/*********************************************************************/ -/* DOToMultifield: */ -/*********************************************************************/ +/*******************/ +/* DOToMultifield: */ +/*******************/ globle void *DOToMultifield( void *theEnv, DATA_OBJECT *theValue) @@ -285,44 +266,49 @@ globle void *DOToMultifield( return((void *) dst); } -/***********************************************************/ -/* AddToMultifieldList: */ -/***********************************************************/ +/************************/ +/* AddToMultifieldList: */ +/************************/ globle void AddToMultifieldList( void *theEnv, struct multifield *theSegment) { - theSegment->depth = (short) EvaluationData(theEnv)->CurrentEvaluationDepth; - theSegment->next = MultifieldData(theEnv)->ListOfMultifields; - MultifieldData(theEnv)->ListOfMultifields = theSegment; - - UtilityData(theEnv)->EphemeralItemCount++; - UtilityData(theEnv)->EphemeralItemSize += sizeof(struct multifield) + (sizeof(struct field) * theSegment->multifieldLength); + theSegment->next = UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields; + UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields = theSegment; + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + if (UtilityData(theEnv)->CurrentGarbageFrame->LastMultifield == NULL) + { UtilityData(theEnv)->CurrentGarbageFrame->LastMultifield = theSegment; } } -/***********************************************************/ -/* FlushMultifields: */ -/***********************************************************/ +/*********************/ +/* FlushMultifields: */ +/*********************/ globle void FlushMultifields( void *theEnv) { struct multifield *theSegment, *nextPtr, *lastPtr = NULL; unsigned long newSize; - theSegment = MultifieldData(theEnv)->ListOfMultifields; + theSegment = UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields; while (theSegment != NULL) { nextPtr = theSegment->next; - if ((theSegment->depth > EvaluationData(theEnv)->CurrentEvaluationDepth) && (theSegment->busyCount == 0)) + if (theSegment->busyCount == 0) { - UtilityData(theEnv)->EphemeralItemCount--; - UtilityData(theEnv)->EphemeralItemSize -= sizeof(struct multifield) + - (sizeof(struct field) * theSegment->multifieldLength); if (theSegment->multifieldLength == 0) newSize = 1; else newSize = theSegment->multifieldLength; - rtn_var_struct2(theEnv,multifield,sizeof(struct field) * (newSize - 1),theSegment); - if (lastPtr == NULL) MultifieldData(theEnv)->ListOfMultifields = nextPtr; + rtn_var_struct(theEnv,multifield,sizeof(struct field) * (newSize - 1),theSegment); + if (lastPtr == NULL) UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields = nextPtr; else lastPtr->next = nextPtr; + + /*=================================================*/ + /* If the multifield deleted was the last in the */ + /* list, update the pointer to the last multifield */ + /* to the prior multifield. */ + /*=================================================*/ + + if (nextPtr == NULL) + { UtilityData(theEnv)->CurrentGarbageFrame->LastMultifield = lastPtr; } } else { lastPtr = theSegment; } @@ -331,10 +317,10 @@ globle void FlushMultifields( } } -/*********************************************************************/ +/************************************************************************/ /* DuplicateMultifield: Allocates a new segment and copies results from */ -/* old value to new - NOT put on ListOfMultifields!! */ -/*********************************************************************/ +/* old value to new. This value is not put on the ListOfMultifields. */ +/************************************************************************/ globle void DuplicateMultifield( void *theEnv, DATA_OBJECT_PTR dst, @@ -348,9 +334,9 @@ globle void DuplicateMultifield( &((struct multifield *) src->value)->theFields[src->begin]); } -/*********************************************************************/ -/* CopyMultifield: */ -/*********************************************************************/ +/*******************/ +/* CopyMultifield: */ +/*******************/ globle void *CopyMultifield( void *theEnv, struct multifield *src) @@ -362,12 +348,12 @@ globle void *CopyMultifield( return((void *) dst); } -/**********************************************************/ -/* PrintMultifield: Prints out a multifield */ -/**********************************************************/ +/*********************************************/ +/* PrintMultifield: Prints out a multifield. */ +/*********************************************/ globle void PrintMultifield( void *theEnv, - char *fileid, + const char *fileid, struct multifield *segment, long begin, long end, @@ -390,9 +376,9 @@ globle void PrintMultifield( EnvPrintRouter(theEnv,fileid,")"); } -/*****************************************************/ -/* StoreInMultifield: Append function for segments. */ -/*****************************************************/ +/****************************************************/ +/* StoreInMultifield: Append function for segments. */ +/****************************************************/ globle void StoreInMultifield( void *theEnv, DATA_OBJECT *returnValue, @@ -423,7 +409,6 @@ globle void StoreInMultifield( SetpValue(returnValue,(void *) theMultifield); return; } - else { /*========================================*/ @@ -433,7 +418,8 @@ globle void StoreInMultifield( val_arr = (DATA_OBJECT *) gm3(theEnv,(long) sizeof(DATA_OBJECT) * argCount); seg_size = 0; - for(i = 1 ; i <= argCount ; i++ , expptr = expptr->nextArg) + + for (i = 1; i <= argCount; i++, expptr = expptr->nextArg) { EvaluateExpression(theEnv,expptr,&val_ptr); if (EvaluationData(theEnv)->EvaluationError) @@ -480,20 +466,20 @@ globle void StoreInMultifield( /* Copy each argument into new segment. */ /*========================================*/ - for(k=0,j=1; k < argCount;k++) + for (k = 0, j = 1; k < argCount; k++) { if (GetpType(val_arr+k) == MULTIFIELD) { start = GetpDOBegin(val_arr+k); end = GetpDOEnd(val_arr+k); orig_ptr = (struct multifield *) GetpValue(val_arr+k); - for(i=start; i< end + 1; i++,j++) + for (i = start; i < end + 1; i++, j++) { SetMFType(theMultifield,j,(GetMFType(orig_ptr,i))); SetMFValue(theMultifield,j,(GetMFValue(orig_ptr,i))); } } - else if (GetpType(val_arr+k) != MULTIFIELD) + else if (GetpType(val_arr+k) != RVOID) { SetMFType(theMultifield,j,(short) (GetpType(val_arr+k))); SetMFValue(theMultifield,j,(GetpValue(val_arr+k))); @@ -559,7 +545,7 @@ globle int MultifieldsEqual( { struct field *elem1; struct field *elem2; - unsigned long length, i = 0; + long length, i = 0; length = segment1->multifieldLength; if (length != segment2->multifieldLength) @@ -595,18 +581,19 @@ globle int MultifieldsEqual( /************************************************************/ /* HashMultifield: Returns the hash value for a multifield. */ /************************************************************/ -unsigned HashMultifield( +globle unsigned long HashMultifield( struct multifield *theSegment, - unsigned theRange) + unsigned long theRange) { unsigned long length, i; - unsigned int tvalue; - unsigned int count; + unsigned long tvalue; + unsigned long count; struct field *fieldPtr; union { double fv; - unsigned int liv; + void *vv; + unsigned long liv; } fis; /*================================================*/ @@ -633,22 +620,30 @@ unsigned HashMultifield( break; case FLOAT: + fis.liv = 0; fis.fv = ValueToDouble(fieldPtr[i].value); count += (fis.liv * (i + 29)) + - (int) ValueToDouble(fieldPtr[i].value); + (unsigned long) ValueToDouble(fieldPtr[i].value); break; case INTEGER: - count += (((int) ValueToLong(fieldPtr[i].value)) * (i + 29)) + - ValueToLong(fieldPtr[i].value); + count += (((unsigned long) ValueToLong(fieldPtr[i].value)) * (i + 29)) + + ((unsigned long) ValueToLong(fieldPtr[i].value)); break; case FACT_ADDRESS: - case EXTERNAL_ADDRESS: #if OBJECT_SYSTEM case INSTANCE_ADDRESS: #endif - count += (unsigned int) (((int) fieldPtr[i].value) * (i + 29)); + fis.liv = 0; + fis.vv = fieldPtr[i].value; + count += (unsigned long) (fis.liv * (i + 29)); + break; + + case EXTERNAL_ADDRESS: + fis.liv = 0; + fis.vv = ValueToExternalAddress(fieldPtr[i].value); + count += (unsigned long) (fis.liv * (i + 29)); break; case SYMBOL: @@ -656,11 +651,9 @@ unsigned HashMultifield( #if OBJECT_SYSTEM case INSTANCE_NAME: #endif - tvalue = (unsigned) HashSymbol(ValueToString(fieldPtr[i].value),theRange); - count += (unsigned) (tvalue * (i + 29)); + tvalue = (unsigned long) HashSymbol(ValueToString(fieldPtr[i].value),theRange); + count += (unsigned long) (tvalue * (i + 29)); break; - default: - break; } } @@ -677,7 +670,7 @@ unsigned HashMultifield( globle struct multifield *GetMultifieldList( void *theEnv) { - return(MultifieldData(theEnv)->ListOfMultifields); + return(UtilityData(theEnv)->CurrentGarbageFrame->ListOfMultifields); } /***************************************/ @@ -688,12 +681,13 @@ globle void *ImplodeMultifield( void *theEnv, DATA_OBJECT *value) { - unsigned strsize = 0; + size_t strsize = 0; long i, j; - char *tmp_str; + const char *tmp_str; char *ret_str; void *rv; struct multifield *theMultifield; + DATA_OBJECT tempDO; /*===================================================*/ /* Determine the size of the string to be allocated. */ @@ -734,7 +728,11 @@ globle void *ImplodeMultifield( #endif else - { strsize += strlen(ValueToString(GetMFValue(theMultifield,i))) + 1; } + { + SetType(tempDO,GetMFType(theMultifield,i)); + SetValue(tempDO,GetMFValue(theMultifield,i)); + strsize += strlen(DataObjectToString(theEnv,&tempDO)) + 1; + } } /*=============================================*/ @@ -791,7 +789,7 @@ globle void *ImplodeMultifield( *(ret_str+j) = '\\'; /* GDR 111599 #835 */ j++; /* GDR 111599 #835 */ } /* GDR 111599 #835 */ - + *(ret_str+j) = *tmp_str; j++, tmp_str++; } @@ -824,7 +822,9 @@ globle void *ImplodeMultifield( #endif else { - tmp_str = ValueToString(GetMFValue(theMultifield,i)); + SetType(tempDO,GetMFType(theMultifield,i)); + SetValue(tempDO,GetMFValue(theMultifield,i)); + tmp_str = DataObjectToString(theEnv,&tempDO); while(*tmp_str) { *(ret_str+j) = *tmp_str; @@ -845,5 +845,18 @@ globle void *ImplodeMultifield( return(rv); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *CreateMultifield( + long size) + { + return EnvCreateMultifield(GetCurrentEnvironment(),size); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ diff --git a/src/multifld.h b/src/multifld.h index 4596f83..a024a4a 100644 --- a/src/multifld.h +++ b/src/multifld.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/19/14 */ /* */ /* MULTIFIELD HEADER FILE */ /*******************************************************/ @@ -19,8 +19,27 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove compiler warnings. */ +/* */ /* Moved ImplodeMultifield from multifun.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used DataObjectToString instead of */ +/* ValueToString in implode$ to handle */ +/* print representation of external addresses. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Fixed issue with StoreInMultifield when */ +/* asserting void values in implied deftemplate */ +/* facts. */ +/* */ /*************************************************************/ #ifndef _H_multifld @@ -43,8 +62,7 @@ struct field struct multifield { unsigned busyCount; - short depth; - unsigned long multifieldLength; + long multifieldLength; struct multifield *next; struct field theFields[1]; }; @@ -69,19 +87,6 @@ typedef struct field * FIELD_PTR; #define EnvGetMFType(theEnv,target,index) (((struct field *) ((struct multifield *) (target))->theFields)[index-1].type) #define EnvGetMFValue(theEnv,target,index) (((struct field *) ((struct multifield *) (target))->theFields)[index-1].value) -/*==================*/ -/* ENVIRONMENT DATA */ -/*==================*/ - -#define MULTIFIELD_DATA 51 - -struct multifieldData - { - struct multifield *ListOfMultifields; - }; - -#define MultifieldData(theEnv) ((struct multifieldData *) GetEnvironmentData(theEnv,MULTIFIELD_DATA)) - #ifdef LOCALE #undef LOCALE #endif @@ -90,34 +95,33 @@ struct multifieldData #else #define LOCALE extern #endif - -#if ENVIRONMENT_API_ONLY -#define CreateMultifield(theEnv,a) EnvCreateMultifield(theEnv,a) -#else -#define CreateMultifield(a) EnvCreateMultifield(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeMultifieldData(void *); - LOCALE void *CreateMultifield2(void *,unsigned long); + LOCALE void *CreateMultifield2(void *,long); LOCALE void ReturnMultifield(void *,struct multifield *); LOCALE void MultifieldInstall(void *,struct multifield *); LOCALE void MultifieldDeinstall(void *,struct multifield *); - LOCALE struct multifield *StringToMultifield(void *,char *); - LOCALE void *EnvCreateMultifield(void *,unsigned long); + LOCALE struct multifield *StringToMultifield(void *,const char *); + LOCALE void *EnvCreateMultifield(void *,long); LOCALE void AddToMultifieldList(void *,struct multifield *); LOCALE void FlushMultifields(void *); LOCALE void DuplicateMultifield(void *,struct dataObject *,struct dataObject *); - LOCALE void PrintMultifield(void *,char *,SEGMENT_PTR,long,long,int); + LOCALE void PrintMultifield(void *,const char *,SEGMENT_PTR,long,long,int); LOCALE intBool MultifieldDOsEqual(DATA_OBJECT_PTR,DATA_OBJECT_PTR); LOCALE void StoreInMultifield(void *,DATA_OBJECT *,EXPRESSION *,int); LOCALE void *CopyMultifield(void *,struct multifield *); LOCALE intBool MultifieldsEqual(struct multifield *,struct multifield *); LOCALE void *DOToMultifield(void *,DATA_OBJECT *); - LOCALE unsigned HashMultifield(struct multifield *,unsigned); + LOCALE unsigned long HashMultifield(struct multifield *,unsigned long); LOCALE struct multifield *GetMultifieldList(void *); LOCALE void *ImplodeMultifield(void *,DATA_OBJECT *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void *CreateMultifield(long); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_multifld */ diff --git a/src/multifun.c b/src/multifun.c index 1ab1284..b3a6f59 100644 --- a/src/multifun.c +++ b/src/multifun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* MULTIFIELD FUNCTIONS MODULE */ /*******************************************************/ @@ -16,12 +16,13 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian Donnell */ +/* Brian Dantes */ /* Barry Cameron */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable exp to theExp */ @@ -32,6 +33,20 @@ /* */ /* Moved ImplodeMultifield to multifld.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Fixed memory leaks when error occurred. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when DEFMODULE_CONSTRUCT */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #define _MULTIFUN_SOURCE_ @@ -80,13 +95,15 @@ typedef struct fieldVarStack #if MULTIFIELD_FUNCTIONS static intBool MVRangeCheck(long,long,long *,int); + static void MultifieldPrognDriver(void *,DATA_OBJECT_PTR,const char *); #if (! BLOAD_ONLY) && (! RUN_TIME) - static struct expr *MultifieldPrognParser(void *,struct expr *,char *); + static struct expr *MultifieldPrognParser(void *,struct expr *,const char *); + static struct expr *ForeachParser(void *,struct expr *,const char *); static void ReplaceMvPrognFieldVars(void *,SYMBOL_HN *,struct expr *,int); -#endif -#endif - static void MVRangeError(void *,long,long,unsigned long,char *); -#endif +#endif /* (! BLOAD_ONLY) && (! RUN_TIME) */ +#endif /* MULTIFIELD_FUNCTIONS */ + static void MVRangeError(void *,long,long,long,const char *); +#endif /* MULTIFIELD_FUNCTIONS || OBJECT_SYSTEM */ /***************************************/ /* LOCAL INTERNAL VARIABLE DEFINITIONS */ @@ -97,7 +114,7 @@ typedef struct fieldVarStack #define MULTIFUN_DATA 10 struct multiFunctionData - { + { FIELD_VAR_STACK *FieldVarStack; }; @@ -127,6 +144,7 @@ globle void MultifieldFunctionDefinitions( EnvDefineFunction2(theEnv,"member$", 'u', PTIEF MemberFunction, "MemberFunction", "22*um"); EnvDefineFunction2(theEnv,"subsetp", 'b', PTIEF SubsetpFunction, "SubsetpFunction", "22*mm"); EnvDefineFunction2(theEnv,"progn$", 'u', PTIEF MultifieldPrognFunction, "MultifieldPrognFunction", NULL); + EnvDefineFunction2(theEnv,"foreach", 'u', PTIEF ForeachFunction, "ForeachFunction", NULL); EnvDefineFunction2(theEnv,"str-implode", 's', PTIEF ImplodeFunction, "ImplodeFunction", "11m"); EnvDefineFunction2(theEnv,"str-explode", 'm', PTIEF ExplodeFunction, "ExplodeFunction", "11s"); EnvDefineFunction2(theEnv,"subset", 'b', PTIEF SubsetpFunction, "SubsetpFunction", "22*mm"); @@ -137,8 +155,10 @@ globle void MultifieldFunctionDefinitions( EnvDefineFunction2(theEnv,"mv-delete", 'm', PTIEF MVDeleteFunction,"MVDeleteFunction", "22*im"); #if ! BLOAD_ONLY AddFunctionParser(theEnv,"progn$",MultifieldPrognParser); + AddFunctionParser(theEnv,"foreach",ForeachParser); #endif FuncSeqOvlFlags(theEnv,"progn$",FALSE,FALSE); + FuncSeqOvlFlags(theEnv,"foreach",FALSE,FALSE); EnvDefineFunction2(theEnv,"(get-progn$-field)", 'u', PTIEF GetMvPrognField, "GetMvPrognField", "00"); EnvDefineFunction2(theEnv,"(get-progn$-index)", 'l', PTIEF GetMvPrognIndex, "GetMvPrognIndex", "00"); #endif @@ -172,7 +192,7 @@ globle void DeleteFunction( /*=================================================*/ if (DeleteMultiValueField(theEnv,returnValue,&value1, - DOToLong(value2),DOToLong(value3),"delete$") == FALSE) + (long) DOToLong(value2),(long) DOToLong(value3),"delete$") == FALSE)/* TBD */ { SetEvaluationError(theEnv,TRUE); EnvSetMultifieldErrorValue(theEnv,returnValue); @@ -206,7 +226,7 @@ globle void MVDeleteFunction( /*=================================================*/ if (DeleteMultiValueField(theEnv,returnValue,&value2, - DOToLong(value1),DOToLong(value1),"mv-delete") == FALSE) + (long) DOToLong(value1),(long) DOToLong(value1),"mv-delete") == FALSE) /* TBD */ { SetEvaluationError(theEnv,TRUE); EnvSetMultifieldErrorValue(theEnv,returnValue); @@ -251,8 +271,8 @@ globle void ReplaceFunction( /* Replace the section in the multifield value. */ /*==============================================*/ - if (ReplaceMultiValueField(theEnv,returnValue,&value1,DOToInteger(value2), - DOToInteger(value3),&value4,"replace$") == FALSE) + if (ReplaceMultiValueField(theEnv,returnValue,&value1,(long) DOToLong(value2), + (long) DOToLong(value3),&value4,"replace$") == FALSE) /* TBD */ { SetEvaluationError(theEnv,TRUE); EnvSetMultifieldErrorValue(theEnv,returnValue); @@ -291,8 +311,8 @@ globle void MVReplaceFunction( /* Replace the section in the multifield value. */ /*==============================================*/ - if (ReplaceMultiValueField(theEnv,returnValue,&value2,DOToInteger(value1), - DOToInteger(value1),&value3,"mv-replace") == FALSE) + if (ReplaceMultiValueField(theEnv,returnValue,&value2,(long) DOToLong(value1), + (long) DOToLong(value1),&value3,"mv-replace") == FALSE) /* TBD */ { SetEvaluationError(theEnv,TRUE); EnvSetMultifieldErrorValue(theEnv,returnValue); @@ -485,7 +505,7 @@ globle void InsertFunction( /* Insert the value in the multifield value. */ /*===========================================*/ - if (InsertMultiValueField(theEnv,returnValue,&value1,DOToLong(value2), + if (InsertMultiValueField(theEnv,returnValue,&value1,(long) DOToLong(value2), /* TBD */ &value3,"insert$") == FALSE) { SetEvaluationError(theEnv,TRUE); @@ -593,7 +613,7 @@ globle void SubseqFunction( { DATA_OBJECT value; struct multifield *theList; - long offset, start, end, length; /* 6.04 Bug Fix */ + long long offset, start, end, length; /* 6.04 Bug Fix */ /*===================================*/ /* Get the segment to be subdivided. */ @@ -618,14 +638,14 @@ globle void SubseqFunction( EnvSetMultifieldErrorValue(theEnv,sub_value); return; } - start = DOToInteger(value); + start = DOToLong(value); if (EnvArgTypeCheck(theEnv,"subseq$",3,INTEGER,&value) == FALSE) { EnvSetMultifieldErrorValue(theEnv,sub_value); return; } - end = DOToInteger(value); + end = DOToLong(value); if ((end < 1) || (end < start)) { @@ -665,7 +685,7 @@ globle void MVSubseqFunction( { DATA_OBJECT value; struct multifield *theList; - long offset, start, end, length; /* 6.04 Bug Fix */ + long long offset, start, end, length; /* 6.04 Bug Fix */ /*=============================================*/ /* Get range arguments. If they are not within */ @@ -677,14 +697,14 @@ globle void MVSubseqFunction( EnvSetMultifieldErrorValue(theEnv,sub_value); return; } - start = DOToInteger(value); + start = DOToLong(value); if (EnvArgTypeCheck(theEnv,"mv-subseq",2,INTEGER,&value) == FALSE) { EnvSetMultifieldErrorValue(theEnv,sub_value); return; } - end = DOToInteger(value); + end = DOToLong(value); if ((end < 1) || (end < start)) { @@ -809,34 +829,34 @@ globle void NthFunction( { DATA_OBJECT value1, value2; struct multifield *elm_ptr; - long n; /* 6.04 Bug Fix */ + long long n; /* 6.04 Bug Fix */ if (EnvArgCountCheck(theEnv,"nth$",EXACTLY,2) == -1) - { - SetpType(nth_value,SYMBOL); - SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); - return; - } + { + SetpType(nth_value,SYMBOL); + SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); + return; + } if ((EnvArgTypeCheck(theEnv,"nth$",1,INTEGER,&value1) == FALSE) || - (EnvArgTypeCheck(theEnv,"nth$",2,MULTIFIELD,&value2) == FALSE)) - { - SetpType(nth_value,SYMBOL); - SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); - return; - } + (EnvArgTypeCheck(theEnv,"nth$",2,MULTIFIELD,&value2) == FALSE)) + { + SetpType(nth_value,SYMBOL); + SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); + return; + } n = DOToLong(value1); /* 6.04 Bug Fix */ if ((n > GetDOLength(value2)) || (n < 1)) - { - SetpType(nth_value,SYMBOL); - SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); - return; - } + { + SetpType(nth_value,SYMBOL); + SetpValue(nth_value,(void *) EnvAddSymbol(theEnv,"nil")); + return; + } elm_ptr = (struct multifield *) GetValue(value2); - SetpType(nth_value,GetMFType(elm_ptr,n + GetDOBegin(value2) - 1)); - SetpValue(nth_value,GetMFValue(elm_ptr,n + GetDOBegin(value2) - 1)); + SetpType(nth_value,GetMFType(elm_ptr,((long) n) + GetDOBegin(value2) - 1)); + SetpValue(nth_value,GetMFValue(elm_ptr,((long) n) + GetDOBegin(value2) - 1)); } /* ------------------------------------------------------------------ @@ -862,7 +882,7 @@ globle intBool SubsetpFunction( void *theEnv) { DATA_OBJECT item1, item2, tmpItem; - long i,j,k; + long i,j,k; if (EnvArgCountCheck(theEnv,"subsetp",EXACTLY,2) == -1) return(FALSE); @@ -898,7 +918,7 @@ globle void MemberFunction( DATA_OBJECT_PTR result) { DATA_OBJECT item1, item2; - long j,k; + long j, k; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); @@ -1012,7 +1032,7 @@ static intBool MVRangeCheck( static struct expr *MultifieldPrognParser( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct BindInfo *oldBindList,*newBindList,*prev; struct token tkn; @@ -1087,6 +1107,7 @@ static struct expr *MultifieldPrognParser( SavePPBuffer(theEnv,tkn.printForm); if (top->argList->nextArg == NULL) { + ClearParsedBindNames(theEnv); SetParsedBindNames(theEnv,oldBindList); ReturnExpression(theEnv,top); return(NULL); @@ -1126,6 +1147,89 @@ MvPrognParseError: return(NULL); } +/******************************************************/ +/* ForeachParser: Parses the foreach function. */ +/******************************************************/ +static struct expr *ForeachParser( + void *theEnv, + struct expr *top, + const char *infile) + { + struct BindInfo *oldBindList,*newBindList,*prev; + struct token tkn; + struct expr *tmp; + SYMBOL_HN *fieldVar; + + SavePPBuffer(theEnv," "); + GetToken(theEnv,infile,&tkn); + + if (tkn.type != SF_VARIABLE) + { goto ForeachParseError; } + + fieldVar = (SYMBOL_HN *) tkn.value; + SavePPBuffer(theEnv," "); + top->argList = ParseAtomOrExpression(theEnv,infile,NULL); + if (top->argList == NULL) + { + ReturnExpression(theEnv,top); + return(NULL); + } + + if (CheckArgumentAgainstRestriction(theEnv,top->argList,(int) 'm')) + goto ForeachParseError; + oldBindList = GetParsedBindNames(theEnv); + SetParsedBindNames(theEnv,NULL); + IncrementIndentDepth(theEnv,3); + ExpressionData(theEnv)->BreakContext = TRUE; + ExpressionData(theEnv)->ReturnContext = ExpressionData(theEnv)->svContexts->rtn; + PPCRAndIndent(theEnv); + top->argList->nextArg = GroupActions(theEnv,infile,&tkn,TRUE,NULL,FALSE); + DecrementIndentDepth(theEnv,3); + PPBackup(theEnv); + PPBackup(theEnv); + SavePPBuffer(theEnv,tkn.printForm); + if (top->argList->nextArg == NULL) + { + ClearParsedBindNames(theEnv); + SetParsedBindNames(theEnv,oldBindList); + ReturnExpression(theEnv,top); + return(NULL); + } + tmp = top->argList->nextArg; + top->argList->nextArg = tmp->argList; + tmp->argList = NULL; + ReturnExpression(theEnv,tmp); + newBindList = GetParsedBindNames(theEnv); + prev = NULL; + while (newBindList != NULL) + { + if ((fieldVar == NULL) ? FALSE : + (strcmp(ValueToString(newBindList->name),ValueToString(fieldVar)) == 0)) + { + ClearParsedBindNames(theEnv); + SetParsedBindNames(theEnv,oldBindList); + PrintErrorID(theEnv,"MULTIFUN",2,FALSE); + EnvPrintRouter(theEnv,WERROR,"Cannot rebind field variable in function foreach.\n"); + ReturnExpression(theEnv,top); + return(NULL); + } + prev = newBindList; + newBindList = newBindList->next; + } + if (prev == NULL) + SetParsedBindNames(theEnv,oldBindList); + else + prev->next = oldBindList; + if (fieldVar != NULL) + ReplaceMvPrognFieldVars(theEnv,fieldVar,top->argList->nextArg,0); + return(top); + +ForeachParseError: + SyntaxErrorMessage(theEnv,"foreach"); + ReturnExpression(theEnv,top); + return(NULL); + } + /**********************************************/ /* ReplaceMvPrognFieldVars: Replaces variable */ /* references found in the progn$ function. */ @@ -1149,18 +1253,19 @@ static void ReplaceMvPrognFieldVars( { theExp->type = FCALL; theExp->value = (void *) FindFunction(theEnv,"(get-progn$-field)"); - theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long) depth)); + theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long long) depth)); } else if (strcmp(ValueToString(theExp->value) + flen,"-index") == 0) { theExp->type = FCALL; theExp->value = (void *) FindFunction(theEnv,"(get-progn$-index)"); - theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long) depth)); + theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long long) depth)); } } else if (theExp->argList != NULL) { - if ((theExp->type == FCALL) && (theExp->value == (void *) FindFunction(theEnv,"progn$"))) + if ((theExp->type == FCALL) && ((theExp->value == (void *) FindFunction(theEnv,"progn$")) || + (theExp->value == (void *) FindFunction(theEnv,"foreach")) )) ReplaceMvPrognFieldVars(theEnv,fieldVar,theExp->argList,depth+1); else ReplaceMvPrognFieldVars(theEnv,fieldVar,theExp->argList,depth); @@ -1169,7 +1274,7 @@ static void ReplaceMvPrognFieldVars( } } -#endif +#endif /* (! BLOAD_ONLY) && (! RUN_TIME) */ /*****************************************/ /* MultifieldPrognFunction: H/L access */ @@ -1179,10 +1284,35 @@ globle void MultifieldPrognFunction( void *theEnv, DATA_OBJECT_PTR result) { + MultifieldPrognDriver(theEnv,result,"progn$"); + } + +/***************************************/ +/* ForeachFunction: H/L access routine */ +/* for the foreach function. */ +/***************************************/ +globle void ForeachFunction( + void *theEnv, + DATA_OBJECT_PTR result) + { + MultifieldPrognDriver(theEnv,result,"foreach"); + } + +/*******************************************/ +/* MultifieldPrognDriver: Driver routine */ +/* for the progn$ and foreach functions. */ +/******************************************/ +static void MultifieldPrognDriver( + void *theEnv, + DATA_OBJECT_PTR result, + const char *functionName) + { EXPRESSION *theExp; DATA_OBJECT argval; long i, end; /* 6.04 Bug Fix */ FIELD_VAR_STACK *tmpField; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; tmpField = get_struct(theEnv,fieldVarStack); tmpField->type = SYMBOL; @@ -1191,32 +1321,31 @@ globle void MultifieldPrognFunction( MultiFunctionData(theEnv)->FieldVarStack = tmpField; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); - if (EnvArgTypeCheck(theEnv,"progn$",1,MULTIFIELD,&argval) == FALSE) + if (EnvArgTypeCheck(theEnv,functionName,1,MULTIFIELD,&argval) == FALSE) { MultiFunctionData(theEnv)->FieldVarStack = tmpField->nxt; rtn_struct(theEnv,fieldVarStack,tmpField); return; } - ValueInstall(theEnv,&argval); + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + end = GetDOEnd(argval); for (i = GetDOBegin(argval) ; i <= end ; i++) { tmpField->type = GetMFType(argval.value,i); tmpField->value = GetMFValue(argval.value,i); /* tmpField->index = i; */ - tmpField->index = (i - GetDOBegin(argval)) + 1; + tmpField->index = (i - GetDOBegin(argval)) + 1; for (theExp = GetFirstArgument()->nextArg ; theExp != NULL ; theExp = theExp->nextArg) { - EvaluationData(theEnv)->CurrentEvaluationDepth++; EvaluateExpression(theEnv,theExp,result); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - if (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE) - { PropagateReturnValue(theEnv,result); } - PeriodicCleanup(theEnv,FALSE,TRUE); if (EvaluationData(theEnv)->HaltExecution || ProcedureFunctionData(theEnv)->BreakFlag || ProcedureFunctionData(theEnv)->ReturnFlag) { - ValueDeinstall(theEnv,&argval); ProcedureFunctionData(theEnv)->BreakFlag = FALSE; if (EvaluationData(theEnv)->HaltExecution) { @@ -1225,14 +1354,29 @@ globle void MultifieldPrognFunction( } MultiFunctionData(theEnv)->FieldVarStack = tmpField->nxt; rtn_struct(theEnv,fieldVarStack,tmpField); + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); return; } + + /*===================================*/ + /* Garbage collect if this isn't the */ + /* last evaluation of the progn$. */ + /*===================================*/ + + if ((i < end) || (theExp->nextArg != NULL)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } } } - ValueDeinstall(theEnv,&argval); + ProcedureFunctionData(theEnv)->BreakFlag = FALSE; MultiFunctionData(theEnv)->FieldVarStack = tmpField->nxt; rtn_struct(theEnv,fieldVarStack,tmpField); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,result); + CallPeriodicTasks(theEnv); } /***************************************************/ @@ -1275,7 +1419,7 @@ globle long GetMvPrognIndex( return(tmpField->index); } -#endif +#endif /* MULTIFIELD_FUNCTIONS */ #if OBJECT_SYSTEM || MULTIFIELD_FUNCTIONS @@ -1302,7 +1446,7 @@ globle int ReplaceMultiValueField( long rb, long re, DATA_OBJECT *field, - char *funcName) + const char *funcName) { long i,j,k; struct field *deptr; @@ -1311,54 +1455,54 @@ globle int ReplaceMultiValueField( srclen = ((src != NULL) ? (src->end - src->begin + 1) : 0); if ((re < rb) || - (rb < 1) || (re < 1) || - (rb > srclen) || (re > srclen)) - { - MVRangeError(theEnv,rb,re,(unsigned long) srclen,funcName); - return(FALSE); - } + (rb < 1) || (re < 1) || + (rb > srclen) || (re > srclen)) + { + MVRangeError(theEnv,rb,re,srclen,funcName); + return(FALSE); + } rb = src->begin + rb - 1; re = src->begin + re - 1; if (field->type == MULTIFIELD) - dstlen = srclen + GetpDOLength(field) - (re-rb+1); + dstlen = srclen + GetpDOLength(field) - (re-rb+1); else - dstlen = srclen + 1 - (re-rb+1); + dstlen = srclen + 1 - (re-rb+1); dst->type = MULTIFIELD; dst->begin = 0; - dst->value = EnvCreateMultifield(theEnv,(unsigned long) dstlen); + dst->value = EnvCreateMultifield(theEnv,dstlen); SetpDOEnd(dst,dstlen); for (i = 0 , j = src->begin ; j < rb ; i++ , j++) - { - deptr = &((struct multifield *) dst->value)->theFields[i]; - septr = &((struct multifield *) src->value)->theFields[j]; - deptr->type = septr->type; - deptr->value = septr->value; - } + { + deptr = &((struct multifield *) dst->value)->theFields[i]; + septr = &((struct multifield *) src->value)->theFields[j]; + deptr->type = septr->type; + deptr->value = septr->value; + } if (field->type != MULTIFIELD) - { - deptr = &((struct multifield *) dst->value)->theFields[i++]; - deptr->type = field->type; - deptr->value = field->value; - } + { + deptr = &((struct multifield *) dst->value)->theFields[i++]; + deptr->type = field->type; + deptr->value = field->value; + } else - { - for (k = field->begin ; k <= field->end ; k++ , i++) - { - deptr = &((struct multifield *) dst->value)->theFields[i]; - septr = &((struct multifield *) field->value)->theFields[k]; - deptr->type = septr->type; - deptr->value = septr->value; - } - } + { + for (k = field->begin ; k <= field->end ; k++ , i++) + { + deptr = &((struct multifield *) dst->value)->theFields[i]; + septr = &((struct multifield *) field->value)->theFields[k]; + deptr->type = septr->type; + deptr->value = septr->value; + } + } while (j < re) - j++; + j++; for (j++ ; i < dstlen ; i++ , j++) - { - deptr = &((struct multifield *) dst->value)->theFields[i]; - septr = &((struct multifield *) src->value)->theFields[j]; - deptr->type = septr->type; - deptr->value = septr->value; - } + { + deptr = &((struct multifield *) dst->value)->theFields[i]; + septr = &((struct multifield *) src->value)->theFields[j]; + deptr->type = septr->type; + deptr->value = septr->value; + } return(TRUE); } @@ -1383,20 +1527,20 @@ globle int InsertMultiValueField( DATA_OBJECT *src, long theIndex, DATA_OBJECT *field, - char *funcName) + const char *funcName) { - register long i,j,k; + long i,j,k; register FIELD *deptr, *septr; - unsigned long srclen,dstlen; + long srclen,dstlen; - srclen = (unsigned long) ((src != NULL) ? (src->end - src->begin + 1) : 0); + srclen = (long) ((src != NULL) ? (src->end - src->begin + 1) : 0); if (theIndex < 1) { MVRangeError(theEnv,theIndex,theIndex,srclen+1,funcName); return(FALSE); } - if (theIndex > (long) (srclen + 1)) - theIndex = (long) (srclen + 1); + if (theIndex > (srclen + 1)) + theIndex = (srclen + 1); dst->type = MULTIFIELD; dst->begin = 0; if (src == NULL) @@ -1471,22 +1615,22 @@ static void MVRangeError( void *theEnv, long brb, long bre, - unsigned long max, - char *funcName) + long max, + const char *funcName) { PrintErrorID(theEnv,"MULTIFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Multifield index "); if (brb == bre) - PrintLongInteger(theEnv,WERROR,(long) brb); + PrintLongInteger(theEnv,WERROR,(long long) brb); else { EnvPrintRouter(theEnv,WERROR,"range "); - PrintLongInteger(theEnv,WERROR,(long) brb); + PrintLongInteger(theEnv,WERROR,(long long) brb); EnvPrintRouter(theEnv,WERROR,".."); - PrintLongInteger(theEnv,WERROR,(long) bre); + PrintLongInteger(theEnv,WERROR,(long long) bre); } EnvPrintRouter(theEnv,WERROR," out of range 1.."); - PrintLongInteger(theEnv,WERROR,(long) max); + PrintLongInteger(theEnv,WERROR,(long long) max); if (funcName != NULL) { EnvPrintRouter(theEnv,WERROR," in function "); @@ -1516,16 +1660,16 @@ globle int DeleteMultiValueField( DATA_OBJECT *src, long rb, long re, - char *funcName) + const char *funcName) { - register long i,j; + long i,j; register FIELD_PTR deptr,septr; - unsigned long srclen, dstlen; + long srclen, dstlen; - srclen = (unsigned long) ((src != NULL) ? (src->end - src->begin + 1) : 0); + srclen = (long) ((src != NULL) ? (src->end - src->begin + 1) : 0); if ((re < rb) || (rb < 1) || (re < 1) || - (rb > ((long) srclen)) || (re > ((long) srclen))) + (rb > srclen) || (re > srclen)) { MVRangeError(theEnv,rb,re,srclen,funcName); return(FALSE); @@ -1562,4 +1706,4 @@ globle int DeleteMultiValueField( return(TRUE); } -#endif +#endif /* OBJECT_SYSTEM || MULTIFIELD_FUNCTIONS */ diff --git a/src/multifun.h b/src/multifun.h index eeff85d..55f0a72 100644 --- a/src/multifun.h +++ b/src/multifun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* MULTIFIELD FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -10,16 +10,36 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Gary Riley and Brian Donnell */ +/* Gary Riley and Brian Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ /* Moved ImplodeMultifield to multifld.c. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Fixed memory leaks when error occurred. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when DEFMODULE_CONSTRUCT */ +/* compiler flag is set to 0. */ +/* */ /*************************************************************/ #ifndef _H_multifun @@ -58,6 +78,7 @@ LOCALE intBool SubsetpFunction(void *); LOCALE void MemberFunction(void *,DATA_OBJECT_PTR); LOCALE void MultifieldPrognFunction(void *,DATA_OBJECT_PTR); + LOCALE void ForeachFunction(void *,DATA_OBJECT_PTR); LOCALE void GetMvPrognField(void *,DATA_OBJECT_PTR); LOCALE long GetMvPrognIndex(void *); LOCALE intBool FindDOsInSegment(DATA_OBJECT_PTR,int,DATA_OBJECT_PTR, @@ -65,13 +86,13 @@ #endif LOCALE int ReplaceMultiValueField(void *,struct dataObject *, struct dataObject *, - long, - long,struct dataObject *,char *); + long,long, + struct dataObject *,const char *); LOCALE int InsertMultiValueField(void *,struct dataObject *, struct dataObject *, - long,struct dataObject *,char *); + long,struct dataObject *,const char *); LOCALE int DeleteMultiValueField(void *,struct dataObject *,struct dataObject *, - long,long,char *); + long,long,const char *); -#endif +#endif /* _H_multifun */ diff --git a/src/network.h b/src/network.h index c081fba..1f10242 100644 --- a/src/network.h +++ b/src/network.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* NETWORK HEADER FILE */ /*******************************************************/ @@ -16,6 +16,8 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ /*************************************************************/ #ifndef _H_network @@ -24,16 +26,22 @@ struct patternNodeHeader; struct joinNode; +struct alphaMemoryHash; #ifndef _H_match #include "match.h" #endif +#ifndef _H_expressn +#include "expressn.h" +#endif + struct patternNodeHeader { - struct partialMatch *alphaMemory; - struct partialMatch *endOfQueue; + struct alphaMemoryHash *firstHash; + struct alphaMemoryHash *lastHash; struct joinNode *entryJoin; + struct expr *rightHash; unsigned int singlefieldNode : 1; unsigned int multifieldNode : 1; unsigned int stopNode : 1; @@ -41,38 +49,87 @@ struct patternNodeHeader unsigned int marked : 1; unsigned int beginSlot : 1; unsigned int endSlot : 1; + unsigned int selector : 1; }; -#ifndef _H_expressn -#include "expressn.h" -#endif +struct patternNodeHashEntry + { + void *parent; + void *child; + int type; + void *value; + struct patternNodeHashEntry *next; + }; + +#define SIZE_PATTERN_HASH 16231 + +struct alphaMemoryHash + { + unsigned long bucket; + struct patternNodeHeader *owner; + struct partialMatch *alphaMemory; + struct partialMatch *endOfQueue; + struct alphaMemoryHash *nextHash; + struct alphaMemoryHash *prevHash; + struct alphaMemoryHash *next; + struct alphaMemoryHash *prev; + }; + +typedef struct alphaMemoryHash ALPHA_MEMORY_HASH; #ifndef _H_ruledef #include "ruledef.h" #endif +#define INITIAL_BETA_HASH_SIZE 17 + +struct betaMemory + { + unsigned long size; + unsigned long count; + struct partialMatch **beta; + struct partialMatch **last; + }; + +struct joinLink + { + char enterDirection; + struct joinNode *join; + struct joinLink *next; + long bsaveID; + }; + struct joinNode { unsigned int firstJoin : 1; unsigned int logicalJoin : 1; unsigned int joinFromTheRight : 1; unsigned int patternIsNegated : 1; + unsigned int patternIsExists : 1; unsigned int initialize : 1; unsigned int marked : 1; unsigned int rhsType : 3; - unsigned int depth : 7; + unsigned int depth : 16; long bsaveID; - struct partialMatch *beta; + long long memoryLeftAdds; + long long memoryRightAdds; + long long memoryLeftDeletes; + long long memoryRightDeletes; + long long memoryCompares; + struct betaMemory *leftMemory; + struct betaMemory *rightMemory; struct expr *networkTest; + struct expr *secondaryNetworkTest; + struct expr *leftHash; + struct expr *rightHash; void *rightSideEntryStructure; - struct joinNode *nextLevel; + struct joinLink *nextLinks; struct joinNode *lastLevel; - struct joinNode *rightDriveNode; struct joinNode *rightMatchNode; struct defrule *ruleToActivate; }; -#endif +#endif /* _H_network */ diff --git a/src/objbin.c b/src/objbin.c index aa8d602..abcb6c0 100644 --- a/src/objbin.c +++ b/src/objbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -11,14 +11,21 @@ /* message-handlers */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS and */ /* AUXILIARY_MESSAGE_HANDLERS compilation flags. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ /* ========================================= @@ -57,7 +64,6 @@ MACROS AND TYPES ========================================= ***************************************** */ -typedef unsigned long UNLN; #define SlotIndex(p) (((p) != NULL) ? (p)->bsaveIndex : -1L) #define SlotNameIndex(p) (p)->bsaveIndex @@ -77,7 +83,7 @@ typedef struct bsaveDefclassModule typedef struct bsavePackedClassLinks { - unsigned short classCount; + long classCount; long classArray; } BSAVE_PACKED_CLASS_LINKS; @@ -87,13 +93,13 @@ typedef struct bsaveDefclass unsigned abstract : 1; unsigned reactive : 1; unsigned system : 1; - unsigned short id; + unsigned id; BSAVE_PACKED_CLASS_LINKS directSuperclasses, directSubclasses, allSuperclasses; - unsigned slotCount,localInstanceSlotCount, + short slotCount,localInstanceSlotCount, instanceSlotCount,maxSlotNameID; - unsigned handlerCount; + short handlerCount; long slots, instanceTemplate, slotNameMap, @@ -103,8 +109,8 @@ typedef struct bsaveDefclass typedef struct bsaveSlotName { - unsigned id, - hashTableIndex; + short id; + unsigned hashTableIndex; long name, putHandlerName; } BSAVE_SLOT_NAME; @@ -134,7 +140,7 @@ typedef struct bsaveMessageHandler { unsigned system : 1; unsigned type : 2; - int minParams, + short minParams, maxParams, localVarCount; long name, @@ -207,7 +213,7 @@ globle void SetupObjectsBload( void *theEnv) { AllocateEnvironmentData(theEnv,OBJECTBIN_DATA,sizeof(struct objectBinaryData),DeallocateObjectBinaryData); - + AddAbortBloadFunction(theEnv,"defclass",CreateSystemClasses,0); #if BLOAD_AND_BSAVE @@ -223,7 +229,7 @@ globle void SetupObjectsBload( #endif } - + /*******************************************************/ /* DeallocateObjectBinaryData: Deallocates environment */ /* data for object binary functionality. */ @@ -231,57 +237,58 @@ globle void SetupObjectsBload( static void DeallocateObjectBinaryData( void *theEnv) { - unsigned long space, i; + size_t space; + long i; #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) - - space = (unsigned long) (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); - if (space != 0) genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->ModuleArray,space); + + space = (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); + if (space != 0) genfree(theEnv,(void *) ObjectBinaryData(theEnv)->ModuleArray,space); if (ObjectBinaryData(theEnv)->ClassCount != 0) - { + { if (DefclassData(theEnv)->ClassIDMap != NULL) { rm(theEnv,(void *) DefclassData(theEnv)->ClassIDMap,(sizeof(DEFCLASS *) * DefclassData(theEnv)->AvailClassID)); } - for (i = 0L ; i < (unsigned long) ObjectBinaryData(theEnv)->SlotCount ; i++) + for (i = 0L ; i < ObjectBinaryData(theEnv)->SlotCount ; i++) { if ((ObjectBinaryData(theEnv)->SlotArray[i].defaultValue != NULL) && (ObjectBinaryData(theEnv)->SlotArray[i].dynamicDefault == 0)) { rtn_struct(theEnv,dataObject,ObjectBinaryData(theEnv)->SlotArray[i].defaultValue); } } - space = (UNLN) (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); + space = (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->DefclassArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->DefclassArray,space); } - space = (UNLN) (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); + space = (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->LinkArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->LinkArray,space); } - space = (UNLN) (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); + space = (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotArray,space); } - space = (UNLN) (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); + space = (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotNameArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotNameArray,space); } - space = (UNLN) (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); + space = (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->TmpslotArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->TmpslotArray,space); } - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); if (space != 0L) - { genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->MapslotArray,space); } + { genfree(theEnv,(void *) ObjectBinaryData(theEnv)->MapslotArray,space); } } if (ObjectBinaryData(theEnv)->HandlerCount != 0L) { - space = (UNLN) (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); + space = (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->HandlerArray,space); - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->MaphandlerArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->HandlerArray,space); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->MaphandlerArray,space); } } #endif @@ -355,7 +362,7 @@ static void BsaveObjectsFind( /* ============================================== Mark items needed by defclasses in all modules ============================================== */ - ObjectBinaryData(theEnv)->ModuleCount = + ObjectBinaryData(theEnv)->ModuleCount = DoForAllConstructs(theEnv,MarkDefclassItems,DefclassData(theEnv)->DefclassModuleIndex, FALSE,NULL); @@ -384,19 +391,16 @@ static void BsaveObjectsFind( ephemerals marked NOTES : None ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkDefclassItems( void *theEnv, struct constructHeader *theDefclass, void *buf) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buf) #endif DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; EXPRESSION *tmpexp; MarkConstructHeaderNeededItems(&cls->header,ObjectBinaryData(theEnv)->ClassCount++); @@ -502,7 +506,7 @@ static void BsaveDefaultSlotExpressions( void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; EXPRESSION *tmpexp; for (i = 0 ; i < cls->slotCount ; i++) @@ -542,7 +546,7 @@ static void BsaveHandlerActionExpressions( void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; for (i = 0 ; i < cls->handlerCount ; i++) BsaveExpression(theEnv,cls->handlers[i].actions,(FILE *) buf); @@ -568,26 +572,27 @@ static void BsaveStorageObjects( void *theEnv, FILE *fp) { - UNLN space; + size_t space; + long maxClassID; if ((ObjectBinaryData(theEnv)->ClassCount == 0L) && (ObjectBinaryData(theEnv)->HandlerCount == 0L)) { space = 0L; - GenWrite((void *) &space,(UNLN) sizeof(long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); return; } space = sizeof(long) * 9; - GenWrite((void *) &space,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->ModuleCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->ClassCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->LinkCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->SlotNameCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->SlotCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->TemplateSlotCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->SlotNameMapCount,(UNLN) sizeof(long),fp); - GenWrite((void *) &ObjectBinaryData(theEnv)->HandlerCount,(UNLN) sizeof(long),fp); - space = (UNLN) DefclassData(theEnv)->MaxClassID; - GenWrite((void *) &space,(UNLN) sizeof(long),fp); + GenWrite((void *) &space,sizeof(size_t),fp); // 64-bit issue changed long to size_t + GenWrite((void *) &ObjectBinaryData(theEnv)->ModuleCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->ClassCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->LinkCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->SlotNameCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->SlotCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->TemplateSlotCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->SlotNameMapCount,sizeof(long),fp); + GenWrite((void *) &ObjectBinaryData(theEnv)->HandlerCount,sizeof(long),fp); + maxClassID = DefclassData(theEnv)->MaxClassID; + GenWrite((void *) &maxClassID,sizeof(long),fp); } /************************************************************************************* @@ -604,7 +609,7 @@ static void BsaveObjects( void *theEnv, FILE *fp) { - UNLN space; + size_t space; struct defmodule *theModule; DEFCLASS_MODULE *theModuleItem; BSAVE_DEFCLASS_MODULE dummy_mitem; @@ -615,19 +620,19 @@ static void BsaveObjects( if ((ObjectBinaryData(theEnv)->ClassCount == 0L) && (ObjectBinaryData(theEnv)->HandlerCount == 0L)) { space = 0L; - GenWrite((void *) &space,(UNLN) sizeof(UNLN),fp); + GenWrite((void *) &space,sizeof(size_t),fp); return; } - space = (ObjectBinaryData(theEnv)->ModuleCount * (UNLN) sizeof(BSAVE_DEFCLASS_MODULE)) + - (ObjectBinaryData(theEnv)->ClassCount * (UNLN) sizeof(BSAVE_DEFCLASS)) + - (ObjectBinaryData(theEnv)->LinkCount * (UNLN) sizeof(long)) + - (ObjectBinaryData(theEnv)->SlotCount * (UNLN) sizeof(BSAVE_SLOT_DESC)) + - (ObjectBinaryData(theEnv)->SlotNameCount * (UNLN) sizeof(BSAVE_SLOT_NAME)) + - (ObjectBinaryData(theEnv)->TemplateSlotCount * (UNLN) sizeof(long)) + - (ObjectBinaryData(theEnv)->SlotNameMapCount * (UNLN) sizeof(unsigned)) + - (ObjectBinaryData(theEnv)->HandlerCount * (UNLN) sizeof(BSAVE_HANDLER)) + - (ObjectBinaryData(theEnv)->HandlerCount * (UNLN) sizeof(unsigned)); - GenWrite((void *) &space,(UNLN) sizeof(UNLN),fp); + space = (ObjectBinaryData(theEnv)->ModuleCount * sizeof(BSAVE_DEFCLASS_MODULE)) + + (ObjectBinaryData(theEnv)->ClassCount * sizeof(BSAVE_DEFCLASS)) + + (ObjectBinaryData(theEnv)->LinkCount * sizeof(long)) + + (ObjectBinaryData(theEnv)->SlotCount * sizeof(BSAVE_SLOT_DESC)) + + (ObjectBinaryData(theEnv)->SlotNameCount * sizeof(BSAVE_SLOT_NAME)) + + (ObjectBinaryData(theEnv)->TemplateSlotCount * sizeof(long)) + + (ObjectBinaryData(theEnv)->SlotNameMapCount * sizeof(unsigned)) + + (ObjectBinaryData(theEnv)->HandlerCount * sizeof(BSAVE_HANDLER)) + + (ObjectBinaryData(theEnv)->HandlerCount * sizeof(unsigned)); + GenWrite((void *) &space,sizeof(size_t),fp); ObjectBinaryData(theEnv)->ClassCount = 0L; ObjectBinaryData(theEnv)->LinkCount = 0L; @@ -646,7 +651,7 @@ static void BsaveObjects( theModuleItem = (DEFCLASS_MODULE *) GetModuleItem(theEnv,theModule,FindModuleItem(theEnv,"defclass")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&dummy_mitem.header,&theModuleItem->header); - GenWrite((void *) &dummy_mitem,(unsigned long) sizeof(BSAVE_DEFCLASS_MODULE),fp); + GenWrite((void *) &dummy_mitem,sizeof(BSAVE_DEFCLASS_MODULE),fp); theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule); } @@ -673,7 +678,7 @@ static void BsaveObjects( dummy_slot_name.hashTableIndex = snp->hashTableIndex; dummy_slot_name.name = (long) snp->name->bucket; dummy_slot_name.putHandlerName = (long) snp->putHandlerName->bucket; - GenWrite((void *) &dummy_slot_name,(UNLN) sizeof(BSAVE_SLOT_NAME),fp); + GenWrite((void *) &dummy_slot_name,sizeof(BSAVE_SLOT_NAME),fp); } } @@ -794,7 +799,7 @@ static void BsaveDefclass( #else dummy_class.scopeMap = -1L; #endif - GenWrite((void *) &dummy_class,(UNLN) sizeof(BSAVE_DEFCLASS),(FILE *) buf); + GenWrite((void *) &dummy_class,sizeof(BSAVE_DEFCLASS),(FILE *) buf); } /*************************************************** @@ -812,25 +817,25 @@ static void BsaveClassLinks( void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; long dummy_class_index; for (i = 0 ; i < cls->directSuperclasses.classCount ; i++) { dummy_class_index = DefclassIndex(cls->directSuperclasses.classArray[i]); - GenWrite((void *) &dummy_class_index,(UNLN) sizeof(long),(FILE *) buf); + GenWrite((void *) &dummy_class_index,sizeof(long),(FILE *) buf); } ObjectBinaryData(theEnv)->LinkCount += cls->directSuperclasses.classCount; for (i = 0 ; i < cls->directSubclasses.classCount ; i++) { dummy_class_index = DefclassIndex(cls->directSubclasses.classArray[i]); - GenWrite((void *) &dummy_class_index,(UNLN) sizeof(long),(FILE *) buf); + GenWrite((void *) &dummy_class_index,sizeof(long),(FILE *) buf); } ObjectBinaryData(theEnv)->LinkCount += cls->directSubclasses.classCount; for (i = 0 ; i < cls->allSuperclasses.classCount ; i++) { dummy_class_index = DefclassIndex(cls->allSuperclasses.classArray[i]); - GenWrite((void *) &dummy_class_index,(UNLN) sizeof(long),(FILE *) buf); + GenWrite((void *) &dummy_class_index,sizeof(long),(FILE *) buf); } ObjectBinaryData(theEnv)->LinkCount += cls->allSuperclasses.classCount; } @@ -850,7 +855,7 @@ static void BsaveSlots( void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; BSAVE_SLOT_DESC dummy_slot; SLOT_DESC *sp; EXPRESSION *tmpexp; @@ -888,7 +893,7 @@ static void BsaveSlots( else dummy_slot.defaultValue = -1L; dummy_slot.constraint = ConstraintIndex(sp->constraint); - GenWrite((void *) &dummy_slot,(UNLN) sizeof(BSAVE_SLOT_DESC),(FILE *) buf); + GenWrite((void *) &dummy_slot,sizeof(BSAVE_SLOT_DESC),(FILE *) buf); } } @@ -901,25 +906,22 @@ static void BsaveSlots( SIDE EFFECTS : Defclass instance template binary data written NOTES : None **************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void BsaveTemplateSlots( void *theEnv, struct constructHeader *theDefclass, void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; long tsp; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif - + for (i = 0 ; i < cls->instanceSlotCount ; i++) { tsp = SlotIndex(cls->instanceTemplate[i]); - GenWrite((void *) &tsp,(UNLN) sizeof(long),(FILE *) buf); + GenWrite((void *) &tsp,sizeof(long),(FILE *) buf); } } @@ -932,22 +934,19 @@ static void BsaveTemplateSlots( SIDE EFFECTS : Defclass canonical slot map binary data written NOTES : None ***************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void BsaveSlotMap( void *theEnv, struct constructHeader *theDefclass, void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif if (cls->instanceSlotCount != 0) GenWrite((void *) cls->slotNameMap, - (UNLN) (sizeof(unsigned) * (cls->maxSlotNameID + 1)),(FILE *) buf); + (sizeof(unsigned) * (cls->maxSlotNameID + 1)),(FILE *) buf); } /************************************************************ @@ -965,7 +964,7 @@ static void BsaveHandlers( void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; - register unsigned i; + long i; BSAVE_HANDLER dummy_handler; HANDLER *hnd; @@ -986,7 +985,7 @@ static void BsaveHandlers( } else dummy_handler.actions = -1L; - GenWrite((void *) &dummy_handler,(UNLN) sizeof(BSAVE_HANDLER),(FILE *) buf); + GenWrite((void *) &dummy_handler,sizeof(BSAVE_HANDLER),(FILE *) buf); } } @@ -999,21 +998,18 @@ static void BsaveHandlers( SIDE EFFECTS : Defclass message-handler map binary data written NOTES : None ****************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void BsaveHandlerMap( void *theEnv, struct constructHeader *theDefclass, void *buf) { DEFCLASS *cls = (DEFCLASS *) theDefclass; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif GenWrite((void *) cls->handlerOrderMap, - (UNLN) (sizeof(unsigned) * cls->handlerCount),(FILE *) buf); + (sizeof(unsigned) * cls->handlerCount),(FILE *) buf); } #endif @@ -1036,7 +1032,7 @@ static void BsaveHandlerMap( static void BloadStorageObjects( void *theEnv) { - UNLN space; + size_t space; long counts[9]; if ((DefclassData(theEnv)->ClassIDMap != NULL) || (DefclassData(theEnv)->MaxClassID != 0)) @@ -1044,7 +1040,7 @@ static void BloadStorageObjects( SystemError(theEnv,"OBJBIN",1); EnvExitRouter(theEnv,EXIT_FAILURE); } - GenReadBinary(theEnv,(void *) &space,(UNLN) sizeof(UNLN)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) { ObjectBinaryData(theEnv)->ClassCount = ObjectBinaryData(theEnv)->HandlerCount = 0L; @@ -1063,46 +1059,46 @@ static void BloadStorageObjects( DefclassData(theEnv)->AvailClassID = (unsigned short) counts[8]; if (ObjectBinaryData(theEnv)->ModuleCount != 0L) { - space = (UNLN) (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); - ObjectBinaryData(theEnv)->ModuleArray = (DEFCLASS_MODULE *) genlongalloc(theEnv,space); + space = (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); + ObjectBinaryData(theEnv)->ModuleArray = (DEFCLASS_MODULE *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->ClassCount != 0L) { - space = (UNLN) (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); - ObjectBinaryData(theEnv)->DefclassArray = (DEFCLASS *) genlongalloc(theEnv,space); + space = (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); + ObjectBinaryData(theEnv)->DefclassArray = (DEFCLASS *) genalloc(theEnv,space); DefclassData(theEnv)->ClassIDMap = (DEFCLASS **) gm2(theEnv,(sizeof(DEFCLASS *) * DefclassData(theEnv)->MaxClassID)); } if (ObjectBinaryData(theEnv)->LinkCount != 0L) { - space = (UNLN) (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); - ObjectBinaryData(theEnv)->LinkArray = (DEFCLASS * *) genlongalloc(theEnv,space); + space = (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); + ObjectBinaryData(theEnv)->LinkArray = (DEFCLASS * *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->SlotCount != 0L) { - space = (UNLN) (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); - ObjectBinaryData(theEnv)->SlotArray = (SLOT_DESC *) genlongalloc(theEnv,space); + space = (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); + ObjectBinaryData(theEnv)->SlotArray = (SLOT_DESC *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->SlotNameCount != 0L) { - space = (UNLN) (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); - ObjectBinaryData(theEnv)->SlotNameArray = (SLOT_NAME *) genlongalloc(theEnv,space); + space = (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); + ObjectBinaryData(theEnv)->SlotNameArray = (SLOT_NAME *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->TemplateSlotCount != 0L) { - space = (UNLN) (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); - ObjectBinaryData(theEnv)->TmpslotArray = (SLOT_DESC * *) genlongalloc(theEnv,space); + space = (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); + ObjectBinaryData(theEnv)->TmpslotArray = (SLOT_DESC * *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->SlotNameMapCount != 0L) { - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); - ObjectBinaryData(theEnv)->MapslotArray = (unsigned *) genlongalloc(theEnv,space); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); + ObjectBinaryData(theEnv)->MapslotArray = (unsigned *) genalloc(theEnv,space); } if (ObjectBinaryData(theEnv)->HandlerCount != 0L) { - space = (UNLN) (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); - ObjectBinaryData(theEnv)->HandlerArray = (HANDLER *) genlongalloc(theEnv,space); - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); - ObjectBinaryData(theEnv)->MaphandlerArray = (unsigned *) genlongalloc(theEnv,space); + space = (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); + ObjectBinaryData(theEnv)->HandlerArray = (HANDLER *) genalloc(theEnv,space); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); + ObjectBinaryData(theEnv)->MaphandlerArray = (unsigned *) genalloc(theEnv,space); } } @@ -1118,30 +1114,30 @@ static void BloadStorageObjects( static void BloadObjects( void *theEnv) { - UNLN space; + size_t space; - GenReadBinary(theEnv,(void *) &space,(UNLN) sizeof(UNLN)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) return; if (ObjectBinaryData(theEnv)->ModuleCount != 0L) - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->ModuleCount,(unsigned) sizeof(BSAVE_DEFCLASS_MODULE),UpdateDefclassModule); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->ModuleCount,sizeof(BSAVE_DEFCLASS_MODULE),UpdateDefclassModule); if (ObjectBinaryData(theEnv)->ClassCount != 0L) { - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->ClassCount,(unsigned) sizeof(BSAVE_DEFCLASS),UpdateDefclass); - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->LinkCount,(unsigned) sizeof(DEFCLASS *),UpdateLink); - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->SlotNameCount,(unsigned) sizeof(BSAVE_SLOT_NAME),UpdateSlotName); - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->SlotCount,(unsigned) sizeof(BSAVE_SLOT_DESC),UpdateSlot); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->ClassCount,sizeof(BSAVE_DEFCLASS),UpdateDefclass); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->LinkCount,sizeof(long),UpdateLink); // 64-bit bug fix: DEFCLASS * replaced with long + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->SlotNameCount,sizeof(BSAVE_SLOT_NAME),UpdateSlotName); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->SlotCount,sizeof(BSAVE_SLOT_DESC),UpdateSlot); if (ObjectBinaryData(theEnv)->TemplateSlotCount != 0L) - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->TemplateSlotCount,(unsigned) sizeof(long),UpdateTemplateSlot); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->TemplateSlotCount,sizeof(long),UpdateTemplateSlot); if (ObjectBinaryData(theEnv)->SlotNameMapCount != 0L) { - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); GenReadBinary(theEnv,(void *) ObjectBinaryData(theEnv)->MapslotArray,space); } if (ObjectBinaryData(theEnv)->HandlerCount != 0L) { - BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->HandlerCount,(unsigned) sizeof(BSAVE_HANDLER),UpdateHandler); - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); + BloadandRefresh(theEnv,ObjectBinaryData(theEnv)->HandlerCount,sizeof(BSAVE_HANDLER),UpdateHandler); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); GenReadBinary(theEnv,(void *) ObjectBinaryData(theEnv)->MaphandlerArray,space); } UpdatePrimitiveClassesMap(theEnv); @@ -1242,7 +1238,7 @@ static void UpdateLink( long obji) { long *blink; - + blink = (long *) buf; ObjectBinaryData(theEnv)->LinkArray[obji] = DefclassPointer(*blink); } @@ -1368,12 +1364,12 @@ static void ClearBloadObjects( void *theEnv) { register long i; - UNLN space; + size_t space; - space = (unsigned long) (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); + space = (sizeof(DEFCLASS_MODULE) * ObjectBinaryData(theEnv)->ModuleCount); if (space == 0L) return; - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->ModuleArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->ModuleArray,space); ObjectBinaryData(theEnv)->ModuleArray = NULL; ObjectBinaryData(theEnv)->ModuleCount = 0L; @@ -1407,50 +1403,50 @@ static void ClearBloadObjects( DecrementSymbolCount(theEnv,ObjectBinaryData(theEnv)->SlotNameArray[i].putHandlerName); } - space = (UNLN) (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); + space = (sizeof(DEFCLASS) * ObjectBinaryData(theEnv)->ClassCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->DefclassArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->DefclassArray,space); ObjectBinaryData(theEnv)->DefclassArray = NULL; ObjectBinaryData(theEnv)->ClassCount = 0L; } - space = (UNLN) (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); + space = (sizeof(DEFCLASS *) * ObjectBinaryData(theEnv)->LinkCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->LinkArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->LinkArray,space); ObjectBinaryData(theEnv)->LinkArray = NULL; ObjectBinaryData(theEnv)->LinkCount = 0L; } - space = (UNLN) (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); + space = (sizeof(SLOT_DESC) * ObjectBinaryData(theEnv)->SlotCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotArray,space); ObjectBinaryData(theEnv)->SlotArray = NULL; ObjectBinaryData(theEnv)->SlotCount = 0L; } - space = (UNLN) (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); + space = (sizeof(SLOT_NAME) * ObjectBinaryData(theEnv)->SlotNameCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotNameArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->SlotNameArray,space); ObjectBinaryData(theEnv)->SlotNameArray = NULL; ObjectBinaryData(theEnv)->SlotNameCount = 0L; } - space = (UNLN) (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); + space = (sizeof(SLOT_DESC *) * ObjectBinaryData(theEnv)->TemplateSlotCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->TmpslotArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->TmpslotArray,space); ObjectBinaryData(theEnv)->TmpslotArray = NULL; ObjectBinaryData(theEnv)->TemplateSlotCount = 0L; } - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->SlotNameMapCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->MapslotArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->MapslotArray,space); ObjectBinaryData(theEnv)->MapslotArray = NULL; ObjectBinaryData(theEnv)->SlotNameMapCount = 0L; } @@ -1461,13 +1457,13 @@ static void ClearBloadObjects( for (i = 0L ; i < ObjectBinaryData(theEnv)->HandlerCount ; i++) DecrementSymbolCount(theEnv,ObjectBinaryData(theEnv)->HandlerArray[i].name); - space = (UNLN) (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); + space = (sizeof(HANDLER) * ObjectBinaryData(theEnv)->HandlerCount); if (space != 0L) { - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->HandlerArray,space); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->HandlerArray,space); ObjectBinaryData(theEnv)->HandlerArray = NULL; - space = (UNLN) (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); - genlongfree(theEnv,(void *) ObjectBinaryData(theEnv)->MaphandlerArray,space); + space = (sizeof(unsigned) * ObjectBinaryData(theEnv)->HandlerCount); + genfree(theEnv,(void *) ObjectBinaryData(theEnv)->MaphandlerArray,space); ObjectBinaryData(theEnv)->MaphandlerArray = NULL; ObjectBinaryData(theEnv)->HandlerCount = 0L; } diff --git a/src/objbin.h b/src/objbin.h index ee3120b..ba30744 100644 --- a/src/objbin.h +++ b/src/objbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,21 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS and */ +/* AUXILIARY_MESSAGE_HANDLERS compilation flags. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ #ifndef _H_objbin @@ -28,7 +37,7 @@ #define OBJECTBIN_DATA 33 struct objectBinaryData - { + { DEFCLASS *DefclassArray; long ModuleCount; long ClassCount; @@ -53,7 +62,6 @@ struct objectBinaryData #define DefclassPointer(i) (((i) == -1L) ? NULL : (DEFCLASS *) &ObjectBinaryData(theEnv)->DefclassArray[i]) #define DefclassIndex(cls) (((cls) == NULL) ? -1 : ((struct constructHeader *) cls)->bsaveID) - #ifdef LOCALE #undef LOCALE #endif @@ -64,10 +72,10 @@ struct objectBinaryData #define LOCALE extern #endif -LOCALE void SetupObjectsBload(void *); -LOCALE void *BloadDefclassModuleReference(void *,int); + LOCALE void SetupObjectsBload(void *); + LOCALE void *BloadDefclassModuleReference(void *,int); -#endif +#endif /* _H_objbin */ diff --git a/src/objcmp.c b/src/objcmp.c index 1643e49..9970abd 100644 --- a/src/objcmp.c +++ b/src/objcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: Object System Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -20,6 +20,18 @@ /* */ /* Added environment parameter to GenClose. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ /* ========================================= @@ -105,33 +117,33 @@ static void ReadyObjectsForCode(void *); static void MarkDefclassAndSlots(void *,struct constructHeader *,void *); static void PrintSlotNameReference(void *,FILE *,SLOT_NAME *,int,int); static void InitObjectsCode(void *,FILE *,int,int); -static int ObjectsToCode(void *,char *,int,FILE *,int,int); -static int ClassIDMapToCode(void *,char *,int,FILE *,int,int,int *); -static int ClassHashTableToCode(void *,char *,int,FILE *,int,int,int *); -static int SlotNameHashTableToCode(void *,char *,int,FILE *,int,int,int *); -static int SlotNameEntriesToCode(void *,char *,int,FILE *,int,int,int *); +static int ObjectsToCode(void *,const char *,const char *,char *,int,FILE *,int,int); +static int ClassIDMapToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int *); +static int ClassHashTableToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int *); +static int SlotNameHashTableToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int *); +static int SlotNameEntriesToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int *); static void CloseObjectFiles(void *,FILE *[SAVE_ITEMS],int [SAVE_ITEMS], struct CodeGeneratorFile [SAVE_ITEMS],int); static void DefclassModuleToCode(void *,FILE *,struct defmodule *,int,int); static void SingleDefclassToCode(void *,FILE *,int,int,DEFCLASS *,int, int,int,int,int,int,int, int,int,int,int,int,int); -static intBool InheritanceLinksToCode(void *,FILE **,char *,int,int,FILE *, +static intBool InheritanceLinksToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); -static intBool SlotsToCode(void *,FILE **,char *,int,int,FILE *, +static intBool SlotsToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); -static intBool TemplateSlotsToCode(void *,FILE **,char *,int,int,FILE *, +static intBool TemplateSlotsToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); -static intBool OrderedSlotsToCode(void *,FILE **,char *,int,int,FILE *, +static intBool OrderedSlotsToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); -static intBool HandlersToCode(void *,FILE **,char *,int,int,FILE *, +static intBool HandlersToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); -static intBool OrderedHandlersToCode(void *,FILE **,char *,int,int,FILE *, +static intBool OrderedHandlersToCode(void *,FILE **,const char *,const char *,char *,int,int,FILE *, int *,int,DEFCLASS *,int *, int *,int *,struct CodeGeneratorFile *); @@ -280,9 +292,6 @@ static void ReadyObjectsForCode( same time as the real slots - thus the references must be predetermined ************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkDefclassAndSlots( void *theEnv, struct constructHeader *vTheDefclass, @@ -290,9 +299,9 @@ static void MarkDefclassAndSlots( { DEFCLASS *theDefclass = (DEFCLASS *) vTheDefclass; MARK_INFO *markInfo = (MARK_INFO *) vTheBuffer; - register unsigned i; + long i; PACKED_LOCATION_INFO theLocationInfo; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -352,16 +361,13 @@ static void PrintSlotNameReference( SIDE EFFECTS : Writes out initialization code NOTES : None *******************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void InitObjectsCode( void *theEnv, FILE *initFP, int imageID, int maxIndices) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(maxIndices) #endif @@ -388,7 +394,9 @@ static void InitObjectsCode( *************************************************************/ static int ObjectsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -412,19 +420,21 @@ static int ObjectsToCode( itemFiles[i] = NULL; itemReopenFlags[i] = FALSE; itemCodeFiles[i].filePrefix = NULL; + itemCodeFiles[i].pathName = pathName; + itemCodeFiles[i].fileNameBuffer = fileNameBuffer; } fprintf(headerFP,"#include \"classcom.h\"\n"); fprintf(headerFP,"#include \"classini.h\"\n"); - if (ClassIDMapToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,&fileCount) + if (ClassIDMapToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,&fileCount) == FALSE) return(0); - if (ClassHashTableToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,&fileCount) + if (ClassHashTableToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,&fileCount) == FALSE) return(0); - if (SlotNameHashTableToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,&fileCount) + if (SlotNameHashTableToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,&fileCount) == FALSE) return(0); - if (SlotNameEntriesToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,&fileCount) + if (SlotNameEntriesToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,&fileCount) == FALSE) return(0); @@ -439,7 +449,7 @@ static int ObjectsToCode( EnvSetCurrentModule(theEnv,(void *) theModule); itemFiles[MODULEI] = - OpenFileIfNeeded(theEnv,itemFiles[MODULEI],fileName,fileID,imageID,&fileCount, + OpenFileIfNeeded(theEnv,itemFiles[MODULEI],fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, itemArrayVersions[MODULEI],headerFP, "DEFCLASS_MODULE",ModulePrefix(ObjectCompilerData(theEnv)->ObjectCodeItem), itemReopenFlags[MODULEI],&itemCodeFiles[MODULEI]); @@ -457,7 +467,7 @@ static int ObjectsToCode( theDefclass = (DEFCLASS *) EnvGetNextDefclass(theEnv,(void *) theDefclass)) { itemFiles[CLASSI] = - OpenFileIfNeeded(theEnv,itemFiles[CLASSI],fileName,fileID,imageID,&fileCount, + OpenFileIfNeeded(theEnv,itemFiles[CLASSI],fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, itemArrayVersions[CLASSI],headerFP, "DEFCLASS",ClassPrefix(), itemReopenFlags[CLASSI],&itemCodeFiles[CLASSI]); @@ -477,42 +487,42 @@ static int ObjectsToCode( &itemArrayVersions[CLASSI],maxIndices, &itemReopenFlags[CLASSI],&itemCodeFiles[CLASSI]); - if (InheritanceLinksToCode(theEnv,&itemFiles[LINKI],fileName,fileID,imageID, + if (InheritanceLinksToCode(theEnv,&itemFiles[LINKI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[LINKI],&itemArrayCounts[LINKI], &itemReopenFlags[LINKI],&itemCodeFiles[LINKI]) == FALSE) goto ObjectCodeError; - if (SlotsToCode(theEnv,&itemFiles[SLOTI],fileName,fileID,imageID, + if (SlotsToCode(theEnv,&itemFiles[SLOTI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[SLOTI],&itemArrayCounts[SLOTI], &itemReopenFlags[SLOTI],&itemCodeFiles[SLOTI]) == FALSE) goto ObjectCodeError; - if (TemplateSlotsToCode(theEnv,&itemFiles[TSLOTI],fileName,fileID,imageID, + if (TemplateSlotsToCode(theEnv,&itemFiles[TSLOTI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[TSLOTI],&itemArrayCounts[TSLOTI], &itemReopenFlags[TSLOTI],&itemCodeFiles[TSLOTI]) == FALSE) goto ObjectCodeError; - if (OrderedSlotsToCode(theEnv,&itemFiles[OSLOTI],fileName,fileID,imageID, + if (OrderedSlotsToCode(theEnv,&itemFiles[OSLOTI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[OSLOTI],&itemArrayCounts[OSLOTI], &itemReopenFlags[OSLOTI],&itemCodeFiles[OSLOTI]) == FALSE) goto ObjectCodeError; - if (HandlersToCode(theEnv,&itemFiles[HANDLERI],fileName,fileID,imageID, + if (HandlersToCode(theEnv,&itemFiles[HANDLERI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[HANDLERI],&itemArrayCounts[HANDLERI], &itemReopenFlags[HANDLERI],&itemCodeFiles[HANDLERI]) == FALSE) goto ObjectCodeError; - if (OrderedHandlersToCode(theEnv,&itemFiles[OHANDLERI],fileName,fileID,imageID, + if (OrderedHandlersToCode(theEnv,&itemFiles[OHANDLERI],fileName,pathName,fileNameBuffer,fileID,imageID, headerFP,&fileCount,maxIndices,theDefclass, &itemArrayVersions[OHANDLERI],&itemArrayCounts[OHANDLERI], &itemReopenFlags[OHANDLERI],&itemCodeFiles[OHANDLERI]) @@ -547,7 +557,9 @@ ObjectCodeError: ***********************************************************/ static int ClassIDMapToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -558,7 +570,7 @@ static int ClassIDMapToCode( int classIDMapArrayCount, classIDMapArrayVersion = 1; - classIDMapFile = OpenFileIfNeeded(theEnv,classIDMapFile,fileName,fileID,imageID,fileCount, + classIDMapFile = OpenFileIfNeeded(theEnv,classIDMapFile,fileName,pathName,fileNameBuffer,fileID,imageID,fileCount, classIDMapArrayVersion,headerFP, "DEFCLASS *",ClassIDPrefix(),FALSE,NULL); if (classIDMapFile == NULL) @@ -594,7 +606,9 @@ static int ClassIDMapToCode( ***********************************************************/ static int ClassHashTableToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -605,7 +619,7 @@ static int ClassHashTableToCode( int classHashArrayCount, classHashArrayVersion = 1; - classHashFile = OpenFileIfNeeded(theEnv,classHashFile,fileName,fileID,imageID,fileCount, + classHashFile = OpenFileIfNeeded(theEnv,classHashFile,fileName,pathName,fileNameBuffer,fileID,imageID,fileCount, classHashArrayVersion,headerFP, "DEFCLASS *",ClassHashPrefix(),FALSE,NULL); if (classHashFile == NULL) @@ -639,7 +653,9 @@ static int ClassHashTableToCode( ***********************************************************/ static int SlotNameHashTableToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -650,7 +666,7 @@ static int SlotNameHashTableToCode( int slotNameHashArrayCount, slotNameHashArrayVersion = 1; - slotNameHashFile = OpenFileIfNeeded(theEnv,slotNameHashFile,fileName,fileID, + slotNameHashFile = OpenFileIfNeeded(theEnv,slotNameHashFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, slotNameHashArrayVersion,headerFP, "SLOT_NAME *",SlotNameHashPrefix(),FALSE,NULL); @@ -685,7 +701,9 @@ static int SlotNameHashTableToCode( ***********************************************************/ static int SlotNameEntriesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -702,13 +720,13 @@ static int SlotNameEntriesToCode( { for (snp = DefclassData(theEnv)->SlotNameTable[i] ; snp != NULL ; snp = snp->nxt) { - slotNameFile = OpenFileIfNeeded(theEnv,slotNameFile,fileName,fileID, + slotNameFile = OpenFileIfNeeded(theEnv,slotNameFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, slotNameArrayVersion,headerFP, "SLOT_NAME",SlotNamePrefix(),FALSE,NULL); if (slotNameFile == NULL) return(FALSE); - fprintf(slotNameFile,"{ %u,1,%u,",snp->hashTableIndex,snp->id); + fprintf(slotNameFile,"{ %u,1,%d,",snp->hashTableIndex,snp->id); PrintSymbolReference(theEnv,slotNameFile,snp->name); fprintf(slotNameFile,","); PrintSymbolReference(theEnv,slotNameFile,snp->putHandlerName); @@ -908,7 +926,7 @@ static void SingleDefclassToCode( else fprintf(theFile,"NULL,"); - fprintf(theFile,"%u,%u,%u,%u,NULL,NULL,\n ", + fprintf(theFile,"%hd,%hd,%hd,%hd,NULL,NULL,\n ", theDefclass->slotCount,theDefclass->localInstanceSlotCount, theDefclass->instanceSlotCount,theDefclass->maxSlotNameID); @@ -926,7 +944,7 @@ static void SingleDefclassToCode( else fprintf(theFile,"NULL,"); - fprintf(theFile,"%u,",theDefclass->handlerCount); + fprintf(theFile,"%hd,",theDefclass->handlerCount); PrintClassReference(theEnv,theFile,theDefclass->nxtHash,imageID,maxIndices); fprintf(theFile,","); PrintBitMapReference(theEnv,theFile,theDefclass->scopeMap); @@ -965,7 +983,9 @@ static void SingleDefclassToCode( static intBool InheritanceLinksToCode( void *theEnv, FILE **classLinkFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -977,7 +997,7 @@ static intBool InheritanceLinksToCode( int *reopenClassLinkFile, struct CodeGeneratorFile *classLinkCodeFile) { - register unsigned i; + long i; int inheritanceLinkCount, linkPrinted = FALSE; @@ -988,7 +1008,7 @@ static intBool InheritanceLinksToCode( if (inheritanceLinkCount == 0) return(TRUE); - *classLinkFile = OpenFileIfNeeded(theEnv,*classLinkFile,fileName,fileID, + *classLinkFile = OpenFileIfNeeded(theEnv,*classLinkFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *classLinkArrayVersion,headerFP, "DEFCLASS *",ClassLinkPrefix(), @@ -1061,7 +1081,9 @@ static intBool InheritanceLinksToCode( static intBool SlotsToCode( void *theEnv, FILE **slotFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -1073,7 +1095,7 @@ static intBool SlotsToCode( int *reopenSlotFile, struct CodeGeneratorFile *slotCodeFile) { - register unsigned i; + long i; SLOT_DESC *sd; EXPRESSION *tmpexp; PACKED_LOCATION_INFO theLocationInfo; @@ -1081,7 +1103,7 @@ static intBool SlotsToCode( if (theDefclass->slotCount == 0) return(TRUE); - *slotFile = OpenFileIfNeeded(theEnv,*slotFile,fileName,fileID, + *slotFile = OpenFileIfNeeded(theEnv,*slotFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *slotArrayVersion,headerFP, "SLOT_DESC",SlotPrefix(), @@ -1174,7 +1196,9 @@ static intBool SlotsToCode( static intBool TemplateSlotsToCode( void *theEnv, FILE **templateSlotFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -1186,14 +1210,14 @@ static intBool TemplateSlotsToCode( int *reopenTemplateSlotFile, struct CodeGeneratorFile *templateSlotCodeFile) { - register unsigned i; + long i; SLOT_DESC *sd; PACKED_LOCATION_INFO theLocationInfo; if (theDefclass->instanceSlotCount == 0) return(TRUE); - *templateSlotFile = OpenFileIfNeeded(theEnv,*templateSlotFile,fileName,fileID, + *templateSlotFile = OpenFileIfNeeded(theEnv,*templateSlotFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *templateSlotArrayVersion,headerFP, "SLOT_DESC *",TemplateSlotPrefix(), @@ -1251,7 +1275,9 @@ static intBool TemplateSlotsToCode( static intBool OrderedSlotsToCode( void *theEnv, FILE **orderedSlotFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -1263,12 +1289,12 @@ static intBool OrderedSlotsToCode( int *reopenOrderedSlotFile, struct CodeGeneratorFile *orderedSlotCodeFile) { - register unsigned i; + long i; if (theDefclass->instanceSlotCount == 0) return(TRUE); - *orderedSlotFile = OpenFileIfNeeded(theEnv,*orderedSlotFile,fileName,fileID, + *orderedSlotFile = OpenFileIfNeeded(theEnv,*orderedSlotFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *orderedSlotArrayVersion,headerFP, "unsigned",OrderedSlotPrefix(), @@ -1320,7 +1346,9 @@ static intBool OrderedSlotsToCode( static intBool HandlersToCode( void *theEnv, FILE **handlerFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -1332,13 +1360,13 @@ static intBool HandlersToCode( int *reopenHandlerFile, struct CodeGeneratorFile *handlerCodeFile) { - register unsigned i; + long i; HANDLER *hnd; if (theDefclass->handlerCount == 0) return(TRUE); - *handlerFile = OpenFileIfNeeded(theEnv,*handlerFile,fileName,fileID, + *handlerFile = OpenFileIfNeeded(theEnv,*handlerFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *handlerArrayVersion,headerFP, "HANDLER",HandlerPrefix(),*reopenHandlerFile, @@ -1355,7 +1383,7 @@ static intBool HandlersToCode( PrintSymbolReference(theEnv,*handlerFile,hnd->name); fprintf(*handlerFile,","); PrintClassReference(theEnv,*handlerFile,hnd->cls,imageID,maxIndices); - fprintf(*handlerFile,",%d,%d,%d,",hnd->minParams,hnd->maxParams, + fprintf(*handlerFile,",%hd,%hd,%hd,",hnd->minParams,hnd->maxParams, hnd->localVarCount); ExpressionToCode(theEnv,*handlerFile,hnd->actions); fprintf(*handlerFile,",NULL }"); @@ -1399,7 +1427,9 @@ static intBool HandlersToCode( static intBool OrderedHandlersToCode( void *theEnv, FILE **orderedHandlerFile, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, int imageID, FILE *headerFP, @@ -1411,12 +1441,12 @@ static intBool OrderedHandlersToCode( int *reopenOrderedHandlerFile, struct CodeGeneratorFile *orderedHandlerCodeFile) { - register unsigned i; + long i; if (theDefclass->handlerCount == 0) return(TRUE); - *orderedHandlerFile = OpenFileIfNeeded(theEnv,*orderedHandlerFile,fileName,fileID, + *orderedHandlerFile = OpenFileIfNeeded(theEnv,*orderedHandlerFile,fileName,pathName,fileNameBuffer,fileID, imageID,fileCount, *orderedHandlerArrayVersion,headerFP, "unsigned",OrderedHandlerPrefix(), diff --git a/src/objcmp.h b/src/objcmp.h index f91d6ac..68ffb8d 100644 --- a/src/objcmp.h +++ b/src/objcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,12 +10,28 @@ /* Purpose: Object System Construct Compiler Code */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Added environment parameter to GenClose. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_objcmp @@ -36,7 +52,7 @@ #define OBJECT_COMPILER_DATA 36 struct objectCompilerData - { + { #if CONSTRUCT_COMPILER && (! RUN_TIME) struct CodeGeneratorItem *ObjectCodeItem; #endif @@ -54,9 +70,9 @@ struct objectCompilerData #define LOCALE extern #endif -LOCALE void SetupObjectsCompiler(void *); -LOCALE void PrintClassReference(void *,FILE *,DEFCLASS *,int,int); -LOCALE void DefclassCModuleReference(void *,FILE *,int,int,int); + LOCALE void SetupObjectsCompiler(void *); + LOCALE void PrintClassReference(void *,FILE *,DEFCLASS *,int,int); + LOCALE void DefclassCModuleReference(void *,FILE *,int,int,int); -#endif +#endif /* _H_objcmp */ diff --git a/src/object.h b/src/object.h index 64b5e1a..0b99d17 100644 --- a/src/object.h +++ b/src/object.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* OBJECT SYSTEM DEFINITIONS */ /*******************************************************/ @@ -10,13 +10,17 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ /*************************************************************/ #ifndef _H_object @@ -75,7 +79,7 @@ typedef struct instanceSlot INSTANCE_SLOT; struct packedClassLinks { - unsigned short classCount; + long classCount; DEFCLASS **classArray; }; @@ -93,7 +97,7 @@ struct defclass unsigned reactive : 1; unsigned traceInstances : 1; unsigned traceSlots : 1; - unsigned short id; + unsigned id; unsigned busy, hashTableIndex; PACKED_CLASS_LINKS directSuperclasses, @@ -102,15 +106,15 @@ struct defclass SLOT_DESC *slots, **instanceTemplate; unsigned *slotNameMap; - unsigned slotCount, - localInstanceSlotCount, - instanceSlotCount, - maxSlotNameID; + short slotCount; + short localInstanceSlotCount; + short instanceSlotCount; + short maxSlotNameID; INSTANCE_TYPE *instanceList, *instanceListBottom; HANDLER *handlers; unsigned *handlerOrderMap; - unsigned handlerCount; + short handlerCount; DEFCLASS *nxtHash; BITMAP_HN *scopeMap; char traversalRecord[TRAVERSAL_BYTES]; @@ -125,8 +129,8 @@ struct classLink struct slotName { unsigned hashTableIndex, - use, - id; + use; + short id; SYMBOL_HN *name, *putHandlerName; struct slotName *nxt; @@ -138,7 +142,7 @@ struct instanceSlot SLOT_DESC *desc; unsigned valueRequired : 1; unsigned override : 1; - unsigned type : 6; + unsigned short type; void *value; }; @@ -179,7 +183,6 @@ struct instance unsigned initializeInProgress : 1; unsigned reteSynchronized : 1; SYMBOL_HN *name; - int depth; unsigned hashTableIndex; unsigned busy; DEFCLASS *cls; @@ -199,15 +202,15 @@ struct messageHandler unsigned busy; SYMBOL_HN *name; DEFCLASS *cls; - int minParams, - maxParams, - localVarCount; + short minParams; + short maxParams; + short localVarCount; EXPRESSION *actions; char *ppForm; struct userData *usrData; }; -#endif +#endif /* _H_object */ diff --git a/src/objrtbin.c b/src/objrtbin.c index c2bbdbc..6df11e5 100644 --- a/src/objrtbin.c +++ b/src/objrtbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -11,7 +11,7 @@ /* Object Pattern Network */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -23,6 +23,13 @@ /* ResetObjectMatchTimeTags did not pass in the */ /* environment argument when BLOAD_ONLY was set. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ /*************************************************************/ /* ========================================= @@ -57,8 +64,9 @@ typedef struct bsaveObjectPatternNode { unsigned multifieldNode : 1; unsigned endSlot : 1; + unsigned selector : 1; unsigned whichField : 8; - unsigned leaveFields : 8; + unsigned short leaveFields; unsigned slotNameID; long networkTest, nextLevel, @@ -109,7 +117,7 @@ static void DeallocateObjectReteBinaryData(void *); ***************************************** */ /*********************************************************** - NAME : SetupObjectsBload + NAME : SetupObjectPatternsBload DESCRIPTION : Initializes data structures and routines for binary loads of generic function constructs @@ -135,7 +143,7 @@ globle void SetupObjectPatternsBload( ClearBloadObjectPatterns); #endif } - + /***********************************************************/ /* DeallocateObjectReteBinaryData: Deallocates environment */ /* data for object rete binary functionality. */ @@ -144,17 +152,17 @@ static void DeallocateObjectReteBinaryData( void *theEnv) { #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) - unsigned long space; + size_t space; long i; for (i = 0; i < ObjectReteBinaryData(theEnv)->AlphaNodeCount; i++) - { DestroyAlphaBetaMemory(theEnv,ObjectReteBinaryData(theEnv)->AlphaArray[i].header.alphaMemory); } + { DestroyAlphaMemory(theEnv,&ObjectReteBinaryData(theEnv)->AlphaArray[i].header,FALSE); } space = ObjectReteBinaryData(theEnv)->AlphaNodeCount * sizeof(struct objectAlphaNode); - if (space != 0) genlongfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->AlphaArray,space); + if (space != 0) genfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->AlphaArray,space); space = ObjectReteBinaryData(theEnv)->PatternNodeCount * sizeof(struct objectPatternNode); - if (space != 0) genlongfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->PatternArray,space); + if (space != 0) genfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->PatternArray,space); #endif } @@ -234,12 +242,12 @@ static void BsaveStorageObjectPatterns( void *theEnv, FILE *fp) { - UNLN space; + size_t space; space = sizeof(long) * 2; - GenWrite(&space,(UNLN) sizeof(UNLN),fp); - GenWrite(&ObjectReteBinaryData(theEnv)->AlphaNodeCount,(UNLN) sizeof(long),fp); - GenWrite(&ObjectReteBinaryData(theEnv)->PatternNodeCount,(UNLN) sizeof(long),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&ObjectReteBinaryData(theEnv)->AlphaNodeCount,sizeof(long),fp); + GenWrite(&ObjectReteBinaryData(theEnv)->PatternNodeCount,sizeof(long),fp); } /*************************************************** @@ -257,7 +265,7 @@ static void BsaveObjectPatterns( void *theEnv, FILE *fp) { - UNLN space; + size_t space; OBJECT_ALPHA_NODE *alphaPtr; OBJECT_PATTERN_NODE *patternPtr; BSAVE_OBJECT_ALPHA_NODE dummyAlpha; @@ -265,7 +273,7 @@ static void BsaveObjectPatterns( space = (sizeof(BSAVE_OBJECT_ALPHA_NODE) * ObjectReteBinaryData(theEnv)->AlphaNodeCount) + (sizeof(BSAVE_OBJECT_PATTERN_NODE) * ObjectReteBinaryData(theEnv)->PatternNodeCount); - GenWrite(&space,(UNLN) sizeof(UNLN),fp); + GenWrite(&space,sizeof(size_t),fp); /* ========================================== Write out the alpha terminal pattern nodes @@ -273,7 +281,7 @@ static void BsaveObjectPatterns( alphaPtr = ObjectNetworkTerminalPointer(theEnv); while (alphaPtr != NULL) { - AssignBsavePatternHeaderValues(&dummyAlpha.header,&alphaPtr->header); + AssignBsavePatternHeaderValues(theEnv,&dummyAlpha.header,&alphaPtr->header); dummyAlpha.classbmp = (long) alphaPtr->classbmp->bucket; if (alphaPtr->slotbmp != NULL) dummyAlpha.slotbmp = (long) alphaPtr->slotbmp->bucket; @@ -282,7 +290,7 @@ static void BsaveObjectPatterns( dummyAlpha.patternNode = BsaveObjectPatternIndex(alphaPtr->patternNode); dummyAlpha.nxtInGroup = BsaveObjectAlphaIndex(alphaPtr->nxtInGroup); dummyAlpha.nxtTerminal = BsaveObjectAlphaIndex(alphaPtr->nxtTerminal); - GenWrite(&dummyAlpha,(UNLN) sizeof(BSAVE_OBJECT_ALPHA_NODE),fp); + GenWrite(&dummyAlpha,sizeof(BSAVE_OBJECT_ALPHA_NODE),fp); alphaPtr = alphaPtr->nxtTerminal; } @@ -296,6 +304,7 @@ static void BsaveObjectPatterns( dummyPattern.whichField = patternPtr->whichField; dummyPattern.leaveFields = patternPtr->leaveFields; dummyPattern.endSlot = patternPtr->endSlot; + dummyPattern.selector = patternPtr->selector; dummyPattern.slotNameID = patternPtr->slotNameID; dummyPattern.networkTest = HashedExpressionIndex(theEnv,patternPtr->networkTest); dummyPattern.nextLevel = BsaveObjectPatternIndex(patternPtr->nextLevel); @@ -303,7 +312,7 @@ static void BsaveObjectPatterns( dummyPattern.leftNode = BsaveObjectPatternIndex(patternPtr->leftNode); dummyPattern.rightNode = BsaveObjectPatternIndex(patternPtr->rightNode); dummyPattern.alphaNode = BsaveObjectAlphaIndex(patternPtr->alphaNode); - GenWrite(&dummyPattern,(UNLN) sizeof(BSAVE_OBJECT_PATTERN_NODE),fp); + GenWrite(&dummyPattern,sizeof(BSAVE_OBJECT_PATTERN_NODE),fp); if (patternPtr->nextLevel == NULL) { @@ -342,10 +351,10 @@ static void BsaveObjectPatterns( static void BloadStorageObjectPatterns( void *theEnv) { - UNLN space; + size_t space; long counts[2]; - GenReadBinary(theEnv,(void *) &space,(UNLN) sizeof(UNLN)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); GenReadBinary(theEnv,(void *) counts,space); ObjectReteBinaryData(theEnv)->AlphaNodeCount = counts[0]; ObjectReteBinaryData(theEnv)->PatternNodeCount = counts[1]; @@ -354,15 +363,15 @@ static void BloadStorageObjectPatterns( ObjectReteBinaryData(theEnv)->AlphaArray = NULL; else { - space = (UNLN) (ObjectReteBinaryData(theEnv)->AlphaNodeCount * sizeof(OBJECT_ALPHA_NODE)); - ObjectReteBinaryData(theEnv)->AlphaArray = (OBJECT_ALPHA_NODE *) genlongalloc(theEnv,space); + space = (ObjectReteBinaryData(theEnv)->AlphaNodeCount * sizeof(OBJECT_ALPHA_NODE)); + ObjectReteBinaryData(theEnv)->AlphaArray = (OBJECT_ALPHA_NODE *) genalloc(theEnv,space); } if (ObjectReteBinaryData(theEnv)->PatternNodeCount == 0L) ObjectReteBinaryData(theEnv)->PatternArray = NULL; else { - space = (UNLN) (ObjectReteBinaryData(theEnv)->PatternNodeCount * sizeof(OBJECT_PATTERN_NODE)); - ObjectReteBinaryData(theEnv)->PatternArray = (OBJECT_PATTERN_NODE *) genlongalloc(theEnv,space); + space = (ObjectReteBinaryData(theEnv)->PatternNodeCount * sizeof(OBJECT_PATTERN_NODE)); + ObjectReteBinaryData(theEnv)->PatternArray = (OBJECT_PATTERN_NODE *) genalloc(theEnv,space); } } @@ -379,17 +388,30 @@ static void BloadStorageObjectPatterns( static void BloadObjectPatterns( void *theEnv) { - UNLN space; + size_t space; + long i; - GenReadBinary(theEnv,(void *) &space,(UNLN) sizeof(UNLN)); + GenReadBinary(theEnv,(void *) &space,sizeof(size_t)); if (space == 0L) return; /* ================================================ Read in the alpha and intermediate pattern nodes ================================================ */ - BloadandRefresh(theEnv,ObjectReteBinaryData(theEnv)->AlphaNodeCount,(unsigned) sizeof(BSAVE_OBJECT_ALPHA_NODE),UpdateAlpha); - BloadandRefresh(theEnv,ObjectReteBinaryData(theEnv)->PatternNodeCount,(unsigned) sizeof(BSAVE_OBJECT_PATTERN_NODE),UpdatePattern); + BloadandRefresh(theEnv,ObjectReteBinaryData(theEnv)->AlphaNodeCount,sizeof(BSAVE_OBJECT_ALPHA_NODE),UpdateAlpha); + BloadandRefresh(theEnv,ObjectReteBinaryData(theEnv)->PatternNodeCount,sizeof(BSAVE_OBJECT_PATTERN_NODE),UpdatePattern); + + for (i = 0; i < ObjectReteBinaryData(theEnv)->PatternNodeCount; i++) + { + if ((ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel != NULL) && + (ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel->selector)) + { + AddHashedPatternNode(theEnv,ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel, + &ObjectReteBinaryData(theEnv)->PatternArray[i], + ObjectReteBinaryData(theEnv)->PatternArray[i].networkTest->type, + ObjectReteBinaryData(theEnv)->PatternArray[i].networkTest->value); + } + } /* ======================= Set the global pointers @@ -468,6 +490,7 @@ static void UpdatePattern( op->whichField = bop->whichField; op->leaveFields = bop->leaveFields; op->endSlot = bop->endSlot; + op->selector = bop->selector; op->matchTimeTag = 0L; op->slotNameID = bop->slotNameID; op->networkTest = HashedExpressionPointer(bop->networkTest); @@ -492,9 +515,21 @@ static void UpdatePattern( static void ClearBloadObjectPatterns( void *theEnv) { - UNLN space; + size_t space; register long i; + for (i = 0; i < ObjectReteBinaryData(theEnv)->PatternNodeCount; i++) + { + if ((ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel != NULL) && + (ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel->selector)) + { + RemoveHashedPatternNode(theEnv,ObjectReteBinaryData(theEnv)->PatternArray[i].lastLevel, + &ObjectReteBinaryData(theEnv)->PatternArray[i], + ObjectReteBinaryData(theEnv)->PatternArray[i].networkTest->type, + ObjectReteBinaryData(theEnv)->PatternArray[i].networkTest->value); + } + } + /* ================================================ All instances have been deleted by this point so we don't need to worry about clearing partial @@ -509,12 +544,12 @@ static void ClearBloadObjectPatterns( if (ObjectReteBinaryData(theEnv)->AlphaNodeCount != 0L) { - space = (UNLN) (ObjectReteBinaryData(theEnv)->AlphaNodeCount * sizeof(OBJECT_ALPHA_NODE)); - genlongfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->AlphaArray,space); + space = (ObjectReteBinaryData(theEnv)->AlphaNodeCount * sizeof(OBJECT_ALPHA_NODE)); + genfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->AlphaArray,space); ObjectReteBinaryData(theEnv)->AlphaArray = NULL; ObjectReteBinaryData(theEnv)->AlphaNodeCount = 0; - space = (UNLN) (ObjectReteBinaryData(theEnv)->PatternNodeCount * sizeof(OBJECT_PATTERN_NODE)); - genlongfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->PatternArray,space); + space = (ObjectReteBinaryData(theEnv)->PatternNodeCount * sizeof(OBJECT_PATTERN_NODE)); + genfree(theEnv,(void *) ObjectReteBinaryData(theEnv)->PatternArray,space); ObjectReteBinaryData(theEnv)->PatternArray = NULL; ObjectReteBinaryData(theEnv)->PatternNodeCount = 0; } diff --git a/src/objrtbin.h b/src/objrtbin.h index 11cc705..f248ddf 100644 --- a/src/objrtbin.h +++ b/src/objrtbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,16 @@ /* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ +/* ResetObjectMatchTimeTags did not pass in the */ +/* environment argument when BLOAD_ONLY was set. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ /*************************************************************/ #ifndef _H_objrtbin @@ -29,7 +39,7 @@ #define OBJECTRETEBIN_DATA 34 struct objectReteBinaryData - { + { long AlphaNodeCount; long PatternNodeCount; OBJECT_ALPHA_NODE *AlphaArray; @@ -49,11 +59,11 @@ struct objectReteBinaryData #define LOCALE extern #endif -LOCALE void SetupObjectPatternsBload(void *); + LOCALE void SetupObjectPatternsBload(void *); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM */ -#endif +#endif /* _H_objrtbin */ diff --git a/src/objrtbld.c b/src/objrtbld.c index d5e5bd1..53937d7 100644 --- a/src/objrtbld.c +++ b/src/objrtbld.c @@ -1,29 +1,45 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 01/13/15 */ /* */ /* OBJECT PATTERN MATCHER MODULE */ /*******************************************************/ -/**************************************************************/ -/* Purpose: RETE Network Parsing Interface for Objects */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* */ -/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ -/* */ -/* Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ -/* Renamed BOOLEAN macro type to intBool. */ -/* */ -/**************************************************************/ +/*************************************************************/ +/* Purpose: RETE Network Parsing Interface for Objects */ +/* */ +/* Principal Programmer(s): */ +/* Brian L. Dantes */ +/* */ +/* Contributing Programmer(s): */ +/* */ +/* Revision History: */ +/* */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/*************************************************************/ /* ========================================= ***************************************** EXTERNAL DEFINITIONS @@ -103,20 +119,20 @@ ***************************************** */ static intBool PatternParserFind(SYMBOL_HN *); -static struct lhsParseNode *ObjectLHSParse(void *,char *,struct token *); +static struct lhsParseNode *ObjectLHSParse(void *,const char *,struct token *); static intBool ReorderAndAnalyzeObjectPattern(void *,struct lhsParseNode *); static struct patternNodeHeader *PlaceObjectPattern(void *,struct lhsParseNode *); static OBJECT_PATTERN_NODE *FindObjectPatternNode(OBJECT_PATTERN_NODE *,struct lhsParseNode *, - OBJECT_PATTERN_NODE **,unsigned); + OBJECT_PATTERN_NODE **,unsigned,unsigned); static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode(void *,struct lhsParseNode *,OBJECT_PATTERN_NODE *, - OBJECT_PATTERN_NODE *,unsigned); + OBJECT_PATTERN_NODE *,unsigned,unsigned); static void DetachObjectPattern(void *,struct patternNodeHeader *); static void ClearObjectPatternMatches(void *,OBJECT_ALPHA_NODE *); static void RemoveObjectPartialMatches(void *,INSTANCE_TYPE *,struct patternNodeHeader *); static intBool CheckDuplicateSlots(void *,struct lhsParseNode *,SYMBOL_HN *); -static struct lhsParseNode *ParseClassRestriction(void *,char *,struct token *); -static struct lhsParseNode *ParseNameRestriction(void *,char *,struct token *); -static struct lhsParseNode *ParseSlotRestriction(void *,char *,struct token *,CONSTRAINT_RECORD *,int); +static struct lhsParseNode *ParseClassRestriction(void *,const char *,struct token *); +static struct lhsParseNode *ParseNameRestriction(void *,const char *,struct token *); +static struct lhsParseNode *ParseSlotRestriction(void *,const char *,struct token *,CONSTRAINT_RECORD *,int); static CLASS_BITMAP *NewClassBitMap(void *,int,int); static void InitializeClassBitMap(void *,CLASS_BITMAP *,int); static void DeleteIntermediateClassBitMap(void *,CLASS_BITMAP *); @@ -136,7 +152,7 @@ static struct lhsParseNode *FilterObjectPattern(void *,struct patternParser *, static BITMAP_HN *FormSlotBitMap(void *,struct lhsParseNode *); static struct lhsParseNode *RemoveSlotExistenceTests(void *,struct lhsParseNode *,BITMAP_HN **); static struct lhsParseNode *CreateInitialObjectPattern(void *); -static EXPRESSION *ObjectMatchDelayParse(void *,EXPRESSION *,char *); +static EXPRESSION *ObjectMatchDelayParse(void *,EXPRESSION *,const char *); static void MarkObjectPtnIncrementalReset(void *,struct patternNodeHeader *,int); static void ObjectIncrementalReset(void *); @@ -182,7 +198,7 @@ globle void SetupObjectPatternStuff( =========================================================================== */ newPtr = get_struct(theEnv,patternParser); - + newPtr->name = "objects"; newPtr->priority = 20; newPtr->entityType = &InstanceData(theEnv)->InstanceInfo; @@ -190,7 +206,7 @@ globle void SetupObjectPatternStuff( newPtr->recognizeFunction = PatternParserFind; newPtr->parseFunction = ObjectLHSParse; newPtr->postAnalysisFunction = ReorderAndAnalyzeObjectPattern; - newPtr->addPatternFunction = PlaceObjectPattern; + newPtr->addPatternFunction = PlaceObjectPattern; newPtr->removePatternFunction = DetachObjectPattern; newPtr->genJNConstantFunction = NULL; newPtr->replaceGetJNValueFunction = ReplaceGetJNObjectValue; @@ -215,7 +231,7 @@ globle void SetupObjectPatternStuff( #endif AddPatternParser(theEnv,newPtr); - + EnvDefineFunction2(theEnv,"object-pattern-match-delay",'u', PTIEF ObjectMatchDelay,"ObjectMatchDelay",NULL); @@ -302,15 +318,12 @@ static intBool PatternParserFind( <name-constraint> ::= (name <constraint>) <slot-constraint> ::= (<slot-name> <constraint>*) ************************************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static struct lhsParseNode *ObjectLHSParse( void *theEnv, - char *readSource, + const char *readSource, struct token *lastToken) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(lastToken) #endif struct token theToken; @@ -445,7 +458,7 @@ static struct lhsParseNode *ObjectLHSParse( } DeleteIntermediateClassBitMap(theEnv,tmpset); clsset = PackClassBitMap(theEnv,clsset); - firstNode->userData = AddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); + firstNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); IncrementBitMapCount(firstNode->userData); DeleteIntermediateClassBitMap(theEnv,clsset); DecrementIndentDepth(theEnv,7); @@ -528,7 +541,7 @@ static intBool ReorderAndAnalyzeObjectPattern( cls = LookupDefclassInScope(theEnv,ValueToString(rexp->value)); if (cls != NULL) { - if ((cls->id <= clsset->maxid) ? TestBitMap(clsset->map,cls->id) : FALSE) + if ((cls->id <= (unsigned) clsset->maxid) ? TestBitMap(clsset->map,cls->id) : FALSE) SetBitMap(tmpset->map,cls->id); } rexp = rexp->nextArg; @@ -620,13 +633,13 @@ static intBool ReorderAndAnalyzeObjectPattern( PrintErrorID(theEnv,"OBJRTBLD",3,TRUE); DeleteIntermediateClassBitMap(theEnv,tmpset); EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern #"); - PrintLongInteger(theEnv,WERROR,(long) topNode->pattern); + PrintLongInteger(theEnv,WERROR,(long long) topNode->pattern); EnvPrintRouter(theEnv,WERROR,".\n"); return(TRUE); } clsset = PackClassBitMap(theEnv,tmpset); DeleteClassBitMap(theEnv,(void *) bitmap_node->userData); - bitmap_node->userData = AddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); + bitmap_node->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); IncrementBitMapCount(bitmap_node->userData); DeleteIntermediateClassBitMap(theEnv,clsset); } @@ -655,29 +668,34 @@ static struct patternNodeHeader *PlaceObjectPattern( OBJECT_ALPHA_NODE *newAlphaNode; unsigned endSlot; BITMAP_HN *newClassBitMap,*newSlotBitMap; + struct expr *rightHash; + + /*========================================================*/ + /* Get the top of the object pattern network and prepare */ + /* for the traversal to look for shareable pattern nodes. */ + /*========================================================*/ - /* ===================================================== - Get the top of the object pattern network and prepare - for the traversal to look for shareable pattern nodes - ===================================================== */ currentLevel = ObjectNetworkPointer(theEnv); lastLevel = NULL; - /* ================================================== - Remove slot existence tests from the pattern since - these are accounted for by the class bitmap - and find the class and slot bitmaps - ================================================== */ + /*====================================================*/ + /* Remove slot existence tests from the pattern since */ + /* these are accounted for by the class bitmap and */ + /* find the class and slot bitmaps. */ + /*====================================================*/ + + rightHash = thePattern->rightHash; + newSlotBitMap = FormSlotBitMap(theEnv,thePattern->right); thePattern->right = RemoveSlotExistenceTests(theEnv,thePattern->right,&newClassBitMap); thePattern = thePattern->right; - /* ========================================= - Loop until all fields in the pattern have - been added to the pattern network - Process the bitmap node ONLY if it is - the only node in the pattern - ========================================= */ + /*=========================================================*/ + /* Loop until all fields in the pattern have been added to */ + /* the pattern network. Process the bitmap node ONLY if it */ + /* is the only node in the pattern. */ + /*=========================================================*/ + do { if (thePattern->multifieldSlot) @@ -686,34 +704,47 @@ static struct patternNodeHeader *PlaceObjectPattern( thePattern = thePattern->bottom; } - /* ========================================== - Determine if the last pattern field within - a multifield slot is being processed. - ========================================== */ + /*============================================*/ + /* Determine if the last pattern field within */ + /* a multifield slot is being processed. */ + /*============================================*/ if (((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) && (thePattern->right == NULL) && (tempPattern != NULL)) - endSlot = TRUE; + { endSlot = TRUE; } else - endSlot = FALSE; - - /* ====================================== - Is there a node in the pattern network - that can be reused (shared)? - ====================================== */ - newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot); - - /* ============================================== - If the pattern node cannot be shared, then add - a new pattern node to the pattern network - ============================================== */ + { endSlot = FALSE; } + + /*========================================*/ + /* Is there a node in the pattern network */ + /* that can be reused (shared)? */ + /*========================================*/ + + newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,FALSE); + + /*================================================*/ + /* If the pattern node cannot be shared, then add */ + /* a new pattern node to the pattern network. */ + /*================================================*/ + if (newNode == NULL) - newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot); + { newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,FALSE); } + + if (thePattern->constantSelector != NULL) + { + currentLevel = newNode->nextLevel; + lastLevel = newNode; + newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,TRUE); + + if (newNode == NULL) + { newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,TRUE); } + } + + /*=======================================================*/ + /* Move on to the next field in the pattern to be added. */ + /*=======================================================*/ - /* ==================================================== - Move on to the next field in the pattern to be added - ==================================================== */ if ((thePattern->right == NULL) && (tempPattern != NULL)) { thePattern = tempPattern; @@ -726,19 +757,23 @@ static struct patternNodeHeader *PlaceObjectPattern( } while ((thePattern != NULL) ? (thePattern->userData == NULL) : FALSE); - /* =============================================== - Return the leaf node of the newly added pattern - =============================================== */ + /*==================================================*/ + /* Return the leaf node of the newly added pattern. */ + /*==================================================*/ + newAlphaNode = lastLevel->alphaNode; while (newAlphaNode != NULL) { if ((newClassBitMap == newAlphaNode->classbmp) && - (newSlotBitMap == newAlphaNode->slotbmp)) + (newSlotBitMap == newAlphaNode->slotbmp) && + IdenticalExpression(newAlphaNode->header.rightHash,rightHash)) return((struct patternNodeHeader *) newAlphaNode); newAlphaNode = newAlphaNode->nxtInGroup; } + newAlphaNode = get_struct(theEnv,objectAlphaNode); InitializePatternHeader(theEnv,&newAlphaNode->header); + newAlphaNode->header.rightHash = AddHashedExpression(theEnv,rightHash); newAlphaNode->matchTimeTag = 0L; newAlphaNode->patternNode = lastLevel; newAlphaNode->classbmp = newClassBitMap; @@ -778,21 +813,32 @@ static OBJECT_PATTERN_NODE *FindObjectPatternNode( OBJECT_PATTERN_NODE *listOfNodes, struct lhsParseNode *thePattern, OBJECT_PATTERN_NODE **nodeSlotGroup, - unsigned endSlot) + unsigned endSlot, + unsigned constantSelector) { + struct expr *compareTest; *nodeSlotGroup = NULL; - /* ======================================================== - Loop through the nodes at the given level in the pattern - network looking for a node that can be reused (shared) - ======================================================== */ + if (constantSelector) + { compareTest = thePattern->constantValue; } + else if (thePattern->constantSelector != NULL) + { compareTest = thePattern->constantSelector; } + else + { compareTest = thePattern->networkTest; } + + /*==========================================================*/ + /* Loop through the nodes at the given level in the pattern */ + /* network looking for a node that can be reused (shared). */ + /*==========================================================*/ + while (listOfNodes != NULL) { - /* ======================================================= - A object pattern node can be shared if the slot name is - the same, the test is on the same field in the pattern, - and the network test expressions are the same - ======================================================= */ + /*=========================================================*/ + /* A object pattern node can be shared if the slot name is */ + /* the same, the test is on the same field in the pattern, */ + /* and the network test expressions are the same. */ + /*=========================================================*/ + if (((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) ? listOfNodes->multifieldNode : (listOfNodes->multifieldNode == 0)) { @@ -800,14 +846,15 @@ static OBJECT_PATTERN_NODE *FindObjectPatternNode( (thePattern->index == (int) listOfNodes->whichField) && (thePattern->singleFieldsAfter == listOfNodes->leaveFields) && (endSlot == listOfNodes->endSlot) && - IdenticalExpression(listOfNodes->networkTest,thePattern->networkTest)) + IdenticalExpression(listOfNodes->networkTest,compareTest)) return(listOfNodes); } - /* ============================================ - Find the beginning of a group of nodes with - the same slot name testing on the same field - ============================================ */ + /*===============================================*/ + /* Find the beginning of a group of nodes with */ + /* the same slot name testing on the same field. */ + /*===============================================*/ + if ((*nodeSlotGroup == NULL) && (thePattern->index == (int) listOfNodes->whichField) && (thePattern->slotNumber == (int) listOfNodes->slotNameID)) @@ -815,9 +862,10 @@ static OBJECT_PATTERN_NODE *FindObjectPatternNode( listOfNodes = listOfNodes->rightNode; } - /* ============================================ - A shareable pattern node could not be found. - ============================================ */ + /*==============================================*/ + /* A shareable pattern node could not be found. */ + /*==============================================*/ + return(NULL); } @@ -843,7 +891,8 @@ static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode( struct lhsParseNode *thePattern, OBJECT_PATTERN_NODE *nodeSlotGroup, OBJECT_PATTERN_NODE *upperLevel, - unsigned endSlot) + unsigned endSlot, + unsigned constantSelector) { OBJECT_PATTERN_NODE *newNode,*prvNode,*curNode; @@ -857,30 +906,48 @@ static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode( newNode->leftNode = NULL; newNode->bsaveID = 0L; - /* ======================================================== - Install the expression associated with this pattern node - ======================================================== */ - newNode->networkTest = AddHashedExpression(theEnv,(EXPRESSION *) thePattern->networkTest); + if ((thePattern->constantSelector != NULL) && (! constantSelector)) + { newNode->selector = TRUE; } + else + { newNode->selector = FALSE; } + + /*===========================================================*/ + /* Install the expression associated with this pattern node. */ + /*===========================================================*/ + + if (constantSelector) + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantValue); } + else if (thePattern->constantSelector != NULL) + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantSelector); } + else + { newNode->networkTest = AddHashedExpression(theEnv,thePattern->networkTest); } + newNode->whichField = thePattern->index; newNode->leaveFields = thePattern->singleFieldsAfter; - /* ====================================== - Install the slot name for the new node - ====================================== */ + /*=========================================*/ + /* Install the slot name for the new node. */ + /*=========================================*/ + newNode->slotNameID = (unsigned) thePattern->slotNumber; if ((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) newNode->multifieldNode = TRUE; newNode->endSlot = endSlot; - /* ============================================ - Set the upper level pointer for the new node - ============================================ */ + /*===============================================*/ + /* Set the upper level pointer for the new node. */ + /*===============================================*/ + newNode->lastLevel = upperLevel; - /* ============================================ - If there are no nodes with this slot name on - this level, simply prepend it to the front - ============================================ */ + if ((upperLevel != NULL) && (upperLevel->selector)) + { AddHashedPatternNode(theEnv,upperLevel,newNode,newNode->networkTest->type,newNode->networkTest->value); } + + /*==============================================*/ + /* If there are no nodes with this slot name on */ + /* this level, simply prepend it to the front. */ + /*==============================================*/ + if (nodeSlotGroup == NULL) { if (upperLevel == NULL) @@ -982,27 +1049,29 @@ static void DetachObjectPattern( OBJECT_ALPHA_NODE *alphaPtr,*prv,*terminalPtr; OBJECT_PATTERN_NODE *patternPtr,*upperLevel; - /* ================================================== - Get rid of any matches stored in the alpha memory. - ================================================== */ + /*====================================================*/ + /* Get rid of any matches stored in the alpha memory. */ + /*====================================================*/ + alphaPtr = (OBJECT_ALPHA_NODE *) thePattern; ClearObjectPatternMatches(theEnv,alphaPtr); - /* ======================================= - Unmark the classes to which the pattern - is applicable and unmark the class and - slot id maps so that they can become - ephemeral - ======================================= */ + /*========================================================*/ + /* Unmark the classes to which the pattern is applicable */ + /* and unmark the class and slot id maps so that they can */ + /* become ephemeral. */ + /*========================================================*/ + MarkBitMapClassesBusy(theEnv,alphaPtr->classbmp,-1); DeleteClassBitMap(theEnv,alphaPtr->classbmp); if (alphaPtr->slotbmp != NULL) - DecrementBitMapCount(theEnv,alphaPtr->slotbmp); + { DecrementBitMapCount(theEnv,alphaPtr->slotbmp); } + + /*=========================================*/ + /* Only continue deleting this pattern if */ + /* this is the last alpha memory attached. */ + /*=========================================*/ - /* ====================================== - Only continue deleting this pattern if - this is the last alpha memory attached - ====================================== */ prv = NULL; terminalPtr = ObjectNetworkTerminalPointer(theEnv); while (terminalPtr != alphaPtr) @@ -1010,10 +1079,11 @@ static void DetachObjectPattern( prv = terminalPtr; terminalPtr = terminalPtr->nxtTerminal; } + if (prv == NULL) - SetObjectNetworkTerminalPointer(theEnv,terminalPtr->nxtTerminal); + { SetObjectNetworkTerminalPointer(theEnv,terminalPtr->nxtTerminal); } else - prv->nxtTerminal = terminalPtr->nxtTerminal; + { prv->nxtTerminal = terminalPtr->nxtTerminal; } prv = NULL; terminalPtr = alphaPtr->patternNode->alphaNode; @@ -1022,11 +1092,13 @@ static void DetachObjectPattern( prv = terminalPtr; terminalPtr = terminalPtr->nxtInGroup; } + if (prv == NULL) { if (alphaPtr->nxtInGroup != NULL) { alphaPtr->patternNode->alphaNode = alphaPtr->nxtInGroup; + RemoveHashedExpression(theEnv,alphaPtr->header.rightHash); rtn_struct(theEnv,objectAlphaNode,alphaPtr); return; } @@ -1034,19 +1106,22 @@ static void DetachObjectPattern( else { prv->nxtInGroup = alphaPtr->nxtInGroup; + RemoveHashedExpression(theEnv,alphaPtr->header.rightHash); rtn_struct(theEnv,objectAlphaNode,alphaPtr); return; } alphaPtr->patternNode->alphaNode = NULL; + RemoveHashedExpression(theEnv,alphaPtr->header.rightHash); + upperLevel = alphaPtr->patternNode; rtn_struct(theEnv,objectAlphaNode,alphaPtr); - upperLevel = alphaPtr->patternNode; if (upperLevel->nextLevel != NULL) return; /*==============================================================*/ /* Loop until all appropriate pattern nodes have been detached. */ /*==============================================================*/ + while (upperLevel != NULL) { if ((upperLevel->leftNode == NULL) && @@ -1058,16 +1133,22 @@ static void DetachObjectPattern( /* above this one, because no other patterns are */ /* dependent upon this node. */ /*===============================================*/ + patternPtr = upperLevel; upperLevel = patternPtr->lastLevel; + if (upperLevel == NULL) SetObjectNetworkPointer(theEnv,NULL); else { + if (upperLevel->selector) + { RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + upperLevel->nextLevel = NULL; if (upperLevel->alphaNode != NULL) upperLevel = NULL; } + RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest); rtn_struct(theEnv,objectPatternNode,patternPtr); } @@ -1078,7 +1159,13 @@ static void DetachObjectPattern( /* be checked preceding it. Remove the pattern node, */ /* but do not detach any nodes above this one. */ /*====================================================*/ + patternPtr = upperLevel; + + if ((patternPtr->lastLevel != NULL) && + (patternPtr->lastLevel->selector)) + { RemoveHashedPatternNode(theEnv,patternPtr->lastLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + upperLevel->leftNode->rightNode = upperLevel->rightNode; if (upperLevel->rightNode != NULL) { upperLevel->rightNode->leftNode = upperLevel->leftNode; } @@ -1094,12 +1181,18 @@ static void DetachObjectPattern( /* does have one succeeding it. Remove the pattern */ /* node, but do not detach any nodes above this one. */ /*====================================================*/ + patternPtr = upperLevel; upperLevel = upperLevel->lastLevel; if (upperLevel == NULL) { SetObjectNetworkPointer(theEnv,patternPtr->rightNode); } else - { upperLevel->nextLevel = patternPtr->rightNode; } + { + if (upperLevel->selector) + { RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); } + + upperLevel->nextLevel = patternPtr->rightNode; + } patternPtr->rightNode->leftNode = NULL; RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest); @@ -1245,13 +1338,13 @@ static intBool CheckDuplicateSlots( **********************************************************/ static struct lhsParseNode *ParseClassRestriction( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken) { struct lhsParseNode *tmpNode; SYMBOL_HN *rln; CONSTRAINT_RECORD *rv; - + rv = GetConstraintRecord(theEnv); rv->anyAllowed = 0; rv->symbolsAllowed = 1; @@ -1297,13 +1390,13 @@ static struct lhsParseNode *ParseClassRestriction( **********************************************************/ static struct lhsParseNode *ParseNameRestriction( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken) { struct lhsParseNode *tmpNode; SYMBOL_HN *rln; CONSTRAINT_RECORD *rv; - + rv = GetConstraintRecord(theEnv); rv->anyAllowed = 0; rv->instanceNamesAllowed = 1; @@ -1357,7 +1450,7 @@ static struct lhsParseNode *ParseNameRestriction( ***************************************************/ static struct lhsParseNode *ParseSlotRestriction( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, CONSTRAINT_RECORD *slotConstraints, int multip) @@ -1495,14 +1588,11 @@ static void DeleteIntermediateClassBitMap( OR CE. The use count prevents having to make duplicate copies of the bitmap ******************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void *CopyClassBitMap( void *theEnv, void *gset) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -1658,7 +1748,8 @@ static intBool ProcessClassRestriction( { if (chk->type == SYMBOL) { - chk->value = (void *) LookupDefclassInScope(theEnv,ValueToString(chk->value)); + //chk->value = (void *) LookupDefclassInScope(theEnv,ValueToString(chk->value)); + chk->value = (void *) LookupDefclassByMdlOrScope(theEnv,ValueToString(chk->value)); if (chk->value == NULL) { PrintErrorID(theEnv,"OBJRTBLD",5,FALSE); @@ -1966,7 +2057,7 @@ static BITMAP_HN *FormSlotBitMap( ============================================ */ for (node = thePattern ; node != NULL ; node = node->right) SetBitMap(bmp->map,node->slotNumber); - hshBmp = (BITMAP_HN *) AddBitMap(theEnv,(void *) bmp,SlotBitMapSize(bmp)); + hshBmp = (BITMAP_HN *) EnvAddBitMap(theEnv,(void *) bmp,SlotBitMapSize(bmp)); rm(theEnv,(void *) bmp,size); return(hshBmp); } @@ -2168,7 +2259,7 @@ static struct lhsParseNode *CreateInitialObjectPattern( clsset = PackClassBitMap(theEnv,clsset); topNode = GetLHSParseNode(theEnv); - topNode->userData = AddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); + topNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset)); IncrementBitMapCount(topNode->userData); DeleteIntermediateClassBitMap(theEnv,clsset); topNode->type = SF_WILDCARD; @@ -2198,7 +2289,7 @@ static struct lhsParseNode *CreateInitialObjectPattern( static EXPRESSION *ObjectMatchDelayParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token tkn; @@ -2231,15 +2322,12 @@ static EXPRESSION *ObjectMatchDelayParse( thus marked for initialization by PlaceObjectPattern ***************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void MarkObjectPtnIncrementalReset( void *theEnv, struct patternNodeHeader *thePattern, int value) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -2264,7 +2352,7 @@ static void ObjectIncrementalReset( void *theEnv) { INSTANCE_TYPE *ins; - + for (ins = InstanceData(theEnv)->InstanceList ; ins != NULL ; ins = ins->nxtList) ObjectNetworkAction(theEnv,OBJECT_ASSERT,(INSTANCE_TYPE *) ins,-1); } diff --git a/src/objrtbld.h b/src/objrtbld.h index 852ef07..db98643 100644 --- a/src/objrtbld.h +++ b/src/objrtbld.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* OBJECT PATTERN MATCHER MODULE */ /*******************************************************/ @@ -10,15 +10,35 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_objrtbld @@ -36,11 +56,11 @@ #define LOCALE extern #endif -LOCALE void SetupObjectPatternStuff(void *); + LOCALE void SetupObjectPatternStuff(void *); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM */ -#endif +#endif /* _H_objrtbld */ diff --git a/src/objrtcmp.c b/src/objrtcmp.c index d16c5ae..4ba8830 100644 --- a/src/objrtcmp.c +++ b/src/objrtcmp.c @@ -1,27 +1,36 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* OBJECT PATTERN NETWORK CONSTRUCTS-TO-C MODULE */ /*******************************************************/ -/**************************************************************/ -/* Purpose: Saves object pattern network for constructs-to-c */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ -/* Added environment parameter to GenClose. */ -/* */ -/**************************************************************/ +/*************************************************************/ +/* Purpose: Saves object pattern network for constructs-to-c */ +/* */ +/* Principal Programmer(s): */ +/* Brian L. Dantes */ +/* */ +/* Contributing Programmer(s): */ +/* */ +/* Revision History: */ +/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Added environment parameter to GenClose. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/*************************************************************/ /* ========================================= ***************************************** EXTERNAL DEFINITIONS @@ -61,10 +70,10 @@ static void BeforeObjectPatternsToCode(void *); static OBJECT_PATTERN_NODE *GetNextObjectPatternNode(OBJECT_PATTERN_NODE *); static void InitObjectPatternsCode(void *,FILE *,int,int); -static int ObjectPatternsToCode(void *,char *,int,FILE *,int,int); +static int ObjectPatternsToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void IntermediatePatternNodeReference(void *,OBJECT_PATTERN_NODE *,FILE *,int,int); -static int IntermediatePatternNodesToCode(void *,char *,int,FILE *,int,int,int); -static int AlphaPatternNodesToCode(void *,char *,int,FILE *,int,int,int); +static int IntermediatePatternNodesToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int); +static int AlphaPatternNodesToCode(void *,const char *,const char *,char *,int,FILE *,int,int,int); /* ========================================= ***************************************** @@ -251,19 +260,21 @@ static void InitObjectPatternsCode( ***********************************************************/ static int ObjectPatternsToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, int maxIndices) { int version; - - version = IntermediatePatternNodesToCode(theEnv,fileName,fileID, - headerFP,imageID,maxIndices,1); + + version = IntermediatePatternNodesToCode(theEnv,fileName,pathName,fileNameBuffer, + fileID,headerFP,imageID,maxIndices,1); if (version == 0) return(0); - if (! AlphaPatternNodesToCode(theEnv,fileName,fileID,headerFP,imageID,maxIndices,version)) + if (! AlphaPatternNodesToCode(theEnv,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID,maxIndices,version)) return(0); return(1); } @@ -319,7 +330,9 @@ static void IntermediatePatternNodeReference( *************************************************************/ static int IntermediatePatternNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -343,7 +356,7 @@ static int IntermediatePatternNodesToCode( /* ================================= Dump the pattern node structures. ================================= */ - if ((fp = NewCFile(theEnv,fileName,fileID,version,FALSE)) == NULL) + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,version,FALSE)) == NULL) return(0); newHeader = TRUE; @@ -361,8 +374,9 @@ static int IntermediatePatternNodesToCode( ObjectPNPrefix(),imageID,arrayVersion); newHeader = FALSE; } - fprintf(fp,"{0,%u,%u,%u,%u,0L,%u,",thePattern->multifieldNode, + fprintf(fp,"{0,%u,%u,%u,%u,%u,0L,%u,",thePattern->multifieldNode, thePattern->endSlot, + thePattern->selector, thePattern->whichField, thePattern->leaveFields, thePattern->slotNameID); @@ -392,7 +406,7 @@ static int IntermediatePatternNodesToCode( arrayVersion++; if (thePattern != NULL) { - if ((fp = NewCFile(theEnv,fileName,fileID,version,FALSE)) == NULL) + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,version,FALSE)) == NULL) return(0); newHeader = TRUE; } @@ -421,7 +435,9 @@ static int IntermediatePatternNodesToCode( ***********************************************************/ static int AlphaPatternNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -443,7 +459,7 @@ static int AlphaPatternNodesToCode( /* ================================= Dump the pattern node structures. ================================= */ - if ((fp = NewCFile(theEnv,fileName,fileID,version,FALSE)) == NULL) + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,version,FALSE)) == NULL) return(0); newHeader = TRUE; @@ -490,7 +506,7 @@ static int AlphaPatternNodesToCode( arrayVersion++; if (thePattern != NULL) { - if ((fp = NewCFile(theEnv,fileName,fileID,version,FALSE)) == NULL) + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,fileID,version,FALSE)) == NULL) return(0); newHeader = TRUE; } diff --git a/src/objrtcmp.h b/src/objrtcmp.h index 349d895..2bda4e6 100644 --- a/src/objrtcmp.h +++ b/src/objrtcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,15 +10,26 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Added environment parameter to GenClose. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_objrtcmp @@ -41,12 +52,12 @@ #define LOCALE extern #endif -LOCALE void ObjectPatternsCompilerSetup(void *); -LOCALE void ObjectPatternNodeReference(void *,void *,FILE *,int,int); + LOCALE void ObjectPatternsCompilerSetup(void *); + LOCALE void ObjectPatternNodeReference(void *,void *,FILE *,int,int); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM && (! RUN_TIME) && CONSTRUCT_COMPILER */ -#endif +#endif /* _H_objrtcmp */ diff --git a/src/objrtfnx.c b/src/objrtfnx.c index ccae59c..23c23b3 100644 --- a/src/objrtfnx.c +++ b/src/objrtfnx.c @@ -1,28 +1,40 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INFERENCE ENGINE OBJECT ACCESS ROUTINES MODULE */ /*******************************************************/ -/**************************************************************/ -/* Purpose: RETE Network Interface for Objects */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ -/* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ -/* Renamed BOOLEAN macro type to intBool. */ -/* */ -/**************************************************************/ +/*************************************************************/ +/* Purpose: RETE Network Interface for Objects */ +/* */ +/* Principal Programmer(s): */ +/* Brian L. Dantes */ +/* */ +/* Contributing Programmer(s): */ +/* */ +/* Revision History: */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/*************************************************************/ /* ========================================= ***************************************** EXTERNAL DEFINITIONS @@ -72,30 +84,30 @@ ========================================= ***************************************** */ -static void PrintObjectGetVarJN1(void *,char *,void *); +static void PrintObjectGetVarJN1(void *,const char *,void *); static intBool ObjectGetVarJNFunction1(void *,void *,DATA_OBJECT *); -static void PrintObjectGetVarJN2(void *,char *,void *); +static void PrintObjectGetVarJN2(void *,const char *,void *); static intBool ObjectGetVarJNFunction2(void *,void *,DATA_OBJECT *); -static void PrintObjectGetVarPN1(void *,char *,void *); +static void PrintObjectGetVarPN1(void *,const char *,void *); static intBool ObjectGetVarPNFunction1(void *,void *,DATA_OBJECT *); -static void PrintObjectGetVarPN2(void *,char *,void *); +static void PrintObjectGetVarPN2(void *,const char *,void *); static intBool ObjectGetVarPNFunction2(void *,void *,DATA_OBJECT *); -static void PrintObjectCmpConstant(void *,char *,void *); -static void PrintSlotLengthTest(void *,char *,void *); +static void PrintObjectCmpConstant(void *,const char *,void *); +static void PrintSlotLengthTest(void *,const char *,void *); static intBool SlotLengthTestFunction(void *,void *,DATA_OBJECT *); -static void PrintPNSimpleCompareFunction1(void *,char *,void *); +static void PrintPNSimpleCompareFunction1(void *,const char *,void *); static intBool PNSimpleCompareFunction1(void *,void *,DATA_OBJECT *); -static void PrintPNSimpleCompareFunction2(void *,char *,void *); +static void PrintPNSimpleCompareFunction2(void *,const char *,void *); static intBool PNSimpleCompareFunction2(void *,void *,DATA_OBJECT *); -static void PrintPNSimpleCompareFunction3(void *,char *,void *); +static void PrintPNSimpleCompareFunction3(void *,const char *,void *); static intBool PNSimpleCompareFunction3(void *,void *,DATA_OBJECT *); -static void PrintJNSimpleCompareFunction1(void *,char *,void *); +static void PrintJNSimpleCompareFunction1(void *,const char *,void *); static intBool JNSimpleCompareFunction1(void *,void *,DATA_OBJECT *); -static void PrintJNSimpleCompareFunction2(void *,char *,void *); +static void PrintJNSimpleCompareFunction2(void *,const char *,void *); static intBool JNSimpleCompareFunction2(void *,void *,DATA_OBJECT *); -static void PrintJNSimpleCompareFunction3(void *,char *,void *); +static void PrintJNSimpleCompareFunction3(void *,const char *,void *); static intBool JNSimpleCompareFunction3(void *,void *,DATA_OBJECT *); -static void GetPatternObjectAndMarks(void *,int,INSTANCE_TYPE **,struct multifieldMarker **); +static void GetPatternObjectAndMarks(void *,int,int,int,INSTANCE_TYPE **,struct multifieldMarker **); static void GetObjectValueGeneral(void *,DATA_OBJECT *,INSTANCE_TYPE *, struct multifieldMarker *,struct ObjectMatchVar1 *); static void GetObjectValueSimple(void *,DATA_OBJECT *,INSTANCE_TYPE *,struct ObjectMatchVar2 *); @@ -128,89 +140,89 @@ globle void InstallObjectPrimitives( PrintObjectGetVarJN1, PrintObjectGetVarJN1,NULL, ObjectGetVarJNFunction1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord objectGVInfo2 = { "OBJ_GET_SLOT_JNVAR2", OBJ_GET_SLOT_JNVAR2,0,1,0, PrintObjectGetVarJN2, PrintObjectGetVarJN2,NULL, ObjectGetVarJNFunction2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord objectGVPNInfo1 = { "OBJ_GET_SLOT_PNVAR1", OBJ_GET_SLOT_PNVAR1,0,1,0, PrintObjectGetVarPN1, PrintObjectGetVarPN1,NULL, ObjectGetVarPNFunction1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord objectGVPNInfo2 = { "OBJ_GET_SLOT_PNVAR2", OBJ_GET_SLOT_PNVAR2,0,1,0, PrintObjectGetVarPN2, PrintObjectGetVarPN2,NULL, ObjectGetVarPNFunction2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord objectCmpConstantInfo = { "OBJ_PN_CONSTANT", OBJ_PN_CONSTANT,0,1,1, PrintObjectCmpConstant, PrintObjectCmpConstant,NULL, ObjectCmpConstantFunction, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord lengthTestInfo = { "OBJ_SLOT_LENGTH", OBJ_SLOT_LENGTH,0,1,0, PrintSlotLengthTest, PrintSlotLengthTest,NULL, SlotLengthTestFunction, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord pNSimpleCompareInfo1 = { "OBJ_PN_CMP1", OBJ_PN_CMP1,0,1,1, PrintPNSimpleCompareFunction1, PrintPNSimpleCompareFunction1,NULL, PNSimpleCompareFunction1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord pNSimpleCompareInfo2 = { "OBJ_PN_CMP2", OBJ_PN_CMP2,0,1,1, PrintPNSimpleCompareFunction2, PrintPNSimpleCompareFunction2,NULL, PNSimpleCompareFunction2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord pNSimpleCompareInfo3 = { "OBJ_PN_CMP3", OBJ_PN_CMP3,0,1,1, PrintPNSimpleCompareFunction3, PrintPNSimpleCompareFunction3,NULL, PNSimpleCompareFunction3, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord jNSimpleCompareInfo1 = { "OBJ_JN_CMP1", OBJ_JN_CMP1,0,1,1, PrintJNSimpleCompareFunction1, PrintJNSimpleCompareFunction1,NULL, JNSimpleCompareFunction1, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord jNSimpleCompareInfo2 = { "OBJ_JN_CMP2", OBJ_JN_CMP2,0,1,1, PrintJNSimpleCompareFunction2, PrintJNSimpleCompareFunction2,NULL, JNSimpleCompareFunction2, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; struct entityRecord jNSimpleCompareInfo3 = { "OBJ_JN_CMP3", OBJ_JN_CMP3,0,1,1, PrintJNSimpleCompareFunction3, PrintJNSimpleCompareFunction3,NULL, JNSimpleCompareFunction3, - NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; AllocateEnvironmentData(theEnv,OBJECT_RETE_DATA,sizeof(struct objectReteData),DeallocateObjectReteData); ObjectReteData(theEnv)->CurrentObjectSlotLength = 1; - memcpy(&ObjectReteData(theEnv)->ObjectGVInfo1,&objectGVInfo1,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->ObjectGVInfo1,&objectGVInfo1,sizeof(struct entityRecord)); memcpy(&ObjectReteData(theEnv)->ObjectGVInfo2,&objectGVInfo2,sizeof(struct entityRecord)); memcpy(&ObjectReteData(theEnv)->ObjectGVPNInfo1,&objectGVPNInfo1,sizeof(struct entityRecord)); memcpy(&ObjectReteData(theEnv)->ObjectGVPNInfo2,&objectGVPNInfo2,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->ObjectCmpConstantInfo,&objectCmpConstantInfo,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->LengthTestInfo,&lengthTestInfo,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo1,&pNSimpleCompareInfo1,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo2,&pNSimpleCompareInfo2,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo3,&pNSimpleCompareInfo3,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo1,&jNSimpleCompareInfo1,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo2,&jNSimpleCompareInfo2,sizeof(struct entityRecord)); - memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo3,&jNSimpleCompareInfo3,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->ObjectCmpConstantInfo,&objectCmpConstantInfo,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->LengthTestInfo,&lengthTestInfo,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo1,&pNSimpleCompareInfo1,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo2,&pNSimpleCompareInfo2,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->PNSimpleCompareInfo3,&pNSimpleCompareInfo3,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo1,&jNSimpleCompareInfo1,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo2,&jNSimpleCompareInfo2,sizeof(struct entityRecord)); + memcpy(&ObjectReteData(theEnv)->JNSimpleCompareInfo3,&jNSimpleCompareInfo3,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&ObjectReteData(theEnv)->ObjectGVInfo1,OBJ_GET_SLOT_JNVAR1); InstallPrimitive(theEnv,&ObjectReteData(theEnv)->ObjectGVInfo2,OBJ_GET_SLOT_JNVAR2); @@ -225,7 +237,7 @@ globle void InstallObjectPrimitives( InstallPrimitive(theEnv,&ObjectReteData(theEnv)->JNSimpleCompareInfo2,OBJ_JN_CMP2); InstallPrimitive(theEnv,&ObjectReteData(theEnv)->JNSimpleCompareInfo3,OBJ_JN_CMP3); } - + /*****************************************************/ /* DeallocateObjectReteData: Deallocates environment */ /* data for the object rete network. */ @@ -234,15 +246,15 @@ static void DeallocateObjectReteData( void *theEnv) { OBJECT_PATTERN_NODE *theNetwork; - + #if BLOAD || BLOAD_AND_BSAVE if (Bloaded(theEnv)) return; #endif - + theNetwork = ObjectReteData(theEnv)->ObjectPatternNetworkPointer; DestroyObjectPatternNetwork(theEnv,theNetwork); } - + /****************************************************************/ /* DestroyObjectPatternNetwork: Deallocates the data structures */ /* associated with the object pattern network. */ @@ -252,22 +264,22 @@ static void DestroyObjectPatternNetwork( OBJECT_PATTERN_NODE *thePattern) { OBJECT_PATTERN_NODE *patternPtr; - + if (thePattern == NULL) return; - + while (thePattern != NULL) { patternPtr = thePattern->rightNode; - + DestroyObjectPatternNetwork(theEnv,thePattern->nextLevel); DestroyObjectAlphaNodes(theEnv,thePattern->alphaNode); -#if ! RUN_TIME +#if ! RUN_TIME rtn_struct(theEnv,objectPatternNode,thePattern); -#endif +#endif thePattern = patternPtr; } } - + /************************************************************/ /* DestroyObjectAlphaNodes: Deallocates the data structures */ /* associated with the object alpha nodes. */ @@ -277,18 +289,19 @@ static void DestroyObjectAlphaNodes( OBJECT_ALPHA_NODE *theNode) { OBJECT_ALPHA_NODE *nodePtr; - + if (theNode == NULL) return; - + while (theNode != NULL) { nodePtr = theNode->nxtInGroup; - - DestroyAlphaBetaMemory(theEnv,theNode->header.alphaMemory); + + DestroyAlphaMemory(theEnv,&theNode->header,FALSE); + #if ! RUN_TIME rtn_struct(theEnv,objectAlphaNode,theNode); #endif - + theNode = nodePtr; } } @@ -365,12 +378,9 @@ globle intBool ObjectCmpConstantFunction( ========================================= ***************************************** */ -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintObjectGetVarJN1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -381,27 +391,27 @@ static void PrintObjectGetVarJN1( if (hack->objectAddress) { EnvPrintRouter(theEnv,logicalName,"(obj-ptr "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern); } else if (hack->allFields) { EnvPrintRouter(theEnv,logicalName,"(obj-slot-contents "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->whichSlot))); } else { EnvPrintRouter(theEnv,logicalName,"(obj-slot-var "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->whichSlot))); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichField); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichField); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -417,19 +427,16 @@ static intBool ObjectGetVarJNFunction1( struct ObjectMatchVar1 *hack; INSTANCE_TYPE *theInstance; struct multifieldMarker *theMarks; - + hack = (struct ObjectMatchVar1 *) ValueToBitMap(theValue); - GetPatternObjectAndMarks(theEnv,((int) hack->whichPattern) - 1,&theInstance,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->whichPattern),hack->lhs,hack->rhs,&theInstance,&theMarks); GetObjectValueGeneral(theEnv,theResult,theInstance,theMarks,hack); return(TRUE); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintObjectGetVarJN2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -437,22 +444,22 @@ static void PrintObjectGetVarJN2( hack = (struct ObjectMatchVar2 *) ValueToBitMap(theValue); EnvPrintRouter(theEnv,logicalName,"(obj-slot-quick-var "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->whichSlot))); if (hack->fromBeginning) { EnvPrintRouter(theEnv,logicalName," B"); - PrintLongInteger(theEnv,logicalName,(long) (hack->beginningOffset + 1)); + PrintLongInteger(theEnv,logicalName,(long long) (hack->beginningOffset + 1)); } if (hack->fromEnd) { EnvPrintRouter(theEnv,logicalName," E"); - PrintLongInteger(theEnv,logicalName,(long) (hack->endOffset + 1)); + PrintLongInteger(theEnv,logicalName,(long long) (hack->endOffset + 1)); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -468,19 +475,16 @@ static intBool ObjectGetVarJNFunction2( struct ObjectMatchVar2 *hack; INSTANCE_TYPE *theInstance; struct multifieldMarker *theMarks; - + hack = (struct ObjectMatchVar2 *) ValueToBitMap(theValue); - GetPatternObjectAndMarks(theEnv,((int) hack->whichPattern) - 1,&theInstance,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->whichPattern),hack->lhs,hack->rhs,&theInstance,&theMarks); GetObjectValueSimple(theEnv,theResult,theInstance,hack); return(TRUE); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintObjectGetVarPN1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -500,11 +504,11 @@ static void PrintObjectGetVarPN1( EnvPrintRouter(theEnv,logicalName,"(ptn-obj-slot-var "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->whichSlot))); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->whichField); + PrintLongInteger(theEnv,logicalName,(long long) hack->whichField); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -524,12 +528,9 @@ static intBool ObjectGetVarPNFunction1( return(TRUE); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintObjectGetVarPN2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -541,16 +542,16 @@ static void PrintObjectGetVarPN2( if (hack->fromBeginning) { EnvPrintRouter(theEnv,logicalName," B"); - PrintLongInteger(theEnv,logicalName,(long) (hack->beginningOffset + 1)); + PrintLongInteger(theEnv,logicalName,(long long) (hack->beginningOffset + 1)); } if (hack->fromEnd) { EnvPrintRouter(theEnv,logicalName," E"); - PrintLongInteger(theEnv,logicalName,(long) (hack->endOffset + 1)); + PrintLongInteger(theEnv,logicalName,(long long) (hack->endOffset + 1)); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -570,12 +571,9 @@ static intBool ObjectGetVarPNFunction2( return(TRUE); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintObjectCmpConstant( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -590,13 +588,13 @@ static void PrintObjectCmpConstant( else { EnvPrintRouter(theEnv,logicalName,hack->fromBeginning ? "B" : "E"); - PrintLongInteger(theEnv,logicalName,(long) hack->offset); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset); EnvPrintRouter(theEnv,logicalName," "); PrintExpression(theEnv,logicalName,GetFirstArgument()); } EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -604,12 +602,9 @@ static void PrintObjectCmpConstant( #endif } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintSlotLengthTest( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -622,10 +617,10 @@ static void PrintSlotLengthTest( EnvPrintRouter(theEnv,logicalName,"= "); else EnvPrintRouter(theEnv,logicalName,">= "); - PrintLongInteger(theEnv,logicalName,(long) hack->minLength); + PrintLongInteger(theEnv,logicalName,(long long) hack->minLength); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -651,12 +646,9 @@ static intBool SlotLengthTestFunction( return(TRUE); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintPNSimpleCompareFunction1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -671,7 +663,7 @@ static void PrintPNSimpleCompareFunction1( EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -702,12 +694,9 @@ static intBool PNSimpleCompareFunction1( return(rv); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintPNSimpleCompareFunction2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -719,12 +708,12 @@ static void PrintPNSimpleCompareFunction2( EnvPrintRouter(theEnv,logicalName,hack->pass ? "p " : "n "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->firstSlot))); EnvPrintRouter(theEnv,logicalName,hack->fromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->offset); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -757,12 +746,9 @@ static intBool PNSimpleCompareFunction2( return(rv); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintPNSimpleCompareFunction3( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -774,14 +760,14 @@ static void PrintPNSimpleCompareFunction3( EnvPrintRouter(theEnv,logicalName,hack->pass ? "p " : "n "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->firstSlot))); EnvPrintRouter(theEnv,logicalName,hack->firstFromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->firstOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->firstOffset); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,hack->secondFromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->secondOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->secondOffset); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -814,12 +800,9 @@ static intBool PNSimpleCompareFunction3( return(rv); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintJNSimpleCompareFunction1( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -829,16 +812,16 @@ static void PrintJNSimpleCompareFunction1( EnvPrintRouter(theEnv,logicalName,"(jslot-cmp1 "); EnvPrintRouter(theEnv,logicalName,hack->pass ? "p " : "n "); - PrintLongInteger(theEnv,logicalName,(long) hack->firstPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->firstPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->firstSlot))); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->secondPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->secondPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -858,9 +841,9 @@ static intBool JNSimpleCompareFunction1( INSTANCE_SLOT *is1,*is2; hack = (struct ObjectCmpJoinSingleSlotVars1 *) ValueToBitMap(theValue); - GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern) - 1,&ins1,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern),hack->firstPatternLHS,hack->firstPatternRHS,&ins1,&theMarks); is1 = GetInsSlot(ins1,hack->firstSlot); - GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern) - 1,&ins2,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern),hack->secondPatternLHS,hack->secondPatternRHS,&ins2,&theMarks); is2 = GetInsSlot(ins2,hack->secondSlot); if (is1->type != is2->type) rv = hack->fail; @@ -873,12 +856,9 @@ static intBool JNSimpleCompareFunction1( return(rv); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintJNSimpleCompareFunction2( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -888,18 +868,18 @@ static void PrintJNSimpleCompareFunction2( EnvPrintRouter(theEnv,logicalName,"(jslot-cmp2 "); EnvPrintRouter(theEnv,logicalName,hack->pass ? "p " : "n "); - PrintLongInteger(theEnv,logicalName,(long) hack->firstPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->firstPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->firstSlot))); EnvPrintRouter(theEnv,logicalName,hack->fromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->offset); + PrintLongInteger(theEnv,logicalName,(long long) hack->offset); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->secondPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->secondPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -920,10 +900,10 @@ static intBool JNSimpleCompareFunction2( INSTANCE_SLOT *is2; hack = (struct ObjectCmpJoinSingleSlotVars2 *) ValueToBitMap(theValue); - GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern) - 1,&ins1,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern),hack->firstPatternLHS,hack->firstPatternRHS,&ins1,&theMarks); GetInsMultiSlotField(&f1,ins1,(unsigned) hack->firstSlot, (unsigned) hack->fromBeginning,(unsigned) hack->offset); - GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern) - 1,&ins2,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern),hack->secondPatternLHS,hack->secondPatternRHS,&ins2,&theMarks); is2 = GetInsSlot(ins2,hack->secondSlot); if (f1.type != is2->type) rv = hack->fail; @@ -936,12 +916,9 @@ static intBool JNSimpleCompareFunction2( return(rv); } -#if IBM_TBC && (! DEVELOPER) -#pragma argsused -#endif static void PrintJNSimpleCompareFunction3( void *theEnv, - char *logicalName, + const char *logicalName, void *theValue) { #if DEVELOPER @@ -951,20 +928,20 @@ static void PrintJNSimpleCompareFunction3( EnvPrintRouter(theEnv,logicalName,"(jslot-cmp3 "); EnvPrintRouter(theEnv,logicalName,hack->pass ? "p " : "n "); - PrintLongInteger(theEnv,logicalName,(long) hack->firstPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->firstPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->firstSlot))); EnvPrintRouter(theEnv,logicalName,hack->firstFromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->firstOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->firstOffset); EnvPrintRouter(theEnv,logicalName," "); - PrintLongInteger(theEnv,logicalName,(long) hack->secondPattern); + PrintLongInteger(theEnv,logicalName,(long long) hack->secondPattern); EnvPrintRouter(theEnv,logicalName," "); EnvPrintRouter(theEnv,logicalName,ValueToString(FindIDSlotName(theEnv,(unsigned) hack->secondSlot))); EnvPrintRouter(theEnv,logicalName,hack->secondFromBeginning ? " B" : " E"); - PrintLongInteger(theEnv,logicalName,(long) hack->secondOffset); + PrintLongInteger(theEnv,logicalName,(long long) hack->secondOffset); EnvPrintRouter(theEnv,logicalName,")"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #pragma unused(logicalName) #pragma unused(theValue) @@ -984,11 +961,11 @@ static intBool JNSimpleCompareFunction3( FIELD f1,f2; hack = (struct ObjectCmpJoinSingleSlotVars3 *) ValueToBitMap(theValue); - GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern) - 1,&ins1,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->firstPattern),hack->firstPatternLHS,hack->firstPatternRHS,&ins1,&theMarks); GetInsMultiSlotField(&f1,ins1,(unsigned) hack->firstSlot, (unsigned) hack->firstFromBeginning, (unsigned) hack->firstOffset); - GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern) - 1,&ins2,&theMarks); + GetPatternObjectAndMarks(theEnv,((int) hack->secondPattern),hack->secondPatternLHS,hack->secondPatternRHS,&ins2,&theMarks); GetInsMultiSlotField(&f2,ins2,(unsigned) hack->secondSlot, (unsigned) hack->secondFromBeginning, (unsigned) hack->secondOffset); @@ -1020,10 +997,26 @@ static intBool JNSimpleCompareFunction3( static void GetPatternObjectAndMarks( void *theEnv, int pattern, + int lhs, + int rhs, INSTANCE_TYPE **theInstance, struct multifieldMarker **theMarkers) { - if (EngineData(theEnv)->GlobalRHSBinds == NULL) + if (lhs) + { + *theInstance = (INSTANCE_TYPE *) + get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,pattern)->matchingItem; + *theMarkers = + get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,pattern)->markers; + } + else if (rhs) + { + *theInstance = (INSTANCE_TYPE *) + get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,pattern)->matchingItem; + *theMarkers = + get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,pattern)->markers; + } + else if (EngineData(theEnv)->GlobalRHSBinds == NULL) { *theInstance = (INSTANCE_TYPE *) get_nth_pm_match(EngineData(theEnv)->GlobalLHSBinds,pattern)->matchingItem; @@ -1032,7 +1025,8 @@ static void GetPatternObjectAndMarks( } else if ((((int) EngineData(theEnv)->GlobalJoin->depth) - 1) == pattern) { - *theInstance = (INSTANCE_TYPE *) get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; + *theInstance = (INSTANCE_TYPE *) + get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->matchingItem; *theMarkers = get_nth_pm_match(EngineData(theEnv)->GlobalRHSBinds,0)->markers; } else @@ -1068,7 +1062,7 @@ static void GetObjectValueGeneral( { long field, extent; /* 6.04 Bug Fix */ INSTANCE_SLOT **insSlot,*basisSlot; - + if (matchVar->objectAddress) { result->type = INSTANCE_ADDRESS; @@ -1175,7 +1169,7 @@ static void GetObjectValueSimple( INSTANCE_SLOT **insSlot,*basisSlot; SEGMENT *segmentPtr; FIELD *fieldPtr; - + insSlot = &theInstance->slotAddresses [theInstance->cls->slotNameMap[matchVar->whichSlot] - 1]; diff --git a/src/objrtfnx.h b/src/objrtfnx.h index 5616fd2..d92231b 100644 --- a/src/objrtfnx.h +++ b/src/objrtfnx.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -21,6 +21,17 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_objrtfnx @@ -51,16 +62,20 @@ struct ObjectMatchVar1 unsigned short whichField; unsigned objectAddress : 1; unsigned allFields : 1; + unsigned lhs : 1; + unsigned rhs : 1; }; struct ObjectMatchVar2 { unsigned short whichSlot; unsigned short whichPattern; + unsigned short beginningOffset; + unsigned short endOffset; unsigned fromBeginning : 1; - unsigned beginningOffset : 7; unsigned fromEnd : 1; - unsigned endOffset : 7; + unsigned lhs : 1; + unsigned rhs : 1; }; struct ObjectMatchLength @@ -71,7 +86,7 @@ struct ObjectMatchLength struct ObjectCmpPNConstant { - unsigned offset : 7; + unsigned short offset; unsigned pass : 1; unsigned fail : 1; unsigned general : 1; @@ -90,9 +105,9 @@ struct ObjectCmpPNSingleSlotVars2 { unsigned short firstSlot; unsigned short secondSlot; + unsigned short offset; unsigned pass : 1; unsigned fail : 1; - unsigned offset : 7; unsigned fromBeginning : 1; }; @@ -100,11 +115,11 @@ struct ObjectCmpPNSingleSlotVars3 { unsigned short firstSlot; unsigned short secondSlot; + unsigned short firstOffset; + unsigned short secondOffset; unsigned pass : 1; unsigned fail : 1; - unsigned firstOffset : 7; unsigned firstFromBeginning : 1; - unsigned secondOffset : 7; unsigned secondFromBeginning : 1; }; @@ -116,6 +131,10 @@ struct ObjectCmpJoinSingleSlotVars1 unsigned short secondPattern; unsigned pass : 1; unsigned fail : 1; + unsigned int firstPatternLHS : 1; + unsigned int firstPatternRHS : 1; + unsigned int secondPatternLHS : 1; + unsigned int secondPatternRHS : 1; }; struct ObjectCmpJoinSingleSlotVars2 @@ -124,10 +143,14 @@ struct ObjectCmpJoinSingleSlotVars2 unsigned short secondSlot; unsigned short firstPattern; unsigned short secondPattern; + unsigned short offset; unsigned pass : 1; unsigned fromBeginning : 1; - unsigned offset : 7; unsigned fail : 1; + unsigned int firstPatternLHS : 1; + unsigned int firstPatternRHS : 1; + unsigned int secondPatternLHS : 1; + unsigned int secondPatternRHS : 1; }; struct ObjectCmpJoinSingleSlotVars3 @@ -136,40 +159,44 @@ struct ObjectCmpJoinSingleSlotVars3 unsigned short secondSlot; unsigned short firstPattern; unsigned short secondPattern; + unsigned short firstOffset; + unsigned short secondOffset; unsigned pass : 1; unsigned fail : 1; - unsigned firstOffset : 7; unsigned firstFromBeginning : 1; - unsigned secondOffset : 7; unsigned secondFromBeginning : 1; + unsigned int firstPatternLHS : 1; + unsigned int firstPatternRHS : 1; + unsigned int secondPatternLHS : 1; + unsigned int secondPatternRHS : 1; }; #define OBJECT_RETE_DATA 35 struct objectReteData - { + { INSTANCE_TYPE *CurrentPatternObject; INSTANCE_SLOT *CurrentPatternObjectSlot; unsigned CurrentObjectSlotLength; struct multifieldMarker *CurrentPatternObjectMarks; - struct entityRecord ObjectGVInfo1; + struct entityRecord ObjectGVInfo1; struct entityRecord ObjectGVInfo2; struct entityRecord ObjectGVPNInfo1; struct entityRecord ObjectGVPNInfo2; - struct entityRecord ObjectCmpConstantInfo; - struct entityRecord LengthTestInfo; - struct entityRecord PNSimpleCompareInfo1; - struct entityRecord PNSimpleCompareInfo2; - struct entityRecord PNSimpleCompareInfo3; - struct entityRecord JNSimpleCompareInfo1; - struct entityRecord JNSimpleCompareInfo2; - struct entityRecord JNSimpleCompareInfo3; + struct entityRecord ObjectCmpConstantInfo; + struct entityRecord LengthTestInfo; + struct entityRecord PNSimpleCompareInfo1; + struct entityRecord PNSimpleCompareInfo2; + struct entityRecord PNSimpleCompareInfo3; + struct entityRecord JNSimpleCompareInfo1; + struct entityRecord JNSimpleCompareInfo2; + struct entityRecord JNSimpleCompareInfo3; OBJECT_MATCH_ACTION *ObjectMatchActionQueue; OBJECT_PATTERN_NODE *ObjectPatternNetworkPointer; OBJECT_ALPHA_NODE *ObjectPatternNetworkTerminalPointer; intBool DelayObjectPatternMatching; - unsigned long CurrentObjectMatchTimeTag; - long UseEntityTimeTag; + unsigned long long CurrentObjectMatchTimeTag; + long long UseEntityTimeTag; #if DEFRULE_CONSTRUCT && OBJECT_SYSTEM && CONSTRUCT_COMPILER && (! RUN_TIME) struct CodeGeneratorItem *ObjectPatternCodeItem; #endif @@ -177,7 +204,6 @@ struct objectReteData #define ObjectReteData(theEnv) ((struct objectReteData *) GetEnvironmentData(theEnv,OBJECT_RETE_DATA)) - #ifdef LOCALE #undef LOCALE #endif @@ -188,12 +214,12 @@ struct objectReteData #define LOCALE extern #endif -LOCALE void InstallObjectPrimitives(void *); -LOCALE intBool ObjectCmpConstantFunction(void *,void *,DATA_OBJECT *); + LOCALE void InstallObjectPrimitives(void *); + LOCALE intBool ObjectCmpConstantFunction(void *,void *,DATA_OBJECT *); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM */ -#endif +#endif /* _H_objrtfnx */ diff --git a/src/objrtgen.c b/src/objrtgen.c index b811b2e..f77c031 100644 --- a/src/objrtgen.c +++ b/src/objrtgen.c @@ -1,30 +1,34 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* INFERENCE ENGINE OBJECT PARSING ROUTINES MODULE */ /*******************************************************/ -/**************************************************************/ -/* Purpose: RETE Network Parsing Interface for Objects */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* Contributing Programmer(s): */ -/* */ -/* Revision History: */ -/* 6.23: Changed name of variable exp to theExp */ -/* because of Unix compiler warnings of shadowed */ -/* definitions. */ -/* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ -/* DEFRULE_CONSTRUCT. */ -/* */ -/* Renamed BOOLEAN macro type to intBool. */ -/* */ -/**************************************************************/ +/*************************************************************/ +/* Purpose: RETE Network Parsing Interface for Objects */ +/* */ +/* Principal Programmer(s): */ +/* Brian L. Dantes */ +/* */ +/* Contributing Programmer(s): */ +/* */ +/* Revision History: */ +/* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* DEFRULE_CONSTRUCT. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Added support for hashed memories and other */ +/* join network changes. */ +/* */ +/*************************************************************/ /* ========================================= ***************************************** EXTERNAL DEFINITIONS @@ -52,9 +56,9 @@ ========================================= ***************************************** */ -static void GenObjectGetVar(void *,int,EXPRESSION *,struct lhsParseNode *); +static void GenObjectGetVar(void *,int,EXPRESSION *,struct lhsParseNode *,int); static intBool IsSimpleSlotVariable(struct lhsParseNode *); -static EXPRESSION *GenerateSlotComparisonTest(void *,int,struct lhsParseNode *,struct lhsParseNode *); +static EXPRESSION *GenerateSlotComparisonTest(void *,int,int,struct lhsParseNode *,struct lhsParseNode *); /* ========================================= ***************************************** @@ -69,28 +73,31 @@ static EXPRESSION *GenerateSlotComparisonTest(void *,int,struct lhsParseNode *,s globle void ReplaceGetJNObjectValue( void *theEnv, EXPRESSION *theItem, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { - GenObjectGetVar(theEnv,TRUE,theItem,theNode); + GenObjectGetVar(theEnv,TRUE,theItem,theNode,side); } globle EXPRESSION *GenGetJNObjectValue( void *theEnv, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { EXPRESSION *theItem; theItem = GenConstant(theEnv,0,NULL); - GenObjectGetVar(theEnv,TRUE,theItem,theNode); + GenObjectGetVar(theEnv,TRUE,theItem,theNode,side); return(theItem); } globle EXPRESSION *ObjectJNVariableComparison( void *theEnv, struct lhsParseNode *selfNode, - struct lhsParseNode *referringNode) - { - return(GenerateSlotComparisonTest(theEnv,TRUE,selfNode,referringNode)); + struct lhsParseNode *referringNode, + int isNand) + { + return(GenerateSlotComparisonTest(theEnv,TRUE,isNand,selfNode,referringNode)); } /********************************************** @@ -137,19 +144,19 @@ globle EXPRESSION *GenObjectPNConstantCompare( } else hack.offset = theNode->singleFieldsAfter; - theExp = GenConstant(theEnv,OBJ_PN_CONSTANT,AddBitMap(theEnv,(void *) &hack, + theExp = GenConstant(theEnv,OBJ_PN_CONSTANT,EnvAddBitMap(theEnv,(void *) &hack, (int) sizeof(struct ObjectCmpPNConstant))); theExp->argList = GenConstant(theEnv,theNode->type,theNode->value); } else { hack.general = 1; - theExp = GenConstant(theEnv,OBJ_PN_CONSTANT,AddBitMap(theEnv,(void *) &hack, + theExp = GenConstant(theEnv,OBJ_PN_CONSTANT,EnvAddBitMap(theEnv,(void *) &hack, (int) sizeof(struct ObjectCmpPNConstant))); theExp->argList = GenConstant(theEnv,0,NULL); tmpType = theNode->type; theNode->type = SF_VARIABLE; - GenObjectGetVar(theEnv,FALSE,theExp->argList,theNode); + GenObjectGetVar(theEnv,FALSE,theExp->argList,theNode,-1); theNode->type = tmpType; theExp->argList->nextArg = GenConstant(theEnv,theNode->type,theNode->value); } @@ -161,7 +168,7 @@ globle void ReplaceGetPNObjectValue( EXPRESSION *theItem, struct lhsParseNode *theNode) { - GenObjectGetVar(theEnv,FALSE,theItem,theNode); + GenObjectGetVar(theEnv,FALSE,theItem,theNode,-1); } globle EXPRESSION *GenGetPNObjectValue( @@ -171,7 +178,7 @@ globle EXPRESSION *GenGetPNObjectValue( EXPRESSION *theItem; theItem = GenConstant(theEnv,0,NULL); - GenObjectGetVar(theEnv,FALSE,theItem,theNode); + GenObjectGetVar(theEnv,FALSE,theItem,theNode,-1); return(theItem); } @@ -180,7 +187,7 @@ globle EXPRESSION *ObjectPNVariableComparison( struct lhsParseNode *selfNode, struct lhsParseNode *referringNode) { - return(GenerateSlotComparisonTest(theEnv,FALSE,selfNode,referringNode)); + return(GenerateSlotComparisonTest(theEnv,FALSE,FALSE,selfNode,referringNode)); } /**************************************************** @@ -220,8 +227,12 @@ globle void GenObjectLengthTest( else hack.minLength = theNode->singleFieldsAfter; - theTest = GenConstant(theEnv,OBJ_SLOT_LENGTH,AddBitMap(theEnv,(void *) &hack, + theTest = GenConstant(theEnv,OBJ_SLOT_LENGTH,EnvAddBitMap(theEnv,(void *) &hack, (int) sizeof(struct ObjectMatchLength))); + + if (theNode->constantSelector != NULL) + { theNode->constantSelector->nextArg = CopyExpression(theEnv,theTest); } + theNode->networkTest = CombineExpressions(theEnv,theTest,theNode->networkTest); } @@ -246,7 +257,7 @@ globle void GenObjectZeroLengthTest( ClearBitString((void *) &hack,(int) sizeof(struct ObjectMatchLength)); hack.exactly = 1; hack.minLength = 0; - theTest = GenConstant(theEnv,OBJ_SLOT_LENGTH,AddBitMap(theEnv,(void *) &hack, + theTest = GenConstant(theEnv,OBJ_SLOT_LENGTH,EnvAddBitMap(theEnv,(void *) &hack, (int) sizeof(struct ObjectMatchLength))); theNode->networkTest = CombineExpressions(theEnv,theTest,theNode->networkTest); } @@ -268,6 +279,8 @@ globle void GenObjectZeroLengthTest( the type and value 3) The lhsParseNode for the variable reference + 4) For a join reference, the side from + which the variable must be retrieved. RETURNS : Nothing useful SIDE EFFECTS : The value is a packed long holding pattern index, slot number, @@ -278,7 +291,8 @@ static void GenObjectGetVar( void *theEnv, int joinReference, EXPRESSION *theItem, - struct lhsParseNode *theNode) + struct lhsParseNode *theNode, + int side) { struct ObjectMatchVar1 hack1; struct ObjectMatchVar2 hack2; @@ -288,8 +302,32 @@ static void GenObjectGetVar( if (joinReference) { - hack1.whichPattern = (unsigned short) theNode->pattern; - hack2.whichPattern = (unsigned short) theNode->pattern; + if (side == LHS) + { + hack1.lhs = 1; + hack2.lhs = 1; + hack1.whichPattern = (unsigned short) theNode->joinDepth; + hack2.whichPattern = (unsigned short) theNode->joinDepth; + } + else if (side == RHS) + { + hack1.rhs = 1; + hack2.rhs = 1; + hack1.whichPattern = (unsigned short) 0; + hack2.whichPattern = (unsigned short) 0; + } + else if (side == NESTED_RHS) + { + hack1.rhs = 1; + hack2.rhs = 1; + hack1.whichPattern = (unsigned short) theNode->joinDepth; + hack2.whichPattern = (unsigned short) theNode->joinDepth; + } + else + { + hack1.whichPattern = (unsigned short) theNode->joinDepth; + hack2.whichPattern = (unsigned short) theNode->joinDepth; + } } /* ======================== @@ -299,7 +337,7 @@ static void GenObjectGetVar( { hack1.objectAddress = 1; SetpType(theItem,(joinReference ? OBJ_GET_SLOT_JNVAR1 : OBJ_GET_SLOT_PNVAR1)); - theItem->value = AddBitMap(theEnv,(void *) &hack1,(int) sizeof(struct ObjectMatchVar1)); + theItem->value = EnvAddBitMap(theEnv,(void *) &hack1,(int) sizeof(struct ObjectMatchVar1)); return; } @@ -317,7 +355,7 @@ static void GenObjectGetVar( hack1.allFields = 1; hack1.whichSlot = (unsigned short) theNode->slotNumber; theItem->type = (unsigned short) (joinReference ? OBJ_GET_SLOT_JNVAR1 : OBJ_GET_SLOT_PNVAR1); - theItem->value = AddBitMap(theEnv,(void *) &hack1,(int) sizeof(struct ObjectMatchVar1)); + theItem->value = EnvAddBitMap(theEnv,(void *) &hack1,(int) sizeof(struct ObjectMatchVar1)); return; } @@ -326,7 +364,7 @@ static void GenObjectGetVar( containing at most one multifield variable and at least one (or two if no multifield variables) single-field variable ============================================================= */ - if (((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE)) && + if (((theNode->type == SF_WILDCARD) || (theNode->type == SF_VARIABLE) || ConstantType(theNode->type)) && ((theNode->multiFieldsBefore == 0) || (theNode->multiFieldsAfter == 0))) { hack2.whichSlot = (unsigned short) theNode->slotNumber; @@ -341,11 +379,11 @@ static void GenObjectGetVar( hack2.endOffset = theNode->singleFieldsAfter; } theItem->type = (unsigned short) (joinReference ? OBJ_GET_SLOT_JNVAR2 : OBJ_GET_SLOT_PNVAR2); - theItem->value = AddBitMap(theEnv,(void *) &hack2,sizeof(struct ObjectMatchVar2)); + theItem->value = EnvAddBitMap(theEnv,(void *) &hack2,sizeof(struct ObjectMatchVar2)); return; } - if (((theNode->type == MF_WILDCARD) || (theNode->type == MF_VARIABLE)) && + if (((theNode->type == MF_WILDCARD) || (theNode->type == MF_VARIABLE) || ConstantType(theNode->type)) && (theNode->multiFieldsBefore == 0) && (theNode->multiFieldsAfter == 0)) { @@ -355,7 +393,7 @@ static void GenObjectGetVar( hack2.beginningOffset = theNode->singleFieldsBefore; hack2.endOffset = theNode->singleFieldsAfter; theItem->type = (unsigned short) (joinReference ? OBJ_GET_SLOT_JNVAR2 : OBJ_GET_SLOT_PNVAR2); - theItem->value = AddBitMap(theEnv,(void *) &hack2,sizeof(struct ObjectMatchVar2)); + theItem->value = EnvAddBitMap(theEnv,(void *) &hack2,sizeof(struct ObjectMatchVar2)); return; } @@ -365,7 +403,7 @@ static void GenObjectGetVar( hack1.whichSlot = (unsigned short) theNode->slotNumber; hack1.whichField = (unsigned short) theNode->index; theItem->type = (unsigned short) (joinReference ? OBJ_GET_SLOT_JNVAR1 : OBJ_GET_SLOT_PNVAR1); - theItem->value = AddBitMap(theEnv,(void *) &hack1,sizeof(struct ObjectMatchVar1)); + theItem->value = EnvAddBitMap(theEnv,(void *) &hack1,sizeof(struct ObjectMatchVar1)); } /**************************************************************** @@ -406,9 +444,11 @@ static intBool IsSimpleSlotVariable( pattern variables INPUTS : 1) A flag indicating if this is a pattern or join network test - 2) The intermediate parse node - for the first variable + 2) For a join test, a flag indicating + if it is a nand join 3) The intermediate parse node + for the first variable + 4) The intermediate parse node for the second variable RETURNS : An expression for comparing the variables @@ -431,6 +471,7 @@ static intBool IsSimpleSlotVariable( static EXPRESSION *GenerateSlotComparisonTest( void *theEnv, int joinTest, + int isNand, struct lhsParseNode *selfNode, struct lhsParseNode *referringNode) { @@ -441,6 +482,12 @@ static EXPRESSION *GenerateSlotComparisonTest( struct ObjectCmpJoinSingleSlotVars1 jhack1; struct ObjectCmpJoinSingleSlotVars2 jhack2; struct ObjectCmpJoinSingleSlotVars3 jhack3; + struct lhsParseNode *firstNode; + + if (isNand) + { firstNode = referringNode; } + else + { firstNode = selfNode; } /* ========================================================= If we are comparing two single-field slot variables that @@ -448,12 +495,12 @@ static EXPRESSION *GenerateSlotComparisonTest( a quick comparison. Otherwise, use a general eq/neq with the pattern variable access routines ========================================================= */ - if (IsSimpleSlotVariable(selfNode) && IsSimpleSlotVariable(referringNode)) + if (IsSimpleSlotVariable(firstNode) && IsSimpleSlotVariable(referringNode)) { /* ============================== Compare two single-field slots ============================== */ - if ((selfNode->withinMultifieldSlot == FALSE) && + if ((firstNode->withinMultifieldSlot == FALSE) && (referringNode->withinMultifieldSlot == FALSE)) { ClearBitString((void *) &phack1,(int) sizeof(struct ObjectCmpPNSingleSlotVars1)); @@ -462,17 +509,26 @@ static EXPRESSION *GenerateSlotComparisonTest( phack1.fail = jhack1.fail = 1; else phack1.pass = jhack1.pass = 1; - phack1.firstSlot = jhack1.firstSlot = (unsigned short) selfNode->slotNumber; + + phack1.firstSlot = jhack1.firstSlot = (unsigned short) firstNode->slotNumber; phack1.secondSlot = jhack1.secondSlot = (unsigned short) referringNode->slotNumber; if (joinTest) { - jhack1.firstPattern = (unsigned short) selfNode->pattern; - jhack1.secondPattern = (unsigned short) referringNode->pattern; - theExp = GenConstant(theEnv,OBJ_JN_CMP1,AddBitMap(theEnv,(void *) &jhack1, + if (isNand) + { jhack1.firstPattern = (unsigned short) referringNode->joinDepth; } + else + { jhack1.firstPattern = 0; } + + jhack1.firstPatternRHS = TRUE; + jhack1.secondPatternLHS = TRUE; + + jhack1.secondPattern = (unsigned short) referringNode->joinDepth; + + theExp = GenConstant(theEnv,OBJ_JN_CMP1,EnvAddBitMap(theEnv,(void *) &jhack1, (int) sizeof(struct ObjectCmpJoinSingleSlotVars1))); } else - theExp = GenConstant(theEnv,OBJ_PN_CMP1,AddBitMap(theEnv,(void *) &phack1, + theExp = GenConstant(theEnv,OBJ_PN_CMP1,EnvAddBitMap(theEnv,(void *) &phack1, (int) sizeof(struct ObjectCmpPNSingleSlotVars1))); } /* ============================================ @@ -480,41 +536,58 @@ static EXPRESSION *GenerateSlotComparisonTest( single-field in a multifield slot (make sure the multifield slot reference is first ============================================ */ - else if ((selfNode->withinMultifieldSlot == FALSE) || + else if ((firstNode->withinMultifieldSlot == FALSE) || (referringNode->withinMultifieldSlot == FALSE)) { ClearBitString((void *) &phack2,(int) sizeof(struct ObjectCmpPNSingleSlotVars2)); ClearBitString((void *) &jhack2,(int) sizeof(struct ObjectCmpJoinSingleSlotVars2)); + if (selfNode->negated) phack2.fail = jhack2.fail = 1; else phack2.pass = jhack2.pass = 1; - if (selfNode->withinMultifieldSlot == TRUE) + + if (firstNode->withinMultifieldSlot == TRUE) { - phack2.firstSlot = jhack2.firstSlot = (unsigned short) selfNode->slotNumber; + phack2.firstSlot = jhack2.firstSlot = (unsigned short) firstNode->slotNumber; phack2.secondSlot = jhack2.secondSlot = (unsigned short) referringNode->slotNumber; if (joinTest) { - jhack2.firstPattern = (unsigned short) selfNode->pattern; - jhack2.secondPattern = (unsigned short) referringNode->pattern; + if (isNand) + { jhack2.firstPattern = (unsigned short) referringNode->joinDepth; } + else + { jhack2.firstPattern = 0; } + + jhack2.firstPatternRHS = TRUE; + jhack2.secondPatternLHS = TRUE; + jhack2.secondPattern = (unsigned short) referringNode->joinDepth; } - if (selfNode->multiFieldsBefore == 0) + + if (firstNode->multiFieldsBefore == 0) { phack2.fromBeginning = jhack2.fromBeginning = 1; - phack2.offset = jhack2.offset = selfNode->singleFieldsBefore; + phack2.offset = jhack2.offset = firstNode->singleFieldsBefore; } else - phack2.offset = jhack2.offset = selfNode->singleFieldsAfter; + phack2.offset = jhack2.offset = firstNode->singleFieldsAfter; } else { phack2.firstSlot = jhack2.firstSlot = (unsigned short) referringNode->slotNumber; - phack2.secondSlot = jhack2.secondSlot = (unsigned short) selfNode->slotNumber; + phack2.secondSlot = jhack2.secondSlot = (unsigned short) firstNode->slotNumber; if (joinTest) { - jhack2.firstPattern = (unsigned short) referringNode->pattern; - jhack2.secondPattern = (unsigned short) selfNode->pattern; + if (isNand) + { jhack2.secondPattern = (unsigned short) firstNode->joinDepth; } + else + { jhack2.secondPattern = 0; } + + jhack2.secondPatternRHS = TRUE; + jhack2.firstPatternLHS = TRUE; + + jhack2.firstPattern = (unsigned short) referringNode->joinDepth; } + if (referringNode->multiFieldsBefore == 0) { phack2.fromBeginning = jhack2.fromBeginning = 1; @@ -524,10 +597,10 @@ static EXPRESSION *GenerateSlotComparisonTest( phack2.offset = jhack2.offset = referringNode->singleFieldsAfter; } if (joinTest) - theExp = GenConstant(theEnv,OBJ_JN_CMP2,AddBitMap(theEnv,(void *) &jhack2, + theExp = GenConstant(theEnv,OBJ_JN_CMP2,EnvAddBitMap(theEnv,(void *) &jhack2, (int) sizeof(struct ObjectCmpJoinSingleSlotVars2))); else - theExp = GenConstant(theEnv,OBJ_PN_CMP2,AddBitMap(theEnv,(void *) &phack2, + theExp = GenConstant(theEnv,OBJ_PN_CMP2,EnvAddBitMap(theEnv,(void *) &phack2, (int) sizeof(struct ObjectCmpPNSingleSlotVars2))); } @@ -539,19 +612,23 @@ static EXPRESSION *GenerateSlotComparisonTest( { ClearBitString((void *) &phack3,(int) sizeof(struct ObjectCmpPNSingleSlotVars3)); ClearBitString((void *) &jhack3,(int) sizeof(struct ObjectCmpJoinSingleSlotVars3)); + if (selfNode->negated) phack3.fail = jhack3.fail = 1; else phack3.pass = jhack3.pass = 1; - phack3.firstSlot = jhack3.firstSlot = (unsigned short) selfNode->slotNumber; + + phack3.firstSlot = jhack3.firstSlot = (unsigned short) firstNode->slotNumber; phack3.secondSlot = jhack3.secondSlot = (unsigned short) referringNode->slotNumber; - if (selfNode->multiFieldsBefore == 0) + + if (firstNode->multiFieldsBefore == 0) { phack3.firstFromBeginning = jhack3.firstFromBeginning = 1; - phack3.firstOffset = jhack3.firstOffset = selfNode->singleFieldsBefore; + phack3.firstOffset = jhack3.firstOffset = firstNode->singleFieldsBefore; } else - phack3.firstOffset = jhack3.firstOffset = selfNode->singleFieldsAfter; + phack3.firstOffset = jhack3.firstOffset = firstNode->singleFieldsAfter; + if (referringNode->multiFieldsBefore == 0) { phack3.secondFromBeginning = jhack3.secondFromBeginning = 1; @@ -559,15 +636,23 @@ static EXPRESSION *GenerateSlotComparisonTest( } else phack3.secondOffset = jhack3.secondOffset = referringNode->singleFieldsAfter; + if (joinTest) { - jhack3.firstPattern = (unsigned short) selfNode->pattern; - jhack3.secondPattern = (unsigned short) referringNode->pattern; - theExp = GenConstant(theEnv,OBJ_JN_CMP3,AddBitMap(theEnv,(void *) &jhack3, + if (isNand) + { jhack3.firstPattern = (unsigned short) referringNode->joinDepth; } + else + { jhack3.firstPattern = 0; } + + jhack3.firstPatternRHS = TRUE; + jhack3.secondPatternLHS = TRUE; + jhack3.secondPattern = (unsigned short) referringNode->joinDepth; + + theExp = GenConstant(theEnv,OBJ_JN_CMP3,EnvAddBitMap(theEnv,(void *) &jhack3, (int) sizeof(struct ObjectCmpJoinSingleSlotVars3))); } else - theExp = GenConstant(theEnv,OBJ_PN_CMP3,AddBitMap(theEnv,(void *) &phack3, + theExp = GenConstant(theEnv,OBJ_PN_CMP3,EnvAddBitMap(theEnv,(void *) &phack3, (int) sizeof(struct ObjectCmpPNSingleSlotVars3))); } } @@ -581,9 +666,15 @@ static EXPRESSION *GenerateSlotComparisonTest( { theExp = GenConstant(theEnv,FCALL,selfNode->negated ? ExpressionData(theEnv)->PTR_NEQ : ExpressionData(theEnv)->PTR_EQ); theExp->argList = GenConstant(theEnv,0,NULL); - GenObjectGetVar(theEnv,joinTest,theExp->argList,selfNode); + + if (isNand) + { GenObjectGetVar(theEnv,joinTest,theExp->argList,selfNode,NESTED_RHS); } + else + { GenObjectGetVar(theEnv,joinTest,theExp->argList,selfNode,RHS); } + theExp->argList->nextArg = GenConstant(theEnv,0,NULL); - GenObjectGetVar(theEnv,joinTest,theExp->argList->nextArg,referringNode); + + GenObjectGetVar(theEnv,joinTest,theExp->argList->nextArg,referringNode,LHS); } return(theExp); } diff --git a/src/objrtgen.h b/src/objrtgen.h index 3076c51..4c3a82a 100644 --- a/src/objrtgen.h +++ b/src/objrtgen.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,7 +10,7 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ @@ -19,6 +19,9 @@ /* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ +/* 6.30: Added support for hashed memories and other */ +/* join network changes. */ +/* */ /*************************************************************/ #ifndef _H_objrtgen @@ -43,19 +46,19 @@ #define LOCALE extern #endif - LOCALE void ReplaceGetJNObjectValue(void *,EXPRESSION *,struct lhsParseNode *); - LOCALE EXPRESSION *GenGetJNObjectValue(void *,struct lhsParseNode *); - LOCALE EXPRESSION *ObjectJNVariableComparison(void *,struct lhsParseNode *,struct lhsParseNode *); + LOCALE void ReplaceGetJNObjectValue(void *,EXPRESSION *,struct lhsParseNode *,int); + LOCALE EXPRESSION *GenGetJNObjectValue(void *,struct lhsParseNode *,int); + LOCALE EXPRESSION *ObjectJNVariableComparison(void *,struct lhsParseNode *,struct lhsParseNode *,int); LOCALE EXPRESSION *GenObjectPNConstantCompare(void *,struct lhsParseNode *); LOCALE void ReplaceGetPNObjectValue(void *,EXPRESSION *,struct lhsParseNode *); - LOCALE EXPRESSION *GenGetPNObjectValue(void *,struct lhsParseNode *); + LOCALE EXPRESSION *GenGetPNObjectValue(void *,struct lhsParseNode *); LOCALE EXPRESSION *ObjectPNVariableComparison(void *,struct lhsParseNode *,struct lhsParseNode *); LOCALE void GenObjectLengthTest(void *,struct lhsParseNode *); LOCALE void GenObjectZeroLengthTest(void *,struct lhsParseNode *); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM && (! RUN_TIME) && (! BLOAD_ONLY) */ -#endif +#endif /* _H_objrtgen */ diff --git a/src/objrtmch.c b/src/objrtmch.c index b83c309..9d773bd 100644 --- a/src/objrtmch.c +++ b/src/objrtmch.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* OBJECT PATTERN MATCHER MODULE */ /*******************************************************/ @@ -10,11 +10,12 @@ /* Purpose: RETE Network Interface for Objects */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Removed INCREMENTAL_RESET and */ @@ -25,6 +26,21 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Modified the QueueObjectMatchAction function */ +/* so that instance retract actions always occur */ +/* before instance assert and modify actions. */ +/* This prevents the pattern matching process */ +/* from attempting the evaluation of a join */ +/* expression that accesses the slots of a */ +/* retracted instance. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ /**************************************************************/ /* ========================================= ***************************************** @@ -393,6 +409,7 @@ static void QueueObjectMatchAction( int slotNameID) { OBJECT_MATCH_ACTION *prv,*cur,*newMatch; + OBJECT_MATCH_ACTION *prvRetract = NULL; /* DR0873 */ prv = NULL; cur = ObjectReteData(theEnv)->ObjectMatchActionQueue; @@ -463,6 +480,9 @@ static void QueueObjectMatchAction( return; } + + if (cur->type == OBJECT_RETRACT) /* DR0873 */ + { prvRetract = cur; } /* DR0873 */ prv = cur; cur = cur->nxt; } @@ -473,11 +493,33 @@ static void QueueObjectMatchAction( ================================================ */ newMatch = get_struct(theEnv,objectMatchAction); newMatch->type = type; - newMatch->nxt = cur; + newMatch->nxt = NULL; /* If we get here, cur should be NULL */ newMatch->slotNameIDs = (type != OBJECT_MODIFY) ? NULL : QueueModifySlotMap(theEnv,NULL,slotNameID); newMatch->ins = ins; newMatch->ins->busy++; + + /* DR0873 Begin */ + /* Retract operations must be processed before assert and */ + /* modify actions, otherwise the pattern matching process */ + /* might attempt to access the slots of a retract instance. */ + + if (type == OBJECT_RETRACT) + { + if (prvRetract == NULL) + { + newMatch->nxt = ObjectReteData(theEnv)->ObjectMatchActionQueue; + ObjectReteData(theEnv)->ObjectMatchActionQueue = newMatch; + } + else + { + newMatch->nxt = prvRetract->nxt; + prvRetract->nxt = newMatch; + } + } + else + /* DR0873 End */ + if (prv == NULL) ObjectReteData(theEnv)->ObjectMatchActionQueue = newMatch; else @@ -748,17 +790,19 @@ static void ObjectPatternMatch( while (patternTop != NULL) { - /* =========================================================== - MarkObjectPatternNetwork() has already marked pattern nodes - which need processing according to the class bitmaps, - slot updates and incremental reset status - =========================================================== */ + /*=============================================================*/ + /* MarkObjectPatternNetwork() has already marked pattern nodes */ + /* which need processing according to the class bitmaps, slot */ + /* updates and incremental reset status. */ + /*=============================================================*/ + if (patternTop->matchTimeTag == ObjectReteData(theEnv)->CurrentObjectMatchTimeTag) { - /* ======================================== - Make sure we are examining the correct - slot of the object for this pattern node - ======================================== */ + /*===========================================*/ + /* Make sure we are examining the correct */ + /* slot of the object for this pattern node. */ + /*===========================================*/ + if ((patternTop->slotNameID == ISA_ID) || (patternTop->slotNameID == NAME_ID)) { @@ -769,12 +813,13 @@ static void ObjectPatternMatch( else if ((ObjectReteData(theEnv)->CurrentPatternObjectSlot == NULL) ? TRUE : (ObjectReteData(theEnv)->CurrentPatternObjectSlot->desc->slotName->id != patternTop->slotNameID)) { - /* ==================================================== - Need to reset the indices for the multifield - markers now that we have moved onto a different slot - ==================================================== */ + /*=======================================================*/ + /* Need to reset the indices for the multifield */ + /* markers now that we have moved onto a different slot. */ + /*=======================================================*/ + ObjectReteData(theEnv)->CurrentPatternObjectSlot = - ObjectReteData(theEnv)->CurrentPatternObject->slotAddresses[ObjectReteData(theEnv)->CurrentPatternObject->cls->slotNameMap + ObjectReteData(theEnv)->CurrentPatternObject->slotAddresses[ObjectReteData(theEnv)->CurrentPatternObject->cls->slotNameMap [patternTop->slotNameID] - 1]; offset = 0; if (ObjectReteData(theEnv)->CurrentPatternObjectSlot->desc->multiple) @@ -784,11 +829,12 @@ static void ObjectPatternMatch( ObjectReteData(theEnv)->CurrentObjectSlotLength = 1; } - /* ======================================================== - Process the pattern node. If it is satisfied by the - the instance, ProcessPatternNode() will recursively pass - all of its children nodes through ObjectPatternMatch() - ======================================================== */ + /*==========================================================*/ + /* Process the pattern node. If it is satisfied by the */ + /* the instance, ProcessPatternNode() will recursively pass */ + /* all of its children nodes through ObjectPatternMatch(). */ + /*==========================================================*/ + saveSlotLength = ObjectReteData(theEnv)->CurrentObjectSlotLength; saveSlot = ObjectReteData(theEnv)->CurrentPatternObjectSlot; ProcessPatternNode(theEnv,offset,patternTop,endMark); @@ -796,13 +842,14 @@ static void ObjectPatternMatch( ObjectReteData(theEnv)->CurrentPatternObjectSlot = saveSlot; } - /* ============================================================== - Move on to the siblings of this node - if the current node was - a constant test that succeeded, skip further sibling nodes - (which test on the same field in the pattern) - which match on the same slot since they are all constant tests - as well and will, of course fail. - ============================================================== */ + /*============================================================*/ + /* Move on to the siblings of this node - if the current node */ + /* was a constant test that succeeded, skip further sibling */ + /* nodes (which test on the same field in the pattern) which */ + /* match on the same slot since they are all constant tests */ + /* as well and will, of course fail. */ + /*============================================================*/ + if (patternTop->blocked == TRUE) { patternTop->blocked = FALSE; @@ -857,17 +904,36 @@ static void ProcessPatternNode( int repeatCount; INSTANCE_SLOT *objectSlot; struct multifieldMarker *newMark; + DATA_OBJECT theResult; + OBJECT_PATTERN_NODE *tempPtr; patternSlotField = patternNode->whichField; objectSlotField = patternSlotField + offset; - /* ========================================== - If this is a test on the class or the name - of the object, process it separately. - ========================================== */ + /*============================================*/ + /* If this is a test on the class or the name */ + /* of the object, process it separately. */ + /*============================================*/ + if (ObjectReteData(theEnv)->CurrentPatternObjectSlot == NULL) { - if ((patternNode->networkTest == NULL) ? TRUE : + if (patternNode->selector) /* TBD Necessary? */ + { + if (EvaluateObjectPatternTest(theEnv,objectSlotField,NULL,patternNode->networkTest->nextArg,patternNode)) + { + EvaluateExpression(theEnv,patternNode->networkTest,&theResult); + + tempPtr = (OBJECT_PATTERN_NODE *) FindHashedPatternNode(theEnv,patternNode,theResult.type,theResult.value); + + if (tempPtr != NULL) + { + if (tempPtr->alphaNode != NULL) + { CreateObjectAlphaMatch(theEnv,tempPtr->alphaNode); } + ObjectPatternMatch(theEnv,offset,tempPtr->nextLevel,endMark); + } + } + } + else if ((patternNode->networkTest == NULL) ? TRUE : (EvaluateObjectPatternTest(theEnv,objectSlotField,NULL, (EXPRESSION *) patternNode->networkTest,patternNode))) { @@ -878,12 +944,29 @@ static void ProcessPatternNode( return; } - /* ================================ - Check a single-field restriction - ================================ */ + /*===================================*/ + /* Check a single-field restriction. */ + /*===================================*/ + if (patternNode->multifieldNode == 0) { - if ((patternNode->networkTest == NULL) ? TRUE : + if (patternNode->selector) + { + if (EvaluateObjectPatternTest(theEnv,objectSlotField,NULL,patternNode->networkTest->nextArg,patternNode)) + { + EvaluateExpression(theEnv,patternNode->networkTest,&theResult); + + tempPtr = (OBJECT_PATTERN_NODE *) FindHashedPatternNode(theEnv,patternNode,theResult.type,theResult.value); + + if (tempPtr != NULL) + { + if (tempPtr->alphaNode != NULL) + { CreateObjectAlphaMatch(theEnv,tempPtr->alphaNode); } + ObjectPatternMatch(theEnv,offset,tempPtr->nextLevel,endMark); + } + } + } + else if ((patternNode->networkTest == NULL) ? TRUE : EvaluateObjectPatternTest(theEnv,objectSlotField,NULL, (EXPRESSION *) patternNode->networkTest,patternNode)) { @@ -894,11 +977,12 @@ static void ProcessPatternNode( return; } - /* ================================================================== - Check a multifield restriction. Add a marker for this field which - has indices indicating to which values in the object slot the - multifield pattern node is bound - ================================================================== */ + /*==============================================================*/ + /* Check a multifield restriction. Add a marker for this field */ + /* which has indices indicating to which values in the object */ + /* slot the multifield pattern node is bound. */ + /*==============================================================*/ + newMark = get_struct(theEnv,multifieldMarker); newMark->whichField = patternSlotField; newMark->where.whichSlot = (void *) ObjectReteData(theEnv)->CurrentPatternObjectSlot->desc->slotName->name; @@ -909,15 +993,16 @@ static void ProcessPatternNode( else endMark->next = newMark; - /* ========================================================== - If there are further pattern restrictions on this slot, - try pattern-matching for all possible bound values of the - multifield pattern node: from no values to all values from - the starting position of the multifield to the end of the - object slot. Otherwise, bind the multifield to all the - remaining fields in the slot value and continue with - pattern-matching - ========================================================== */ + /*============================================================*/ + /* If there are further pattern restrictions on this slot, */ + /* try pattern-matching for all possible bound values of the */ + /* multifield pattern node: from no values to all values from */ + /* the starting position of the multifield to the end of the */ + /* object slot. Otherwise, bind the multifield to all the */ + /* remaining fields in the slot value and continue with */ + /* pattern-matching. */ + /*============================================================*/ + if (patternNode->endSlot == FALSE) { objectSlotLength = ObjectReteData(theEnv)->CurrentObjectSlotLength; @@ -927,7 +1012,26 @@ static void ProcessPatternNode( - patternNode->leaveFields + 2); while (repeatCount > 0) { - if ((patternNode->networkTest == NULL) ? TRUE : + if (patternNode->selector) + { + if (EvaluateObjectPatternTest(theEnv,objectSlotField,newMark,patternNode->networkTest->nextArg,patternNode)) + { + EvaluateExpression(theEnv,patternNode->networkTest,&theResult); + + tempPtr = (OBJECT_PATTERN_NODE *) FindHashedPatternNode(theEnv,patternNode,theResult.type,theResult.value); + + if (tempPtr != NULL) + { + if (tempPtr->alphaNode != NULL) + { CreateObjectAlphaMatch(theEnv,tempPtr->alphaNode); } + ObjectPatternMatch(theEnv,(int) (offset + (newMark->endPosition - objectSlotField)), + tempPtr->nextLevel,newMark); + ObjectReteData(theEnv)->CurrentObjectSlotLength = objectSlotLength; + ObjectReteData(theEnv)->CurrentPatternObjectSlot = objectSlot; + } + } + } + else if ((patternNode->networkTest == NULL) ? TRUE : EvaluateObjectPatternTest(theEnv,objectSlotField,newMark, (EXPRESSION *) patternNode->networkTest,patternNode)) { @@ -944,8 +1048,25 @@ static void ProcessPatternNode( } else { - newMark->endPosition = (long) ObjectReteData(theEnv)->CurrentObjectSlotLength; - if ((patternNode->networkTest == NULL) ? TRUE : + newMark->endPosition = (long) ObjectReteData(theEnv)->CurrentObjectSlotLength - patternNode->leaveFields; // Bug fix: added leaveFields + + if (patternNode->selector) + { + if (EvaluateObjectPatternTest(theEnv,objectSlotField,newMark,patternNode->networkTest->nextArg,patternNode)) + { + EvaluateExpression(theEnv,patternNode->networkTest,&theResult); + + tempPtr = (OBJECT_PATTERN_NODE *) FindHashedPatternNode(theEnv,patternNode,theResult.type,theResult.value); + + if (tempPtr != NULL) + { + if (tempPtr->alphaNode != NULL) + CreateObjectAlphaMatch(theEnv,tempPtr->alphaNode); + ObjectPatternMatch(theEnv,0,tempPtr->nextLevel,newMark); + } + } + } + else if ((patternNode->networkTest == NULL) ? TRUE : EvaluateObjectPatternTest(theEnv,objectSlotField,newMark, (EXPRESSION *) patternNode->networkTest,patternNode)) { @@ -955,9 +1076,9 @@ static void ProcessPatternNode( } } - /* ====================================== - Delete the temporary multifield marker - ====================================== */ + /*=========================================*/ + /* Delete the temporary multifield marker. */ + /*=========================================*/ if (ObjectReteData(theEnv)->CurrentPatternObjectMarks == newMark) ObjectReteData(theEnv)->CurrentPatternObjectMarks = NULL; @@ -984,11 +1105,14 @@ static void CreateObjectAlphaMatch( struct joinNode *listOfJoins; struct partialMatch *theMatch; struct patternMatch *newMatch; + unsigned long hashValue; while (alphaPtr != NULL) { if (alphaPtr->matchTimeTag == ObjectReteData(theEnv)->CurrentObjectMatchTimeTag) { + hashValue = ComputeRightHashValue(theEnv,&alphaPtr->header); + /* =================================================== If we have reached the class bitmap of the pattern, place the object in the alpha memory of each of @@ -1001,7 +1125,8 @@ static void CreateObjectAlphaMatch( ObjectReteData(theEnv)->CurrentPatternObject->busy++; theMatch = CreateAlphaMatch(theEnv,(void *) ObjectReteData(theEnv)->CurrentPatternObject, ObjectReteData(theEnv)->CurrentPatternObjectMarks, - (struct patternNodeHeader *) alphaPtr); + (struct patternNodeHeader *) alphaPtr,hashValue); + theMatch->owner = alphaPtr; /* ====================================== Attach the partial match to the object @@ -1019,7 +1144,7 @@ static void CreateObjectAlphaMatch( listOfJoins = alphaPtr->header.entryJoin; while (listOfJoins != NULL) { - NetworkAssert(theEnv,theMatch,listOfJoins,RHS); + NetworkAssert(theEnv,theMatch,listOfJoins); listOfJoins = listOfJoins->rightMatchNode; } } @@ -1054,6 +1179,8 @@ static intBool EvaluateObjectPatternTest( DATA_OBJECT vresult; int rv; + if (networkTest == NULL) return(TRUE); + if (networkTest->type == OBJ_PN_CONSTANT) { struct expr *oldArgument; @@ -1175,7 +1302,7 @@ static void ObjectAssertAction( NOTES : None **********************************************************************/ static void ObjectModifyAction( - void *theEnv, + void *theEnv, INSTANCE_TYPE *ins, SLOT_BITMAP *slotNameIDs) { @@ -1309,7 +1436,7 @@ static void ObjectPatternNetErrorMessage( EnvPrintRouter(theEnv,WERROR," Problem resides in slot "); EnvPrintRouter(theEnv,WERROR,ValueToString(FindIDSlotName(theEnv,patternPtr->slotNameID))); EnvPrintRouter(theEnv,WERROR," field #"); - PrintLongInteger(theEnv,WERROR,(long) patternPtr->whichField); + PrintLongInteger(theEnv,WERROR,(long long) patternPtr->whichField); EnvPrintRouter(theEnv,WERROR,"\n"); TraceErrorToObjectPattern(theEnv,TRUE,patternPtr); EnvPrintRouter(theEnv,WERROR,"\n"); @@ -1342,10 +1469,7 @@ static void TraceErrorToObjectPattern( joinPtr = patternPtr->alphaNode->header.entryJoin; while (joinPtr != NULL) { - EnvPrintRouter(theEnv,WERROR," Of pattern #"); - PrintLongInteger(theEnv,WERROR,(long) joinPtr->depth); - EnvPrintRouter(theEnv,WERROR," in rule(s):\n"); - TraceErrorToRule(theEnv,joinPtr," "); + TraceErrorToRule(theEnv,joinPtr," "); joinPtr = joinPtr->rightMatchNode; } } diff --git a/src/objrtmch.h b/src/objrtmch.h index 024fe1f..f20195e 100644 --- a/src/objrtmch.h +++ b/src/objrtmch.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,17 +10,37 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ -/* 6.24: Converted INSTANCE_PATTERN_MATCHING to */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Removed INCREMENTAL_RESET and */ +/* LOGICAL_DEPENDENCIES compilation flags. */ +/* */ +/* Converted INSTANCE_PATTERN_MATCHING to */ /* DEFRULE_CONSTRUCT. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Modified the QueueObjectMatchAction function */ +/* so that instance retract actions always occur */ +/* before instance assert and modify actions. */ +/* This prevents the pattern matching process */ +/* from attempting the evaluation of a join */ +/* expression that accesses the slots of a */ +/* retracted instance. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added support for hashed comparisons to */ +/* constants. */ +/* */ /*************************************************************/ #ifndef _H_objrtmch @@ -76,10 +96,11 @@ typedef struct objectPatternNode unsigned blocked : 1; unsigned multifieldNode : 1; unsigned endSlot : 1; + unsigned selector : 1; unsigned whichField : 8; - unsigned leaveFields : 8; - unsigned long matchTimeTag; - unsigned slotNameID; + unsigned short leaveFields; + unsigned long long matchTimeTag; + int slotNameID; EXPRESSION *networkTest; struct objectPatternNode *nextLevel; struct objectPatternNode *lastLevel; @@ -92,7 +113,7 @@ typedef struct objectPatternNode struct objectAlphaNode { struct patternNodeHeader header; - unsigned long matchTimeTag; + unsigned long long matchTimeTag; BITMAP_HN *classbmp,*slotbmp; OBJECT_PATTERN_NODE *patternNode; struct objectAlphaNode *nxtInGroup, @@ -128,9 +149,9 @@ typedef struct objectMatchAction LOCALE void ObjectNetworkAction(void *,int,INSTANCE_TYPE *,int); LOCALE void ResetObjectMatchTimeTags(void *); -#endif +#endif /* DEFRULE_CONSTRUCT && OBJECT_SYSTEM */ -#endif +#endif /* _H_objrtmch */ diff --git a/src/parsefun.c b/src/parsefun.c index d392c85..e6d89cb 100644 --- a/src/parsefun.c +++ b/src/parsefun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PARSING FUNCTIONS MODULE */ /*******************************************************/ @@ -22,6 +22,18 @@ /* 6.24: Corrected code to remove run-time program */ /* compiler warnings. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed function declaration issue when */ +/* BLOAD_ONLY compiler flag is set to 1. */ +/* */ /*************************************************************/ #define _PARSEFUN_SOURCE_ @@ -47,13 +59,13 @@ #define PARSEFUN_DATA 11 struct parseFunctionData - { + { char *ErrorString; - int ErrorCurrentPosition; - unsigned ErrorMaximumPosition; + size_t ErrorCurrentPosition; + size_t ErrorMaximumPosition; char *WarningString; - int WarningCurrentPosition; - unsigned WarningMaximumPosition; + size_t WarningCurrentPosition; + size_t WarningMaximumPosition; }; #define ParseFunctionData(theEnv) ((struct parseFunctionData *) GetEnvironmentData(theEnv,PARSEFUN_DATA)) @@ -63,8 +75,8 @@ struct parseFunctionData /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static int FindErrorCapture(void *,char *); - static int PrintErrorCapture(void *,char *,char *); + static int FindErrorCapture(void *,const char *); + static int PrintErrorCapture(void *,const char *,const char *); static void DeactivateErrorCapture(void *); static void SetErrorCaptureValues(void *,DATA_OBJECT_PTR); #endif @@ -128,10 +140,10 @@ globle void CheckSyntaxFunction( /*********************************/ globle int CheckSyntax( void *theEnv, - char *theString, + const char *theString, DATA_OBJECT_PTR returnValue) { - char *name; + const char *name; struct token theToken; struct expr *top; short rv; @@ -270,7 +282,7 @@ globle int CheckSyntax( /**************************************************/ static void DeactivateErrorCapture( void *theEnv) - { + { if (ParseFunctionData(theEnv)->ErrorString != NULL) { rm(theEnv,ParseFunctionData(theEnv)->ErrorString,ParseFunctionData(theEnv)->ErrorMaximumPosition); @@ -339,14 +351,11 @@ static void SetErrorCaptureValues( /* FindErrorCapture: Find routine */ /* for the check-syntax router. */ /**********************************/ -#if IBM_TBC -#pragma argsused -#endif static int FindErrorCapture( void *theEnv, - char *logicalName) + const char *logicalName) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -363,8 +372,8 @@ static int FindErrorCapture( /************************************/ static int PrintErrorCapture( void *theEnv, - char *logicalName, - char *str) + const char *logicalName, + const char *str) { if (strcmp(logicalName,WERROR) == 0) { @@ -403,14 +412,9 @@ globle void CheckSyntaxFunction( /************************************************/ globle int CheckSyntax( void *theEnv, - char *theString, + const char *theString, DATA_OBJECT_PTR returnValue) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theString) -#pragma unused(returnValue) -#endif - PrintErrorID(theEnv,"PARSEFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Function check-syntax does not work in run time modules.\n"); SetpType(returnValue,SYMBOL); diff --git a/src/parsefun.h b/src/parsefun.h index ca69d92..28164e2 100644 --- a/src/parsefun.h +++ b/src/parsefun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PARSING FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -17,6 +17,23 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: Corrected code to remove run-time program */ +/* compiler warnings. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed function declaration issue when */ +/* BLOAD_ONLY compiler flag is set to 1. */ +/* */ /*************************************************************/ #ifndef _H_parsefun @@ -39,9 +56,9 @@ LOCALE void ParseFunctionDefinitions(void *); LOCALE void CheckSyntaxFunction(void *,DATA_OBJECT *); - LOCALE int CheckSyntax(void *,char *,DATA_OBJECT_PTR); + LOCALE int CheckSyntax(void *,const char *,DATA_OBJECT_PTR); -#endif +#endif /* _H_parsefun */ diff --git a/src/pattern.c b/src/pattern.c index f99c08c..9ada441 100644 --- a/src/pattern.c +++ b/src/pattern.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 07/25/14 */ /* */ /* RULE PATTERN MODULE */ /*******************************************************/ @@ -22,6 +22,11 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _PATTERN_SOURCE_ @@ -53,22 +58,46 @@ /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static struct lhsParseNode *ConjuctiveRestrictionParse(void *,char *,struct token *,int *); - static struct lhsParseNode *LiteralRestrictionParse(void *,char *,struct token *,int *); - static int CheckForVariableMixing(void *,struct lhsParseNode *); - static void TallyFieldTypes(struct lhsParseNode *); + static struct lhsParseNode *ConjuctiveRestrictionParse(void *,const char *,struct token *,int *); + static struct lhsParseNode *LiteralRestrictionParse(void *,const char *,struct token *,int *); + static int CheckForVariableMixing(void *,struct lhsParseNode *); + static void TallyFieldTypes(struct lhsParseNode *); #endif - static void DeallocatePatternData(void *); + static void DeallocatePatternData(void *); + static struct patternNodeHashEntry **CreatePatternHashTable(void *,unsigned long); /*****************************************************************************/ /* InitializePatterns: Initializes the global data associated with patterns. */ /*****************************************************************************/ globle void InitializePatterns( void *theEnv) - { + { AllocateEnvironmentData(theEnv,PATTERN_DATA,sizeof(struct patternData),DeallocatePatternData); + PatternData(theEnv)->NextPosition = 1; + PatternData(theEnv)->PatternHashTable = CreatePatternHashTable(theEnv,SIZE_PATTERN_HASH); + PatternData(theEnv)->PatternHashTableSize = SIZE_PATTERN_HASH; } - + +/*******************************************************************/ +/* CreatePatternHashTable: Creates and initializes a fact hash table. */ +/*******************************************************************/ +static struct patternNodeHashEntry **CreatePatternHashTable( + void *theEnv, + unsigned long tableSize) + { + unsigned long i; + struct patternNodeHashEntry **theTable; + + theTable = (struct patternNodeHashEntry **) + gm3(theEnv,sizeof (struct patternNodeHashEntry *) * tableSize); + + if (theTable == NULL) EnvExitRouter(theEnv,EXIT_FAILURE); + + for (i = 0; i < tableSize; i++) theTable[i] = NULL; + + return(theTable); + } + /**************************************************/ /* DeallocatePatternData: Deallocates environment */ /* data for rule pattern registration. */ @@ -78,6 +107,8 @@ static void DeallocatePatternData( { struct reservedSymbol *tmpRSPtr, *nextRSPtr; struct patternParser *tmpPPPtr, *nextPPPtr; + struct patternNodeHashEntry *tmpPNEPtr, *nextPNEPtr; + unsigned long i; tmpRSPtr = PatternData(theEnv)->ListOfReservedPatternSymbols; while (tmpRSPtr != NULL) @@ -86,7 +117,7 @@ static void DeallocatePatternData( rtn_struct(theEnv,reservedSymbol,tmpRSPtr); tmpRSPtr = nextRSPtr; } - + tmpPPPtr = PatternData(theEnv)->ListOfPatternParsers; while (tmpPPPtr != NULL) { @@ -94,6 +125,120 @@ static void DeallocatePatternData( rtn_struct(theEnv,patternParser,tmpPPPtr); tmpPPPtr = nextPPPtr; } + + for (i = 0; i < PatternData(theEnv)->PatternHashTableSize; i++) + { + tmpPNEPtr = PatternData(theEnv)->PatternHashTable[i]; + + while (tmpPNEPtr != NULL) + { + nextPNEPtr = tmpPNEPtr->next; + rtn_struct(theEnv,patternNodeHashEntry,tmpPNEPtr); + tmpPNEPtr = nextPNEPtr; + } + } + + rm3(theEnv,PatternData(theEnv)->PatternHashTable, + sizeof(struct patternNodeHashEntry *) * PatternData(theEnv)->PatternHashTableSize); + } + +/******************************************************************************/ +/* AddHashedPatternNode: Adds a pattern node entry to the pattern hash table. */ +/******************************************************************************/ +globle void AddHashedPatternNode( + void *theEnv, + void *parent, + void *child, + unsigned short keyType, + void *keyValue) + { + unsigned long hashValue; + struct patternNodeHashEntry *newhash, *temp; + + hashValue = GetAtomicHashValue(keyType,keyValue,1) + HashExternalAddress(parent,0); /* TBD mult * 30 */ + + newhash = get_struct(theEnv,patternNodeHashEntry); + newhash->parent = parent; + newhash->child = child; + newhash->type = keyType; + newhash->value = keyValue; + + hashValue = (hashValue % PatternData(theEnv)->PatternHashTableSize); + + temp = PatternData(theEnv)->PatternHashTable[hashValue]; + PatternData(theEnv)->PatternHashTable[hashValue] = newhash; + newhash->next = temp; + } + +/***************************************************/ +/* RemoveHashedPatternNode: Removes a pattern node */ +/* entry from the pattern node hash table. */ +/***************************************************/ +globle intBool RemoveHashedPatternNode( + void *theEnv, + void *parent, + void *child, + unsigned short keyType, + void *keyValue) + { + unsigned long hashValue; + struct patternNodeHashEntry *hptr, *prev; + + hashValue = GetAtomicHashValue(keyType,keyValue,1) + HashExternalAddress(parent,0); /* TBD mult * 30 */ + hashValue = (hashValue % PatternData(theEnv)->PatternHashTableSize); + + for (hptr = PatternData(theEnv)->PatternHashTable[hashValue], prev = NULL; + hptr != NULL; + hptr = hptr->next) + { + if (hptr->child == child) + { + if (prev == NULL) + { + PatternData(theEnv)->PatternHashTable[hashValue] = hptr->next; + rtn_struct(theEnv,patternNodeHashEntry,hptr); + return(1); + } + else + { + prev->next = hptr->next; + rtn_struct(theEnv,patternNodeHashEntry,hptr); + return(1); + } + } + prev = hptr; + } + + return(0); + } + +/***********************************************/ +/* FindHashedPatternNode: Finds a pattern node */ +/* entry in the pattern node hash table. */ +/***********************************************/ +globle void *FindHashedPatternNode( + void *theEnv, + void *parent, + unsigned short keyType, + void *keyValue) + { + unsigned long hashValue; + struct patternNodeHashEntry *hptr; + + hashValue = GetAtomicHashValue(keyType,keyValue,1) + HashExternalAddress(parent,0); /* TBD mult * 30 */ + hashValue = (hashValue % PatternData(theEnv)->PatternHashTableSize); + + for (hptr = PatternData(theEnv)->PatternHashTable[hashValue]; + hptr != NULL; + hptr = hptr->next) + { + if ((hptr->parent == parent) && + (keyType == hptr->type) && + (keyValue == hptr->value)) + { return(hptr->child); } + } + + return(NULL); } /******************************************************************/ @@ -106,8 +251,8 @@ static void DeallocatePatternData( /******************************************************************/ void AddReservedPatternSymbol( void *theEnv, - char *theSymbol, - char *reservedBy) + const char *theSymbol, + const char *reservedBy) { struct reservedSymbol *newSymbol; @@ -126,8 +271,8 @@ void AddReservedPatternSymbol( /******************************************************************/ intBool ReservedPatternSymbol( void *theEnv, - char *theSymbol, - char *checkedBy) + const char *theSymbol, + const char *checkedBy) { struct reservedSymbol *currentSymbol; @@ -155,8 +300,8 @@ intBool ReservedPatternSymbol( /********************************************************/ void ReservedPatternSymbolErrorMsg( void *theEnv, - char *theSymbol, - char *usedFor) + const char *theSymbol, + const char *usedFor) { PrintErrorID(theEnv,"PATTERN",1,TRUE); EnvPrintRouter(theEnv,WERROR,"The symbol "); @@ -250,10 +395,12 @@ void DetachPattern( int rhsType, struct patternNodeHeader *theHeader) { - if (PatternData(theEnv)->PatternParserArray[rhsType] != NULL) + if (rhsType == 0) return; + + if (PatternData(theEnv)->PatternParserArray[rhsType-1] != NULL) { - FlushAlphaBetaMemory(theEnv,theHeader->alphaMemory); - (*PatternData(theEnv)->PatternParserArray[rhsType]->removePatternFunction)(theEnv,theHeader); + FlushAlphaMemory(theEnv,theHeader); + (*PatternData(theEnv)->PatternParserArray[rhsType-1]->removePatternFunction)(theEnv,theHeader); } } @@ -280,7 +427,7 @@ globle intBool AddPatternParser( /*================================*/ newPtr->positionInArray = PatternData(theEnv)->NextPosition; - PatternData(theEnv)->PatternParserArray[PatternData(theEnv)->NextPosition] = newPtr; + PatternData(theEnv)->PatternParserArray[PatternData(theEnv)->NextPosition-1] = newPtr; PatternData(theEnv)->NextPosition++; /*================================*/ @@ -323,7 +470,7 @@ globle intBool AddPatternParser( /****************************************************/ globle struct patternParser *FindPatternParser( void *theEnv, - char *name) + const char *name) { struct patternParser *tempParser; @@ -343,7 +490,9 @@ struct patternParser *GetPatternParser( void *theEnv, int rhsType) { - return(PatternData(theEnv)->PatternParserArray[rhsType]); + if (rhsType == 0) return(NULL); + + return(PatternData(theEnv)->PatternParserArray[rhsType-1]); } #if CONSTRUCT_COMPILER && (! RUN_TIME) @@ -371,11 +520,14 @@ globle void PatternNodeHeaderToCode( ((int) theHeader->entryJoin->bsaveID) % maxIndices); } - fprintf(fp,"%d,%d,%d,0,0,%d,%d}",theHeader->singlefieldNode, + PrintHashedExpressionReference(theEnv,fp,theHeader->rightHash,imageID,maxIndices); + + fprintf(fp,",%d,%d,%d,0,0,%d,%d,%d}",theHeader->singlefieldNode, theHeader->multifieldNode, theHeader->stopNode, theHeader->beginSlot, - theHeader->endSlot); + theHeader->endSlot, + theHeader->selector); } #endif /* CONSTRUCT_COMPILER && (! RUN_TIME) */ @@ -420,7 +572,7 @@ globle intBool PostPatternAnalysis( /******************************************************************/ struct lhsParseNode *RestrictionParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int multifieldSlot, struct symbolHashNode *theSlot, @@ -455,6 +607,7 @@ struct lhsParseNode *RestrictionParse( nextNode = GetLHSParseNode(theEnv); nextNode->type = theToken->type; nextNode->negated = FALSE; + nextNode->exists = FALSE; GetToken(theEnv,readSource,theToken); } else @@ -738,7 +891,7 @@ static void TallyFieldTypes( /*******************************************************************/ static struct lhsParseNode *ConjuctiveRestrictionParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int *error) { @@ -966,7 +1119,7 @@ static int CheckForVariableMixing( /***********************************************************/ static struct lhsParseNode *LiteralRestrictionParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int *error) { diff --git a/src/pattern.h b/src/pattern.h index 18ff631..4c6ee09 100644 --- a/src/pattern.h +++ b/src/pattern.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PATTERN HEADER FILE */ /*******************************************************/ @@ -24,6 +24,11 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Added support for hashed alpha memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_pattern @@ -46,6 +51,7 @@ struct patternEntityRecord void (*incrementBasisCount)(void *,void *); void (*matchFunction)(void *,void *); intBool (*synchronized)(void *,void *); + intBool (*isDeleted)(void *,void *); }; typedef struct patternEntityRecord PTRN_ENTITY_RECORD; @@ -56,7 +62,7 @@ struct patternEntity struct patternEntityRecord *theInfo; void *dependents; unsigned busyCount; - long int timeTag; + unsigned long long timeTag; }; typedef struct patternEntity PATTERN_ENTITY; @@ -87,18 +93,18 @@ struct patternParser; struct patternParser { - char *name; + const char *name; struct patternEntityRecord *entityType; int positionInArray; int (*recognizeFunction)(SYMBOL_HN *); - struct lhsParseNode *(*parseFunction)(void *,char *,struct token *); + struct lhsParseNode *(*parseFunction)(void *,const char *,struct token *); int (*postAnalysisFunction)(void *,struct lhsParseNode *); struct patternNodeHeader *(*addPatternFunction)(void *,struct lhsParseNode *); void (*removePatternFunction)(void *,struct patternNodeHeader *); - struct expr *(*genJNConstantFunction)(void *,struct lhsParseNode *); - void (*replaceGetJNValueFunction)(void *,struct expr *,struct lhsParseNode *); - struct expr *(*genGetJNValueFunction)(void *,struct lhsParseNode *); - struct expr *(*genCompareJNValuesFunction)(void *,struct lhsParseNode *,struct lhsParseNode *); + struct expr *(*genJNConstantFunction)(void *,struct lhsParseNode *,int); + void (*replaceGetJNValueFunction)(void *,struct expr *,struct lhsParseNode *,int); + struct expr *(*genGetJNValueFunction)(void *,struct lhsParseNode *,int); + struct expr *(*genCompareJNValuesFunction)(void *,struct lhsParseNode *,struct lhsParseNode *,int); struct expr *(*genPNConstantFunction)(void *,struct lhsParseNode *); void (*replaceGetPNValueFunction)(void *,struct expr *,struct lhsParseNode *); struct expr *(*genGetPNValueFunction)(void *,struct lhsParseNode *); @@ -115,8 +121,8 @@ struct patternParser struct reservedSymbol { - char *theSymbol; - char *reservedBy; + const char *theSymbol; + const char *reservedBy; struct reservedSymbol *next; }; @@ -125,7 +131,7 @@ struct reservedSymbol #define PATTERN_DATA 19 struct patternData - { + { struct patternParser *ListOfPatternParsers; struct patternParser *PatternParserArray[MAX_POSITIONS]; int NextPosition; @@ -134,6 +140,8 @@ struct patternData int GlobalSalience; int GlobalAutoFocus; struct expr *SalienceExpression; + struct patternNodeHashEntry **PatternHashTable; + unsigned long PatternHashTableSize; }; #define PatternData(theEnv) ((struct patternData *) GetEnvironmentData(theEnv,PATTERN_DATA)) @@ -150,22 +158,25 @@ struct patternData LOCALE void InitializePatterns(void *); LOCALE int AddPatternParser(void *,struct patternParser *); - LOCALE struct patternParser *FindPatternParser(void *,char *); + LOCALE struct patternParser *FindPatternParser(void *,const char *); LOCALE void DetachPattern(void *,int,struct patternNodeHeader *); LOCALE void GetNextPatternEntity(void *, struct patternParser **, struct patternEntity **); LOCALE struct patternParser *GetPatternParser(void *,int); - LOCALE struct lhsParseNode *RestrictionParse(void *,char *,struct token *,int, + LOCALE struct lhsParseNode *RestrictionParse(void *,const char *,struct token *,int, struct symbolHashNode *,short, struct constraintRecord *,short); LOCALE int PostPatternAnalysis(void *,struct lhsParseNode *); LOCALE void PatternNodeHeaderToCode(void *,FILE *,struct patternNodeHeader *,int,int); - LOCALE void AddReservedPatternSymbol(void *,char *,char *); - LOCALE intBool ReservedPatternSymbol(void *,char *,char *); - LOCALE void ReservedPatternSymbolErrorMsg(void *,char *,char *); - -#endif + LOCALE void AddReservedPatternSymbol(void *,const char *,const char *); + LOCALE intBool ReservedPatternSymbol(void *,const char *,const char *); + LOCALE void ReservedPatternSymbolErrorMsg(void *,const char *,const char *); + LOCALE void AddHashedPatternNode(void *,void *,void *,unsigned short,void *); + LOCALE intBool RemoveHashedPatternNode(void *,void *,void *,unsigned short,void *); + LOCALE void *FindHashedPatternNode(void *,void *,unsigned short,void *); + +#endif /* _H_pattern */ diff --git a/src/pprint.c b/src/pprint.c index c3ed338..5bc3c76 100644 --- a/src/pprint.c +++ b/src/pprint.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PRETTY PRINT MODULE */ /*******************************************************/ @@ -15,13 +15,20 @@ /* */ /* Contributing Programmer(s): */ /* Chris Culbert */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Corrected code generating compilation */ /* warnings. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _PPRINT_SOURCE_ @@ -36,6 +43,7 @@ #include "constant.h" #include "envrnmnt.h" #include "memalloc.h" +#include "sysdep.h" #include "utility.h" #include "pprint.h" @@ -54,7 +62,7 @@ globle void InitializePrettyPrintData( void *theEnv) { AllocateEnvironmentData(theEnv,PRETTY_PRINT_DATA,sizeof(struct prettyPrintData),DeallocatePrettyPrintData); - + PrettyPrintData(theEnv)->PPBufferEnabled = TRUE; } @@ -65,7 +73,7 @@ globle void InitializePrettyPrintData( static void DeallocatePrettyPrintData( void *theEnv) { - if (PrettyPrintData(theEnv)->PrettyPrintBuffer != NULL) + if (PrettyPrintData(theEnv)->PrettyPrintBuffer != NULL) { rm(theEnv,PrettyPrintData(theEnv)->PrettyPrintBuffer,PrettyPrintData(theEnv)->PPBufferMax); } } @@ -102,18 +110,16 @@ globle void DestroyPPBuffer(void *theEnv) /*********************************************/ globle void SavePPBuffer( void *theEnv, - char *str) + const char *str) { - long int longSize; - int normalSize; - int increment; + size_t increment; /*==========================================*/ /* If the pretty print buffer isn't needed, */ /* then don't bother writing to it. */ /*==========================================*/ - if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || (! PrettyPrintData(theEnv)->PPBufferEnabled)) + if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || (! PrettyPrintData(theEnv)->PPBufferEnabled)) { return; } /*===============================*/ @@ -122,34 +128,20 @@ globle void SavePPBuffer( increment = 512; if (PrettyPrintData(theEnv)->PPBufferPos > increment) - { - increment = PrettyPrintData(theEnv)->PPBufferPos * 3; - if (increment < 0) - { increment = 512; } - } - - /*==================================================*/ - /* The pretty print buffer is limited in size to */ - /* the maximum size of a signed int. Any characters */ - /* beyond that number are discarded. */ - /*==================================================*/ - - normalSize = (int) strlen(str); - longSize = (long) normalSize; - longSize += (long) PrettyPrintData(theEnv)->PPBufferPos + ((long) increment) + 1L; - normalSize += PrettyPrintData(theEnv)->PPBufferPos + increment + 1; - if (normalSize != longSize) return; + { increment = PrettyPrintData(theEnv)->PPBufferPos * 3; } /*================================================*/ /* If the pretty print buffer isn't big enough to */ /* contain the string, then increase its size. */ /*================================================*/ - if ((int) strlen(str) + PrettyPrintData(theEnv)->PPBufferPos + 1 >= (int) PrettyPrintData(theEnv)->PPBufferMax) + if (strlen(str) + PrettyPrintData(theEnv)->PPBufferPos + 1 >= PrettyPrintData(theEnv)->PPBufferMax) { - PrettyPrintData(theEnv)->PrettyPrintBuffer = (char *) genrealloc(theEnv,PrettyPrintData(theEnv)->PrettyPrintBuffer,(unsigned) PrettyPrintData(theEnv)->PPBufferMax, - (unsigned) PrettyPrintData(theEnv)->PPBufferMax + increment); - PrettyPrintData(theEnv)->PPBufferMax += (unsigned int) increment; + PrettyPrintData(theEnv)->PrettyPrintBuffer = + (char *) genrealloc(theEnv,PrettyPrintData(theEnv)->PrettyPrintBuffer, + PrettyPrintData(theEnv)->PPBufferMax, + PrettyPrintData(theEnv)->PPBufferMax + increment); + PrettyPrintData(theEnv)->PPBufferMax += increment; } /*==================================================*/ @@ -175,7 +167,7 @@ globle void SavePPBuffer( globle void PPBackup( void *theEnv) { - if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || + if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || (PrettyPrintData(theEnv)->PrettyPrintBuffer == NULL) || (! PrettyPrintData(theEnv)->PPBufferEnabled)) { return; } @@ -192,13 +184,13 @@ globle void PPBackup( globle char *CopyPPBuffer( void *theEnv) { - unsigned length; + size_t length; char *newString; length = (1 + strlen(PrettyPrintData(theEnv)->PrettyPrintBuffer)) * (int) sizeof (char); newString = (char *) gm2(theEnv,length); - strcpy(newString,PrettyPrintData(theEnv)->PrettyPrintBuffer); + genstrcpy(newString,PrettyPrintData(theEnv)->PrettyPrintBuffer); return(newString); } @@ -221,7 +213,7 @@ globle void PPCRAndIndent( int i; char buffer[120]; - if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || + if ((PrettyPrintData(theEnv)->PPBufferStatus == OFF) || (! PrettyPrintData(theEnv)->PPBufferEnabled)) { return; } @@ -296,7 +288,7 @@ globle int SetPPBufferEnabled( int value) { int oldValue; - + oldValue = PrettyPrintData(theEnv)->PPBufferEnabled; PrettyPrintData(theEnv)->PPBufferEnabled = value; return(oldValue); diff --git a/src/pprint.h b/src/pprint.h index 99ed0d8..504ba0f 100644 --- a/src/pprint.h +++ b/src/pprint.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PRETTY PRINT HEADER FILE */ /*******************************************************/ @@ -17,6 +17,13 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_pprint @@ -25,14 +32,14 @@ #define PRETTY_PRINT_DATA 52 struct prettyPrintData - { + { int PPBufferStatus; int PPBufferEnabled; int IndentationDepth; - int PPBufferPos; - unsigned PPBufferMax; - int PPBackupOnce; - int PPBackupTwice; + size_t PPBufferPos; + size_t PPBufferMax; + size_t PPBackupOnce; + size_t PPBackupTwice; char *PrettyPrintBuffer; }; @@ -51,7 +58,7 @@ struct prettyPrintData LOCALE void InitializePrettyPrintData(void *); LOCALE void FlushPPBuffer(void *); LOCALE void DestroyPPBuffer(void *); - LOCALE void SavePPBuffer(void *,char *); + LOCALE void SavePPBuffer(void *,const char *); LOCALE void PPBackup(void *); LOCALE char *CopyPPBuffer(void *); LOCALE char *GetPPBuffer(void *); diff --git a/src/prccode.c b/src/prccode.c index 63101c4..f3d075e 100644 --- a/src/prccode.c +++ b/src/prccode.c @@ -1,33 +1,48 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ -/***************************************************************/ -/* Purpose: Procedural Code Support Routines for Deffunctions, */ -/* Generic Function Methods,Message-Handlers */ -/* and Rules */ -/* */ -/* Principal Programmer(s): */ -/* Brian L. Donnell */ -/* */ -/* 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. */ -/* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ -/* */ -/* Added pragmas to remove compilation warnings. */ -/* */ -/***************************************************************/ +/**************************************************************/ +/* Purpose: Procedural Code Support Routines for */ +/* Deffunctions, Generic Function Methods, */ +/* Message-Handlersand Rules */ +/* */ +/* 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. */ +/* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Added pragmas to remove compilation warnings. */ +/* */ +/* 6.30: Updated ENTITY_RECORD definitions to include */ +/* additional NULL initializers. */ +/* */ +/* Added ReleaseProcParameters call. */ +/* */ +/* Added tracked memory calls. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/**************************************************************/ /* ========================================= ***************************************** @@ -81,12 +96,13 @@ typedef struct ========================================= ***************************************** */ -static void EvaluateProcParameters(void *,EXPRESSION *,int,char *,char *); +static void EvaluateProcParameters(void *,EXPRESSION *,int,const char *,const char *); static intBool RtnProcParam(void *,void *,DATA_OBJECT *); static intBool GetProcBind(void *,void *,DATA_OBJECT *); static intBool PutProcBind(void *,void *,DATA_OBJECT *); static intBool RtnProcWild(void *,void *,DATA_OBJECT *); static void DeallocateProceduralPrimitiveData(void *); +static void ReleaseProcParameters(void *); #if (! BLOAD_ONLY) && (! RUN_TIME) static int FindProcParameter(SYMBOL_HN *,EXPRESSION *,SYMBOL_HN *); @@ -121,34 +137,34 @@ globle void InstallProcedurePrimitives( void *theEnv) { ENTITY_RECORD procParameterInfo = { "PROC_PARAM", PROC_PARAM,0,1,0,NULL,NULL,NULL, - RtnProcParam,NULL,NULL,NULL,NULL,NULL,NULL }, + RtnProcParam,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }, procWildInfo = { "PROC_WILD_PARAM", PROC_WILD_PARAM,0,1,0,NULL,NULL,NULL, - RtnProcWild,NULL,NULL,NULL,NULL,NULL,NULL }, + RtnProcWild,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }, procGetInfo = { "PROC_GET_BIND", PROC_GET_BIND,0,1,0,NULL,NULL,NULL, - GetProcBind,NULL,NULL,NULL,NULL,NULL,NULL }, + GetProcBind,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }, procBindInfo = { "PROC_BIND", PROC_BIND,0,1,0,NULL,NULL,NULL, - PutProcBind,NULL,NULL,NULL,NULL,NULL,NULL }; + PutProcBind,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; #if ! DEFFUNCTION_CONSTRUCT ENTITY_RECORD deffunctionEntityRecord = { "PCALL", PCALL,0,0,1, NULL,NULL,NULL, EvaluateBadCall, - NULL,NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; #endif #if ! DEFGENERIC_CONSTRUCT ENTITY_RECORD genericEntityRecord = { "GCALL", GCALL,0,0,1, NULL,NULL,NULL, EvaluateBadCall, - NULL,NULL,NULL,NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL }; #endif AllocateEnvironmentData(theEnv,PROCEDURAL_PRIMITIVE_DATA,sizeof(struct proceduralPrimitiveData),DeallocateProceduralPrimitiveData); - memcpy(&ProceduralPrimitiveData(theEnv)->ProcParameterInfo,&procParameterInfo,sizeof(struct entityRecord)); - memcpy(&ProceduralPrimitiveData(theEnv)->ProcWildInfo,&procWildInfo,sizeof(struct entityRecord)); - memcpy(&ProceduralPrimitiveData(theEnv)->ProcGetInfo,&procGetInfo,sizeof(struct entityRecord)); - memcpy(&ProceduralPrimitiveData(theEnv)->ProcBindInfo,&procBindInfo,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->ProcParameterInfo,&procParameterInfo,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->ProcWildInfo,&procWildInfo,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->ProcGetInfo,&procGetInfo,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->ProcBindInfo,&procBindInfo,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&ProceduralPrimitiveData(theEnv)->ProcParameterInfo,PROC_PARAM); InstallPrimitive(theEnv,&ProceduralPrimitiveData(theEnv)->ProcWildInfo,PROC_WILD_PARAM); @@ -156,7 +172,7 @@ globle void InstallProcedurePrimitives( InstallPrimitive(theEnv,&ProceduralPrimitiveData(theEnv)->ProcBindInfo,PROC_BIND); ProceduralPrimitiveData(theEnv)->Oldindex = -1; - + /* =============================================== Make sure a default evaluation function is in place for deffunctions and generic functions @@ -166,12 +182,12 @@ globle void InstallProcedurePrimitives( =============================================== */ #if ! DEFFUNCTION_CONSTRUCT - memcpy(&ProceduralPrimitiveData(theEnv)->DeffunctionEntityRecord,&deffunctionEntityRecord,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->DeffunctionEntityRecord,&deffunctionEntityRecord,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&ProceduralPrimitiveData(theEnv)->DeffunctionEntityRecord,PCALL); #endif #if ! DEFGENERIC_CONSTRUCT - memcpy(&ProceduralPrimitiveData(theEnv)->GenericEntityRecord,&genericEntityRecord,sizeof(struct entityRecord)); + memcpy(&ProceduralPrimitiveData(theEnv)->GenericEntityRecord,&genericEntityRecord,sizeof(struct entityRecord)); InstallPrimitive(theEnv,&ProceduralPrimitiveData(theEnv)->GenericEntityRecord,GCALL); #endif @@ -192,6 +208,7 @@ static void DeallocateProceduralPrimitiveData( void *theEnv) { ReturnMultifield(theEnv,(struct multifield *) ProceduralPrimitiveData(theEnv)->NoParamValue); + ReleaseProcParameters(theEnv); } #if (! BLOAD_ONLY) && (! RUN_TIME) @@ -224,14 +241,14 @@ static void DeallocateProceduralPrimitiveData( ************************************************************/ globle EXPRESSION *ParseProcParameters( void *theEnv, - char *readSource, + const char *readSource, struct token *tkn, EXPRESSION *parameterList, SYMBOL_HN **wildcard, int *min, int *max, int *error, - int (*checkfunc)(void *,char *)) + int (*checkfunc)(void *,const char *)) { EXPRESSION *nextOne,*lastOne,*check; int paramprintp = 0; @@ -350,8 +367,8 @@ NOTES : None *************************************************************************/ globle EXPRESSION *ParseProcActions( void *theEnv, - char *bodytype, - char *readSource, + const char *bodytype, + const char *readSource, struct token *tkn, EXPRESSION *params, SYMBOL_HN *wildcard, @@ -454,7 +471,7 @@ globle EXPRESSION *ParseProcActions( *************************************************************************/ globle int ReplaceProcVars( void *theEnv, - char *bodytype, + const char *bodytype, EXPRESSION *actions, EXPRESSION *parameterList, SYMBOL_HN *wildcard, @@ -513,7 +530,7 @@ globle int ReplaceProcVars( else if ((position > 0) && (boundPosn == 0)) { actions->type = (unsigned short) ((bindName != wildcard) ? PROC_PARAM : PROC_WILD_PARAM); - actions->value = AddBitMap(theEnv,(void *) &position,(int) sizeof(int)); + actions->value = EnvAddBitMap(theEnv,(void *) &position,(int) sizeof(int)); } /*=========================================================*/ @@ -544,7 +561,7 @@ globle int ReplaceProcVars( pvar.first = boundPosn; pvar.second = position; pvar.secondFlag = (bindName != wildcard) ? 0 : 1; - actions->value = AddBitMap(theEnv,(void *) &pvar,(int) sizeof(PACKED_PROC_VAR)); + actions->value = EnvAddBitMap(theEnv,(void *) &pvar,(int) sizeof(PACKED_PROC_VAR)); actions->argList = GenConstant(theEnv,SYMBOL,(void *) bindName); actions->argList->nextArg = altvarexp; } @@ -577,7 +594,7 @@ globle int ReplaceProcVars( { actions->type = PROC_BIND; boundPosn = SearchParsedBindNames(theEnv,(SYMBOL_HN *) actions->argList->value); - actions->value = AddBitMap(theEnv,(void *) &boundPosn,(int) sizeof(intBool)); + actions->value = EnvAddBitMap(theEnv,(void *) &boundPosn,(int) sizeof(intBool)); arg_lvl = actions->argList->nextArg; rtn_struct(theEnv,expr,actions->argList); actions->argList = arg_lvl; @@ -604,7 +621,7 @@ globle EXPRESSION *GenProcWildcardReference( void *theEnv, int theIndex) { - return(GenConstant(theEnv,PROC_WILD_PARAM,AddBitMap(theEnv,(void *) &theIndex,(int) sizeof(int)))); + return(GenConstant(theEnv,PROC_WILD_PARAM,EnvAddBitMap(theEnv,(void *) &theIndex,(int) sizeof(int)))); } #endif @@ -643,8 +660,8 @@ globle void PushProcParameters( void *theEnv, EXPRESSION *parameterList, int numberOfParameters, - char *pname, - char *bodytype, + const char *pname, + const char *bodytype, void (*UnboundErrFunc)(void *)) { register PROC_PARAM_STACK *ptmp; @@ -721,6 +738,63 @@ globle void PopProcParameters( rtn_struct(theEnv,ProcParamStack,ptmp); } +/****************************************************************** + NAME : ReleaseProcParameters + DESCRIPTION : Restores old procedure arrays + INPUTS : None + RETURNS : Nothing useful + SIDE EFFECTS : Stack popped and globals restored + NOTES : Assumes pstack != NULL + ******************************************************************/ +static void ReleaseProcParameters( + void *theEnv) + { + register PROC_PARAM_STACK *ptmp, *next; + + if (ProceduralPrimitiveData(theEnv)->ProcParamArray != NULL) + rm(theEnv,(void *) ProceduralPrimitiveData(theEnv)->ProcParamArray,(sizeof(DATA_OBJECT) * ProceduralPrimitiveData(theEnv)->ProcParamArraySize)); + + + if (ProceduralPrimitiveData(theEnv)->WildcardValue != NULL) + { + if (ProceduralPrimitiveData(theEnv)->WildcardValue->value != ProceduralPrimitiveData(theEnv)->NoParamValue) + { ReturnMultifield(theEnv,(struct multifield *) ProceduralPrimitiveData(theEnv)->WildcardValue->value); } + + rtn_struct(theEnv,dataObject,ProceduralPrimitiveData(theEnv)->WildcardValue); + } + +#if DEFGENERIC_CONSTRUCT + if (ProceduralPrimitiveData(theEnv)->ProcParamExpressions != NULL) + rm(theEnv,(void *) ProceduralPrimitiveData(theEnv)->ProcParamExpressions,(sizeof(EXPRESSION) * ProceduralPrimitiveData(theEnv)->ProcParamArraySize)); +#endif + + ptmp = ProceduralPrimitiveData(theEnv)->pstack; + + while (ptmp != NULL) + { + next = ptmp->nxt; + + if (ptmp->ParamArray != NULL) + { rm(theEnv,(void *) ptmp->ParamArray,(sizeof(DATA_OBJECT) * ptmp->ParamArraySize)); } + +#if DEFGENERIC_CONSTRUCT + if (ptmp->ParamExpressions != NULL) + { rm(theEnv,(void *) ptmp->ParamExpressions,(sizeof(EXPRESSION) * ptmp->ParamArraySize)); } +#endif + + if (ptmp->WildcardValue != NULL) + { + if (ptmp->WildcardValue->value != ProceduralPrimitiveData(theEnv)->NoParamValue) + { ReturnMultifield(theEnv,(struct multifield *) ptmp->WildcardValue->value); } + + rtn_struct(theEnv,dataObject,ptmp->WildcardValue); + } + + rtn_struct(theEnv,ProcParamStack,ptmp); + ptmp = next; + } + } + #if DEFGENERIC_CONSTRUCT /*********************************************************** @@ -791,10 +865,17 @@ globle void EvaluateProcActions( register int i; struct defmodule *oldModule; EXPRESSION *oldActions; + struct trackedMemory *theTM; oldLocalVarArray = ProceduralPrimitiveData(theEnv)->LocalVarArray; ProceduralPrimitiveData(theEnv)->LocalVarArray = (lvarcnt == 0) ? NULL : (DATA_OBJECT *) gm2(theEnv,(sizeof(DATA_OBJECT) * lvarcnt)); + + if (lvarcnt != 0) + { theTM = AddTrackedMemory(theEnv,ProceduralPrimitiveData(theEnv)->LocalVarArray,sizeof(DATA_OBJECT) * lvarcnt); } + else + { theTM = NULL; } + for (i = 0 ; i < lvarcnt ; i++) ProceduralPrimitiveData(theEnv)->LocalVarArray[i].supplementalInfo = EnvFalseSymbol(theEnv); @@ -830,6 +911,7 @@ globle void EvaluateProcActions( if (lvarcnt != 0) { + RemoveTrackedMemory(theEnv,theTM); for (i = 0 ; i < lvarcnt ; i++) if (ProceduralPrimitiveData(theEnv)->LocalVarArray[i].supplementalInfo == EnvTrueSymbol(theEnv)) ValueDeinstall(theEnv,&ProceduralPrimitiveData(theEnv)->LocalVarArray[i]); @@ -850,7 +932,7 @@ globle void EvaluateProcActions( ****************************************************/ globle void PrintProcParamArray( void *theEnv, - char *logName) + const char *logName) { register int i; @@ -973,8 +1055,8 @@ static void EvaluateProcParameters( void *theEnv, EXPRESSION *parameterList, int numberOfParameters, - char *pname, - char *bodytype) + const char *pname, + const char *bodytype) { DATA_OBJECT *rva,temp; int i = 0; @@ -1040,7 +1122,7 @@ static intBool RtnProcParam( DATA_OBJECT *result) { register DATA_OBJECT *src; - + src = &ProceduralPrimitiveData(theEnv)->ProcParamArray[*((int *) ValueToBitMap(value)) - 1]; result->type = src->type; result->value = src->value; @@ -1341,15 +1423,12 @@ static EXPRESSION *CompactActions( contain deffunctions and generic functions which cannot be used ******************************************************/ -#if IBM_TBC -#pragma argsused -#endif static intBool EvaluateBadCall( void *theEnv, void *value, DATA_OBJECT *result) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(value) #endif PrintErrorID(theEnv,"PRCCODE",1,FALSE); diff --git a/src/prccode.h b/src/prccode.h index 8dbd6d7..29283c7 100644 --- a/src/prccode.h +++ b/src/prccode.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* */ /*******************************************************/ @@ -10,14 +10,36 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ -/* Revision History: */ -/* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ -/* */ +/* Revision History: */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Added pragmas to remove compilation warnings. */ +/* */ +/* 6.30: Updated ENTITY_RECORD definitions to include */ +/* additional NULL initializers. */ +/* */ +/* Added ReleaseProcParameters call. */ +/* */ +/* Added tracked memory calls. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_prccode @@ -56,7 +78,7 @@ typedef struct ProcParamStack #define PROCEDURAL_PRIMITIVE_DATA 37 struct proceduralPrimitiveData - { + { void *NoParamValue; DATA_OBJECT *ProcParamArray; int ProcParamArraySize; @@ -68,10 +90,10 @@ struct proceduralPrimitiveData DATA_OBJECT *WildcardValue; DATA_OBJECT *LocalVarArray; void (*ProcUnboundErrFunc)(void *); - ENTITY_RECORD ProcParameterInfo; + ENTITY_RECORD ProcParameterInfo; ENTITY_RECORD ProcWildInfo; - ENTITY_RECORD ProcGetInfo; - ENTITY_RECORD ProcBindInfo; + ENTITY_RECORD ProcGetInfo; + ENTITY_RECORD ProcBindInfo; #if ! DEFFUNCTION_CONSTRUCT ENTITY_RECORD DeffunctionEntityRecord; #endif @@ -93,41 +115,37 @@ struct proceduralPrimitiveData #define LOCALE extern #endif -LOCALE void InstallProcedurePrimitives(void *); + LOCALE void InstallProcedurePrimitives(void *); #if (! BLOAD_ONLY) && (! RUN_TIME) #if DEFFUNCTION_CONSTRUCT || OBJECT_SYSTEM -LOCALE EXPRESSION *ParseProcParameters(void *,char *,struct token *,EXPRESSION *, - SYMBOL_HN **,int *,int *,int *, - int (*)(void *,char *)); -#endif -LOCALE EXPRESSION *ParseProcActions(void *,char *,char *,struct token *,EXPRESSION *,SYMBOL_HN *, - int (*)(void *,EXPRESSION *,void *), - int (*)(void *,EXPRESSION *,void *), - int *,void *); -LOCALE intBool ReplaceProcVars(void *,char *,EXPRESSION *,EXPRESSION *,SYMBOL_HN *, - int (*)(void *,EXPRESSION *,void *),void *); + LOCALE EXPRESSION *ParseProcParameters(void *,const char *,struct token *,EXPRESSION *, + SYMBOL_HN **,int *,int *,int *, + int (*)(void *,const char *)); +#endif + LOCALE EXPRESSION *ParseProcActions(void *,const char *,const char *,struct token *,EXPRESSION *,SYMBOL_HN *, + int (*)(void *,EXPRESSION *,void *), + int (*)(void *,EXPRESSION *,void *), + int *,void *); + LOCALE intBool ReplaceProcVars(void *,const char *,EXPRESSION *,EXPRESSION *,SYMBOL_HN *, + int (*)(void *,EXPRESSION *,void *),void *); #if DEFGENERIC_CONSTRUCT -LOCALE EXPRESSION *GenProcWildcardReference(void *,int); + LOCALE EXPRESSION *GenProcWildcardReference(void *,int); #endif #endif -LOCALE void PushProcParameters(void *,EXPRESSION *,int,char *,char *,void (*)(void *)); -LOCALE void PopProcParameters(void *); + LOCALE void PushProcParameters(void *,EXPRESSION *,int,const char *,const char *,void (*)(void *)); + LOCALE void PopProcParameters(void *); #if DEFGENERIC_CONSTRUCT -LOCALE EXPRESSION *GetProcParamExpressions(void *); + LOCALE EXPRESSION *GetProcParamExpressions(void *); #endif -LOCALE void EvaluateProcActions(void *,struct defmodule *,EXPRESSION *,int, - DATA_OBJECT *,void (*)(void *)); -LOCALE void PrintProcParamArray(void *,char *); -LOCALE void GrabProcWildargs(void *,DATA_OBJECT *,int); - -#endif - - - + LOCALE void EvaluateProcActions(void *,struct defmodule *,EXPRESSION *,int, + DATA_OBJECT *,void (*)(void *)); + LOCALE void PrintProcParamArray(void *,const char *); + LOCALE void GrabProcWildargs(void *,DATA_OBJECT *,int); +#endif /* _H_prccode */ diff --git a/src/prcdrfun.c b/src/prcdrfun.c index 0a86a26..7e0653f 100644 --- a/src/prcdrfun.c +++ b/src/prcdrfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PROCEDURAL FUNCTIONS MODULE */ /*******************************************************/ @@ -13,11 +13,12 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* Changed name of variable exp to theExp */ @@ -26,6 +27,13 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Support for long long integers. */ +/* */ /*************************************************************/ #define _PRCDRFUN_SOURCE_ @@ -54,6 +62,12 @@ #include "globldef.h" #endif +/***************************************/ +/* LOCAL INTERNAL FUNCTION DEFINITIONS */ +/***************************************/ + + static void DeallocateProceduralFunctionData(void *); + /**********************************************/ /* ProceduralFunctionDefinitions: Initializes */ /* the procedural functions. */ @@ -61,13 +75,13 @@ globle void ProceduralFunctionDefinitions( void *theEnv) { - AllocateEnvironmentData(theEnv,PRCDRFUN_DATA,sizeof(struct procedureFunctionData),NULL); + AllocateEnvironmentData(theEnv,PRCDRFUN_DATA,sizeof(struct procedureFunctionData),DeallocateProceduralFunctionData); #if ! RUN_TIME EnvDefineFunction2(theEnv,"if", 'u', PTIEF IfFunction, "IfFunction", NULL); EnvDefineFunction2(theEnv,"while", 'u', PTIEF WhileFunction, "WhileFunction", NULL); EnvDefineFunction2(theEnv,"loop-for-count",'u', PTIEF LoopForCountFunction, "LoopForCountFunction", NULL); - EnvDefineFunction2(theEnv,"(get-loop-count)",'l', PTIEF GetLoopCount, "GetLoopCount", NULL); + EnvDefineFunction2(theEnv,"(get-loop-count)",'g', PTIEF GetLoopCount, "GetLoopCount", NULL); EnvDefineFunction2(theEnv,"bind", 'u', PTIEF BindFunction, "BindFunction", NULL); EnvDefineFunction2(theEnv,"progn", 'u', PTIEF PrognFunction, "PrognFunction", NULL); EnvDefineFunction2(theEnv,"return", 'u', PTIEF ReturnFunction, "ReturnFunction",NULL); @@ -83,6 +97,28 @@ globle void ProceduralFunctionDefinitions( FuncSeqOvlFlags(theEnv,"return",FALSE,FALSE); FuncSeqOvlFlags(theEnv,"switch",FALSE,FALSE); #endif + + EnvAddResetFunction(theEnv,"bind",FlushBindList,0); + EnvAddClearFunction(theEnv,"bind",FlushBindList,0); + } + +/*************************************************************/ +/* DeallocateProceduralFunctionData: Deallocates environment */ +/* data for procedural functions. */ +/*************************************************************/ +static void DeallocateProceduralFunctionData( + void *theEnv) + { + DATA_OBJECT_PTR nextPtr, garbagePtr; + + garbagePtr = ProcedureFunctionData(theEnv)->BindList; + + while (garbagePtr != NULL) + { + nextPtr = garbagePtr->next; + rtn_struct(theEnv,dataObject,garbagePtr); + garbagePtr = nextPtr; + } } /***************************************/ @@ -94,13 +130,19 @@ globle void WhileFunction( DATA_OBJECT_PTR returnValue) { DATA_OBJECT theResult; - + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; + /*====================================================*/ /* Evaluate the body of the while loop as long as the */ /* while condition evaluates to a non-FALSE value. */ /*====================================================*/ - EvaluationData(theEnv)->CurrentEvaluationDepth++; + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + EnvRtnUnknown(theEnv,1,&theResult); while (((theResult.value != EnvFalseSymbol(theEnv)) || (theResult.type != SYMBOL)) && @@ -108,17 +150,17 @@ globle void WhileFunction( { if ((ProcedureFunctionData(theEnv)->BreakFlag == TRUE) || (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE)) break; + EnvRtnUnknown(theEnv,2,&theResult); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - if (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE) - { PropagateReturnValue(theEnv,&theResult); } - PeriodicCleanup(theEnv,FALSE,TRUE); - EvaluationData(theEnv)->CurrentEvaluationDepth++; + if ((ProcedureFunctionData(theEnv)->BreakFlag == TRUE) || (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE)) break; + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + EnvRtnUnknown(theEnv,1,&theResult); } - EvaluationData(theEnv)->CurrentEvaluationDepth--; /*=====================================================*/ /* Reset the break flag. The return flag is not reset */ @@ -146,19 +188,24 @@ globle void WhileFunction( returnValue->type = SYMBOL; returnValue->value = EnvFalseSymbol(theEnv); } + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,returnValue); + CallPeriodicTasks(theEnv); } -/**********************************************/ -/* LoopForCountFunction: H/L access routine */ -/* for the loop-for-count function. */ -/**********************************************/ +/********************************************/ +/* LoopForCountFunction: H/L access routine */ +/* for the loop-for-count function. */ +/********************************************/ globle void LoopForCountFunction( void *theEnv, DATA_OBJECT_PTR loopResult) { DATA_OBJECT arg_ptr; - long iterationEnd; + long long iterationEnd; LOOP_COUNTER_STACK *tmpCounter; + struct garbageFrame newGarbageFrame; + struct garbageFrame *oldGarbageFrame; tmpCounter = get_struct(theEnv,loopCounterStack); tmpCounter->loopCounter = 0L; @@ -181,20 +228,27 @@ globle void LoopForCountFunction( rtn_struct(theEnv,loopCounterStack,tmpCounter); return; } + + oldGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + memset(&newGarbageFrame,0,sizeof(struct garbageFrame)); + newGarbageFrame.priorFrame = oldGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame = &newGarbageFrame; + iterationEnd = DOToLong(arg_ptr); while ((tmpCounter->loopCounter <= iterationEnd) && (EvaluationData(theEnv)->HaltExecution != TRUE)) { if ((ProcedureFunctionData(theEnv)->BreakFlag == TRUE) || (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE)) break; - EvaluationData(theEnv)->CurrentEvaluationDepth++; + EnvRtnUnknown(theEnv,3,&arg_ptr); - EvaluationData(theEnv)->CurrentEvaluationDepth--; - if (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE) - { PropagateReturnValue(theEnv,&arg_ptr); } - PeriodicCleanup(theEnv,FALSE,TRUE); + if ((ProcedureFunctionData(theEnv)->BreakFlag == TRUE) || (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE)) break; + + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + tmpCounter->loopCounter++; } @@ -213,12 +267,15 @@ globle void LoopForCountFunction( } ProcedureFunctionData(theEnv)->LoopCounterStack = tmpCounter->nxt; rtn_struct(theEnv,loopCounterStack,tmpCounter); + + RestorePriorGarbageFrame(theEnv,&newGarbageFrame,oldGarbageFrame,loopResult); + CallPeriodicTasks(theEnv); } -/************************************************/ -/* GetLoopCount */ -/************************************************/ -globle long GetLoopCount( +/*****************/ +/* GetLoopCount: */ +/*****************/ +globle long long GetLoopCount( void *theEnv) { int depth; @@ -441,6 +498,7 @@ globle void BindFunction( { theBind = get_struct(theEnv,dataObject); theBind->supplementalInfo = (void *) variableName; + IncrementSymbolCount(variableName); theBind->next = NULL; if (lastBind == NULL) { ProcedureFunctionData(theEnv)->BindList = theBind; } @@ -473,6 +531,7 @@ globle void BindFunction( { if (lastBind == NULL) ProcedureFunctionData(theEnv)->BindList = theBind->next; else lastBind->next = theBind->next; + DecrementSymbolCount(theEnv,(struct symbolHashNode *) theBind->supplementalInfo); rtn_struct(theEnv,dataObject,theBind); returnValue->type = SYMBOL; returnValue->value = EnvFalseSymbol(theEnv); @@ -489,7 +548,7 @@ globle intBool GetBoundVariable( SYMBOL_HN *varName) { DATA_OBJECT_PTR bindPtr; - + for (bindPtr = ProcedureFunctionData(theEnv)->BindList; bindPtr != NULL; bindPtr = bindPtr->next) { if (bindPtr->supplementalInfo == (void *) varName) @@ -512,7 +571,7 @@ globle intBool GetBoundVariable( globle void FlushBindList( void *theEnv) { - ReturnValues(theEnv,ProcedureFunctionData(theEnv)->BindList); + ReturnValues(theEnv,ProcedureFunctionData(theEnv)->BindList,TRUE); ProcedureFunctionData(theEnv)->BindList = NULL; } @@ -524,24 +583,24 @@ globle void PrognFunction( void *theEnv, DATA_OBJECT_PTR returnValue) { - int numa, i; + struct expr *argPtr; - numa = EnvRtnArgCount(theEnv); + argPtr = EvaluationData(theEnv)->CurrentExpression->argList; - if (numa == 0) + if (argPtr == NULL) { returnValue->type = SYMBOL; returnValue->value = EnvFalseSymbol(theEnv); return; } - i = 1; - while ((i <= numa) && (GetHaltExecution(theEnv) != TRUE)) + while ((argPtr != NULL) && (GetHaltExecution(theEnv) != TRUE)) { - EnvRtnUnknown(theEnv,i,returnValue); + EvaluateExpression(theEnv,argPtr,returnValue); + if ((ProcedureFunctionData(theEnv)->BreakFlag == TRUE) || (ProcedureFunctionData(theEnv)->ReturnFlag == TRUE)) break; - i++; + argPtr = argPtr->nextArg; } if (GetHaltExecution(theEnv) == TRUE) diff --git a/src/prcdrfun.h b/src/prcdrfun.h index b1da4f1..c884377 100644 --- a/src/prcdrfun.h +++ b/src/prcdrfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PROCEDURAL FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -11,14 +11,27 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Support for long long integers. */ +/* */ /*************************************************************/ #ifndef _H_prcdrfun @@ -41,14 +54,14 @@ typedef struct loopCounterStack { - long loopCounter; + long long loopCounter; struct loopCounterStack *nxt; } LOOP_COUNTER_STACK; #define PRCDRFUN_DATA 13 struct procedureFunctionData - { + { int ReturnFlag; int BreakFlag; LOOP_COUNTER_STACK *LoopCounterStack; @@ -60,7 +73,7 @@ struct procedureFunctionData LOCALE void ProceduralFunctionDefinitions(void *); LOCALE void WhileFunction(void *,DATA_OBJECT_PTR); LOCALE void LoopForCountFunction(void *,DATA_OBJECT_PTR); - LOCALE long GetLoopCount(void *); + LOCALE long long GetLoopCount(void *); LOCALE void IfFunction(void *,DATA_OBJECT_PTR); LOCALE void BindFunction(void *,DATA_OBJECT_PTR); LOCALE void PrognFunction(void *,DATA_OBJECT_PTR); @@ -70,7 +83,7 @@ struct procedureFunctionData LOCALE intBool GetBoundVariable(void *,struct dataObject *,struct symbolHashNode *); LOCALE void FlushBindList(void *); -#endif +#endif /* _H_prcdrfun */ diff --git a/src/prcdrpsr.c b/src/prcdrpsr.c index b8f1bd1..6ee940c 100644 --- a/src/prcdrpsr.c +++ b/src/prcdrpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PROCEDURAL FUNCTIONS PARSER MODULE */ /*******************************************************/ @@ -11,17 +11,29 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable exp to theExp */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #define _PRCDRPSR_SOURCE_ @@ -56,7 +68,7 @@ #define PRCDRPSR_DATA 12 struct procedureParserData - { + { struct BindInfo *ListOfParsedBindNames; }; @@ -67,17 +79,20 @@ struct procedureParserData /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ -#if (! RUN_TIME) && (! BLOAD_ONLY) - static struct expr *WhileParse(void *,struct expr *,char *); - static struct expr *LoopForCountParse(void *,struct expr *,char *); +#if (! RUN_TIME) + static void DeallocateProceduralFunctionData(void *); +#if (! BLOAD_ONLY) + static struct expr *WhileParse(void *,struct expr *,const char *); + static struct expr *LoopForCountParse(void *,struct expr *,const char *); static void ReplaceLoopCountVars(void *,SYMBOL_HN *,EXPRESSION *,int); - static struct expr *IfParse(void *,struct expr *,char *); - static struct expr *PrognParse(void *,struct expr *,char *); - static struct expr *BindParse(void *,struct expr *,char *); + static struct expr *IfParse(void *,struct expr *,const char *); + static struct expr *PrognParse(void *,struct expr *,const char *); + static struct expr *BindParse(void *,struct expr *,const char *); static int AddBindName(void *,struct symbolHashNode *,CONSTRAINT_RECORD *); - static struct expr *ReturnParse(void *,struct expr *,char *); - static struct expr *BreakParse(void *,struct expr *,char *); - static struct expr *SwitchParse(void *,struct expr *,char *); + static struct expr *ReturnParse(void *,struct expr *,const char *); + static struct expr *BreakParse(void *,struct expr *,const char *); + static struct expr *SwitchParse(void *,struct expr *,const char *); +#endif #endif #if ! RUN_TIME @@ -87,7 +102,7 @@ struct procedureParserData globle void ProceduralFunctionParsers( void *theEnv) { - AllocateEnvironmentData(theEnv,PRCDRPSR_DATA,sizeof(struct procedureParserData),NULL); + AllocateEnvironmentData(theEnv,PRCDRPSR_DATA,sizeof(struct procedureParserData),DeallocateProceduralFunctionData); #if (! BLOAD_ONLY) AddFunctionParser(theEnv,"bind",BindParse); @@ -101,6 +116,23 @@ globle void ProceduralFunctionParsers( #endif } +/*************************************************************/ +/* DeallocateProceduralFunctionData: Deallocates environment */ +/* data for procedural functions. */ +/*************************************************************/ +static void DeallocateProceduralFunctionData( + void *theEnv) + { + struct BindInfo *temp_bind; + + while (ProcedureParserData(theEnv)->ListOfParsedBindNames != NULL) + { + temp_bind = ProcedureParserData(theEnv)->ListOfParsedBindNames->next; + rtn_struct(theEnv,BindInfo,ProcedureParserData(theEnv)->ListOfParsedBindNames); + ProcedureParserData(theEnv)->ListOfParsedBindNames = temp_bind; + } + } + /********************************************************/ /* GetParsedBindNames: */ /********************************************************/ @@ -158,7 +190,7 @@ globle intBool ParsedBindNamesEmpty( static struct expr *WhileParse( void *theEnv, struct expr *parse, - char *infile) + const char *infile) { struct token theToken; int read_first_paren; @@ -247,7 +279,7 @@ static struct expr *WhileParse( static struct expr *LoopForCountParse( void *theEnv, struct expr *parse, - char *infile) + const char *infile) { struct token theToken; SYMBOL_HN *loopVar = NULL; @@ -267,7 +299,7 @@ static struct expr *LoopForCountParse( ========================================== */ if (theToken.type != LPAREN) { - parse->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1L)); + parse->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1LL)); parse->argList->nextArg = ParseAtomOrExpression(theEnv,infile,&theToken); if (parse->argList->nextArg == NULL) { @@ -282,7 +314,7 @@ static struct expr *LoopForCountParse( { if (theToken.type != SYMBOL) goto LoopForCountParseError; - parse->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1L)); + parse->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1LL)); parse->argList->nextArg = Function2Parse(theEnv,infile,ValueToString(theToken.value)); if (parse->argList->nextArg == NULL) { @@ -313,7 +345,7 @@ static struct expr *LoopForCountParse( PPBackup(theEnv); PPBackup(theEnv); SavePPBuffer(theEnv,theToken.printForm); - tmpexp = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1L)); + tmpexp = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,1LL)); tmpexp->nextArg = parse->argList; parse->argList = tmpexp; } @@ -442,7 +474,7 @@ static void ReplaceLoopCountVars( { theExp->type = FCALL; theExp->value = (void *) FindFunction(theEnv,"(get-loop-count)"); - theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long) depth)); + theExp->argList = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long long) depth)); } else if (theExp->argList != NULL) { @@ -465,7 +497,7 @@ static void ReplaceLoopCountVars( static struct expr *IfParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token theToken; @@ -586,7 +618,7 @@ static struct expr *IfParse( static struct expr *PrognParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token tkn; struct expr *tmp; @@ -612,7 +644,7 @@ static struct expr *PrognParse( static struct expr *BindParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token theToken; SYMBOL_HN *variableName; @@ -695,7 +727,7 @@ static struct expr *BindParse( static struct expr *ReturnParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { int error_flag = FALSE; struct token theToken; @@ -748,7 +780,7 @@ static struct expr *ReturnParse( static struct expr *BreakParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token theToken; @@ -780,7 +812,7 @@ static struct expr *BreakParse( static struct expr *SwitchParse( void *theEnv, struct expr *top, - char *infile) + const char *infile) { struct token theToken; EXPRESSION *theExp,*chk; diff --git a/src/prcdrpsr.h b/src/prcdrpsr.h index 3346e86..9b440a5 100644 --- a/src/prcdrpsr.h +++ b/src/prcdrpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PROCEDURAL FUNCTIONS PARSER HEADER FILE */ /*******************************************************/ @@ -11,14 +11,29 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable exp to theExp */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Local variables set with the bind function */ +/* persist until a reset/clear command is issued. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #ifndef _H_prcdrpsr @@ -60,7 +75,7 @@ struct BindInfo LOCALE struct constraintRecord *FindBindConstraints(void *,struct symbolHashNode *); #endif -#endif +#endif /* _H_prcdrpsr */ diff --git a/src/prdctfun.c b/src/prdctfun.c index 81d4077..49ff81a 100644 --- a/src/prdctfun.c +++ b/src/prdctfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PREDICATE FUNCTIONS MODULE */ /*******************************************************/ @@ -19,10 +19,17 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ /*************************************************************/ #define _PRDCTFUN_SOURCE_ @@ -76,7 +83,7 @@ globle void PredicateFunctionDefinitions( EnvDefineFunction2(theEnv,"sequencep",'b', MultifieldpFunction, "MultifieldpFunction", "11"); EnvDefineFunction2(theEnv,"pointerp", 'b', PointerpFunction, "PointerpFunction", "11"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -361,7 +368,7 @@ globle intBool NotFunction( if ((result.value == EnvFalseSymbol(theEnv)) && (result.type == SYMBOL)) { return(TRUE); } - + return(FALSE); } @@ -829,7 +836,7 @@ globle intBool OddpFunction( void *theEnv) { DATA_OBJECT item; - long num, halfnum; + long long num, halfnum; if (EnvArgCountCheck(theEnv,"oddp",EXACTLY,1) == -1) return(FALSE); if (EnvArgTypeCheck(theEnv,"oddp",1,INTEGER,&item) == FALSE) return(FALSE); @@ -850,7 +857,7 @@ globle intBool EvenpFunction( void *theEnv) { DATA_OBJECT item; - long num, halfnum; + long long num, halfnum; if (EnvArgCountCheck(theEnv,"evenp",EXACTLY,1) == -1) return(FALSE); if (EnvArgTypeCheck(theEnv,"evenp",1,INTEGER,&item) == FALSE) return(FALSE); diff --git a/src/prdctfun.h b/src/prdctfun.h index 6905fbe..b3c1915 100644 --- a/src/prdctfun.h +++ b/src/prdctfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* PREDICATE FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -16,8 +16,16 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ /*************************************************************/ #ifndef _H_prdctfun @@ -57,7 +65,7 @@ LOCALE intBool OddpFunction(void *); LOCALE intBool EvenpFunction(void *); -#endif +#endif /* _H_prdctfun */ diff --git a/src/prntutil.c b/src/prntutil.c index cfed606..ef9c4e7 100644 --- a/src/prntutil.c +++ b/src/prntutil.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* PRINT UTILITY MODULE */ /*******************************************************/ @@ -14,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -26,6 +26,25 @@ /* */ /* Added SlotExistError function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Support for DATA_OBJECT_ARRAY primitive. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* Used gensprintf and genstrcat instead of */ +/* sprintf and strcat. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added code for capturing errors/warnings. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #define _PRNTUTIL_SOURCE_ @@ -45,9 +64,11 @@ #include "router.h" #include "multifun.h" #include "factmngr.h" +#include "cstrcpsr.h" #include "inscom.h" #include "insmngr.h" #include "memalloc.h" +#include "sysdep.h" #include "prntutil.h" @@ -68,9 +89,20 @@ globle void InitializePrintUtilityData( /***********************************************************/ globle void PrintInChunks( void *theEnv, - char *logicalName, - char *bigString) + const char *logicalName, + const char *bigString) { + /*=====================================================*/ + /* This function was originally added because VMS had */ + /* a bug that didn't allow printing a string greater */ + /* than 512 bytes. Since this was over 25 years ago, */ + /* we'll assume no modern compiler has this limitation */ + /* and just print the entire string. */ + /*=====================================================*/ + + EnvPrintRouter(theEnv,logicalName,bigString); + +/* char tc, *subString; subString = bigString; @@ -88,6 +120,7 @@ globle void PrintInChunks( } EnvPrintRouter(theEnv,logicalName,subString); +*/ } /************************************************************/ @@ -95,10 +128,10 @@ globle void PrintInChunks( /************************************************************/ globle void PrintFloat( void *theEnv, - char *fileid, + const char *fileid, double number) { - char *theString; + const char *theString; theString = FloatToString(theEnv,number); EnvPrintRouter(theEnv,fileid,theString); @@ -109,12 +142,12 @@ globle void PrintFloat( /****************************************************/ globle void PrintLongInteger( void *theEnv, - char *logicalName, - long int number) + const char *logicalName, + long long number) { char printBuffer[32]; - sprintf(printBuffer,"%ld",number); + gensprintf(printBuffer,"%lld",number); EnvPrintRouter(theEnv,logicalName,printBuffer); } @@ -123,10 +156,11 @@ globle void PrintLongInteger( /**************************************/ globle void PrintAtom( void *theEnv, - char *logicalName, + const char *logicalName, int type, void *value) { + struct externalAddressHashNode *theAddress; char buffer[20]; switch (type) @@ -151,12 +185,37 @@ globle void PrintAtom( } break; - case EXTERNAL_ADDRESS: + case DATA_OBJECT_ARRAY: if (PrintUtilityData(theEnv)->AddressesToStrings) EnvPrintRouter(theEnv,logicalName,"\""); + EnvPrintRouter(theEnv,logicalName,"<Pointer-"); - sprintf(buffer,"%p",value); + gensprintf(buffer,"%p",value); EnvPrintRouter(theEnv,logicalName,buffer); EnvPrintRouter(theEnv,logicalName,">"); + + if (PrintUtilityData(theEnv)->AddressesToStrings) EnvPrintRouter(theEnv,logicalName,"\""); + break; + + case EXTERNAL_ADDRESS: + theAddress = (struct externalAddressHashNode *) value; + + if (PrintUtilityData(theEnv)->AddressesToStrings) EnvPrintRouter(theEnv,logicalName,"\""); + + if ((EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type] != NULL) && + (EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type]->longPrintFunction != NULL)) + { (*EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type]->longPrintFunction)(theEnv,logicalName,value); } + else + { + EnvPrintRouter(theEnv,logicalName,"<Pointer-"); + + gensprintf(buffer,"%d-",theAddress->type); + EnvPrintRouter(theEnv,logicalName,buffer); + + gensprintf(buffer,"%p",ValueToExternalAddress(value)); + EnvPrintRouter(theEnv,logicalName,buffer); + EnvPrintRouter(theEnv,logicalName,">"); + } + if (PrintUtilityData(theEnv)->AddressesToStrings) EnvPrintRouter(theEnv,logicalName,"\""); break; @@ -190,10 +249,10 @@ globle void PrintAtom( /**********************************************************/ globle void PrintTally( void *theEnv, - char *logicalName, - long count, - char *singular, - char *plural) + const char *logicalName, + long long count, + const char *singular, + const char *plural) { if (count == 0) return; @@ -213,10 +272,15 @@ globle void PrintTally( /********************************************/ globle void PrintErrorID( void *theEnv, - char *module, + const char *module, int errorID, int printCR) { +#if (! RUN_TIME) && (! BLOAD_ONLY) + FlushParsingMessages(theEnv); + EnvSetErrorFileName(theEnv,EnvGetParsingFileName(theEnv)); + ConstructData(theEnv)->ErrLineNumber = GetLineCount(theEnv); +#endif if (printCR) EnvPrintRouter(theEnv,WERROR,"\n"); EnvPrintRouter(theEnv,WERROR,"["); EnvPrintRouter(theEnv,WERROR,module); @@ -230,10 +294,15 @@ globle void PrintErrorID( /**********************************************/ globle void PrintWarningID( void *theEnv, - char *module, + const char *module, int warningID, int printCR) { +#if (! RUN_TIME) && (! BLOAD_ONLY) + FlushParsingMessages(theEnv); + EnvSetWarningFileName(theEnv,EnvGetParsingFileName(theEnv)); + ConstructData(theEnv)->WrnLineNumber = GetLineCount(theEnv); +#endif if (printCR) EnvPrintRouter(theEnv,WWARNING,"\n"); EnvPrintRouter(theEnv,WWARNING,"["); EnvPrintRouter(theEnv,WWARNING,module); @@ -247,8 +316,8 @@ globle void PrintWarningID( /***************************************************/ globle void CantFindItemErrorMessage( void *theEnv, - char *itemType, - char *itemName) + const char *itemType, + const char *itemName) { PrintErrorID(theEnv,"PRNTUTIL",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to find "); @@ -264,9 +333,9 @@ globle void CantFindItemErrorMessage( /*****************************************************/ globle void CantFindItemInFunctionErrorMessage( void *theEnv, - char *itemType, - char *itemName, - char *func) + const char *itemType, + const char *itemName, + const char *func) { PrintErrorID(theEnv,"PRNTUTIL",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to find "); @@ -284,8 +353,8 @@ globle void CantFindItemInFunctionErrorMessage( /*****************************************************/ globle void CantDeleteItemErrorMessage( void *theEnv, - char *itemType, - char *itemName) + const char *itemType, + const char *itemName) { PrintErrorID(theEnv,"PRNTUTIL",4,FALSE); EnvPrintRouter(theEnv,WERROR,"Unable to delete "); @@ -301,8 +370,8 @@ globle void CantDeleteItemErrorMessage( /****************************************************/ globle void AlreadyParsedErrorMessage( void *theEnv, - char *itemType, - char *itemName) + const char *itemType, + const char *itemName) { PrintErrorID(theEnv,"PRNTUTIL",5,TRUE); EnvPrintRouter(theEnv,WERROR,"The "); @@ -316,7 +385,7 @@ globle void AlreadyParsedErrorMessage( /*********************************************************/ globle void SyntaxErrorMessage( void *theEnv, - char *location) + const char *location) { PrintErrorID(theEnv,"PRNTUTIL",2,TRUE); EnvPrintRouter(theEnv,WERROR,"Syntax Error"); @@ -337,7 +406,7 @@ globle void SyntaxErrorMessage( /****************************************************/ globle void LocalVariableErrorMessage( void *theEnv, - char *byWhat) + const char *byWhat) { PrintErrorID(theEnv,"PRNTUTIL",6,TRUE); EnvPrintRouter(theEnv,WERROR,"Local variables can not be accessed by "); @@ -351,7 +420,7 @@ globle void LocalVariableErrorMessage( /******************************************/ globle void SystemError( void *theEnv, - char *module, + const char *module, int errorID) { PrintErrorID(theEnv,"PRNTUTIL",3,TRUE); @@ -377,7 +446,7 @@ globle void SystemError( /*******************************************************/ globle void DivideByZeroErrorMessage( void *theEnv, - char *functionName) + const char *functionName) { PrintErrorID(theEnv,"PRNTUTIL",7,FALSE); EnvPrintRouter(theEnv,WERROR,"Attempt to divide by zero in "); @@ -388,7 +457,7 @@ globle void DivideByZeroErrorMessage( /*******************************************************/ /* FloatToString: Converts number to KB string format. */ /*******************************************************/ -globle char *FloatToString( +globle const char *FloatToString( void *theEnv, double number) { @@ -397,7 +466,7 @@ globle char *FloatToString( char x; void *thePtr; - sprintf(floatString,"%.15g",number); + gensprintf(floatString,"%.15g",number); for (i = 0; (x = floatString[i]) != '\0'; i++) { @@ -408,7 +477,7 @@ globle char *FloatToString( } } - strcat(floatString,".0"); + genstrcat(floatString,".0"); thePtr = EnvAddSymbol(theEnv,floatString); return(ValueToString(thePtr)); @@ -417,14 +486,14 @@ globle char *FloatToString( /*******************************************************************/ /* LongIntegerToString: Converts long integer to KB string format. */ /*******************************************************************/ -globle char *LongIntegerToString( +globle const char *LongIntegerToString( void *theEnv, - long number) + long long number) { - char buffer[30]; + char buffer[50]; void *thePtr; - sprintf(buffer,"%ld",number); + gensprintf(buffer,"%lld",number); thePtr = EnvAddSymbol(theEnv,buffer); return(ValueToString(thePtr)); @@ -433,16 +502,18 @@ globle char *LongIntegerToString( /*******************************************************************/ /* DataObjectToString: Converts a DATA_OBJECT to KB string format. */ /*******************************************************************/ -globle char *DataObjectToString( +globle const char *DataObjectToString( void *theEnv, DATA_OBJECT *theDO) { void *thePtr; - char *theString, *newString; - char *prefix, *postfix; - unsigned int length; + const char *theString; + char *newString; + const char *prefix, *postfix; + size_t length; + struct externalAddressHashNode *theAddress; char buffer[30]; - + switch (GetpType(theDO)) { case MULTIFIELD: @@ -450,28 +521,28 @@ globle char *DataObjectToString( theString = ValueToString(ImplodeMultifield(theEnv,theDO)); postfix = ")"; break; - + case STRING: prefix = "\""; theString = DOPToString(theDO); postfix = "\""; break; - + case INSTANCE_NAME: prefix = "["; theString = DOPToString(theDO); postfix = "]"; break; - + case SYMBOL: return(DOPToString(theDO)); - + case FLOAT: return(FloatToString(theEnv,DOPToDouble(theDO))); - + case INTEGER: return(LongIntegerToString(theEnv,DOPToLong(theDO))); - + case RVOID: return(""); @@ -481,7 +552,7 @@ globle char *DataObjectToString( if (thePtr == (void *) &InstanceData(theEnv)->DummyInstance) { return("<Dummy Instance>"); } - + if (((struct instance *) thePtr)->garbage) { prefix = "<Stale Instance-"; @@ -494,49 +565,51 @@ globle char *DataObjectToString( theString = ValueToString(GetFullInstanceName(theEnv,(INSTANCE_TYPE *) thePtr)); postfix = ">"; } - + break; #endif - + case EXTERNAL_ADDRESS: - sprintf(buffer,"<Pointer-%p>",DOPToPointer(theDO)); + theAddress = (struct externalAddressHashNode *) DOPToPointer(theDO); + /* TBD Need specific routine for creating name string. */ + gensprintf(buffer,"<Pointer-%d-%p>",(int) theAddress->type,DOPToExternalAddress(theDO)); thePtr = EnvAddSymbol(theEnv,buffer); return(ValueToString(thePtr)); -#if DEFTEMPLATE_CONSTRUCT +#if DEFTEMPLATE_CONSTRUCT case FACT_ADDRESS: if (DOPToPointer(theDO) == (void *) &FactData(theEnv)->DummyFact) { return("<Dummy Fact>"); } - + thePtr = DOPToPointer(theDO); - sprintf(buffer,"<Fact-%ld>",((struct fact *) thePtr)->factIndex); + gensprintf(buffer,"<Fact-%lld>",((struct fact *) thePtr)->factIndex); thePtr = EnvAddSymbol(theEnv,buffer); return(ValueToString(thePtr)); #endif - + default: - return("TBD"); + return("UNK"); } - + length = strlen(prefix) + strlen(theString) + strlen(postfix) + 1; newString = (char *) genalloc(theEnv,length); newString[0] = '\0'; - strcat(newString,prefix); - strcat(newString,theString); - strcat(newString,postfix); + genstrcat(newString,prefix); + genstrcat(newString,theString); + genstrcat(newString,postfix); thePtr = EnvAddSymbol(theEnv,newString); genfree(theEnv,newString,length); return(ValueToString(thePtr)); } - + /************************************************************/ /* SalienceInformationError: Error message for errors which */ /* occur during the evaluation of a salience value. */ /************************************************************/ globle void SalienceInformationError( void *theEnv, - char *constructType, - char *constructName) + const char *constructType, + const char *constructName) { PrintErrorID(theEnv,"PRNTUTIL",8,TRUE); EnvPrintRouter(theEnv,WERROR,"This error occurred while evaluating the salience"); @@ -587,8 +660,8 @@ globle void SalienceNonIntegerError( /***************************************************/ globle void SlotExistError( void *theEnv, - char *sname, - char *func) + const char *sname, + const char *func) { PrintErrorID(theEnv,"INSFUN",3,FALSE); EnvPrintRouter(theEnv,WERROR,"No such slot "); diff --git a/src/prntutil.h b/src/prntutil.h index 002b0ae..c4aec44 100644 --- a/src/prntutil.h +++ b/src/prntutil.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* PRINT UTILITY HEADER FILE */ /*******************************************************/ @@ -25,6 +25,25 @@ /* */ /* Added SlotExistError function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Support for DATA_OBJECT_ARRAY primitive. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* Used gensprintf and genstrcat instead of */ +/* sprintf and strcat. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added code for capturing errors/warnings. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #ifndef _H_prntutil @@ -42,7 +61,7 @@ #define PRINT_UTILITY_DATA 53 struct printUtilityData - { + { intBool PreserveEscapedCharacters; intBool AddressesToStrings; intBool InstanceAddressesToNames; @@ -59,31 +78,32 @@ struct printUtilityData #else #define LOCALE extern #endif + LOCALE void InitializePrintUtilityData(void *); - LOCALE void PrintInChunks(void *,char *,char *); - LOCALE void PrintFloat(void *,char *,double); - LOCALE void PrintLongInteger(void *,char *,long); - LOCALE void PrintAtom(void *,char *,int,void *); - LOCALE void PrintTally(void *,char *,long,char *,char *); - LOCALE char *FloatToString(void *,double); - LOCALE char *LongIntegerToString(void *,long); - LOCALE char *DataObjectToString(void *,DATA_OBJECT *); - LOCALE void SyntaxErrorMessage(void *,char *); - LOCALE void SystemError(void *,char *,int); - LOCALE void PrintErrorID(void *,char *,int,int); - LOCALE void PrintWarningID(void *,char *,int,int); - LOCALE void CantFindItemErrorMessage(void *,char *,char *); - LOCALE void CantDeleteItemErrorMessage(void *,char *,char *); - LOCALE void AlreadyParsedErrorMessage(void *,char *,char *); - LOCALE void LocalVariableErrorMessage(void *,char *); - LOCALE void DivideByZeroErrorMessage(void *,char *); - LOCALE void SalienceInformationError(void *,char *,char *); + LOCALE void PrintInChunks(void *,const char *,const char *); + LOCALE void PrintFloat(void *,const char *,double); + LOCALE void PrintLongInteger(void *,const char *,long long); + LOCALE void PrintAtom(void *,const char *,int,void *); + LOCALE void PrintTally(void *,const char *,long long,const char *,const char *); + LOCALE const char *FloatToString(void *,double); + LOCALE const char *LongIntegerToString(void *,long long); + LOCALE const char *DataObjectToString(void *,DATA_OBJECT *); + LOCALE void SyntaxErrorMessage(void *,const char *); + LOCALE void SystemError(void *,const char *,int); + LOCALE void PrintErrorID(void *,const char *,int,int); + LOCALE void PrintWarningID(void *,const char *,int,int); + LOCALE void CantFindItemErrorMessage(void *,const char *,const char *); + LOCALE void CantDeleteItemErrorMessage(void *,const char *,const char *); + LOCALE void AlreadyParsedErrorMessage(void *,const char *,const char *); + LOCALE void LocalVariableErrorMessage(void *,const char *); + LOCALE void DivideByZeroErrorMessage(void *,const char *); + LOCALE void SalienceInformationError(void *,const char *,const char *); LOCALE void SalienceRangeError(void *,int,int); LOCALE void SalienceNonIntegerError(void *); - LOCALE void CantFindItemInFunctionErrorMessage(void *,char *,char *,char *); - LOCALE void SlotExistError(void *,char *,char *); + LOCALE void CantFindItemInFunctionErrorMessage(void *,const char *,const char *,const char *); + LOCALE void SlotExistError(void *,const char *,const char *); -#endif +#endif /* _H_prntutil */ diff --git a/src/proflfun.c b/src/proflfun.c index d6dfb42..5c03458 100644 --- a/src/proflfun.c +++ b/src/proflfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/02/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* CONSTRUCT PROFILING FUNCTIONS MODULE */ /*******************************************************/ @@ -16,6 +16,7 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Modified OutputProfileInfo to allow a before */ /* and after prefix so that a string buffer does */ /* not need to be created to contain the entire */ @@ -29,6 +30,14 @@ /* Corrected code to remove run-time program */ /* compiler warnings. */ /* */ +/* 6.30: Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _PROFLFUN_SOURCE_ @@ -63,8 +72,8 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static intBool OutputProfileInfo(void *,char *,struct constructProfileInfo *, - char *,char *,char *,char **); + static intBool OutputProfileInfo(void *,const char *,struct constructProfileInfo *, + const char *,const char *,const char *,const char **); static void OutputUserFunctionsInfo(void *); static void OutputConstructsCodeInfo(void *); #if (! RUN_TIME) @@ -82,8 +91,8 @@ globle void ConstructProfilingFunctionDefinitions( AllocateEnvironmentData(theEnv,PROFLFUN_DATA,sizeof(struct profileFunctionData),NULL); - memcpy(&ProfileFunctionData(theEnv)->ProfileDataInfo,&profileDataInfo,sizeof(struct userDataRecord)); - + memcpy(&ProfileFunctionData(theEnv)->ProfileDataInfo,&profileDataInfo,sizeof(struct userDataRecord)); + ProfileFunctionData(theEnv)->LastProfileInfo = NO_PROFILE; ProfileFunctionData(theEnv)->PercentThreshold = 0.0; ProfileFunctionData(theEnv)->OutputString = OUTPUT_STRING; @@ -99,9 +108,9 @@ globle void ConstructProfilingFunctionDefinitions( EnvDefineFunction2(theEnv,"get-profile-percent-threshold",'d', PTIEF GetProfilePercentThresholdCommand, "GetProfilePercentThresholdCommand","00"); - + ProfileFunctionData(theEnv)->ProfileDataID = InstallUserDataRecord(theEnv,&ProfileFunctionData(theEnv)->ProfileDataInfo); - + EnvAddClearFunction(theEnv,"profile",ProfileClearFunction,0); #endif } @@ -114,7 +123,7 @@ globle void *CreateProfileData( void *theEnv) { struct constructProfileInfo *theInfo; - + theInfo = (struct constructProfileInfo *) genalloc(theEnv,sizeof(struct constructProfileInfo)); @@ -123,10 +132,10 @@ globle void *CreateProfileData( theInfo->startTime = 0.0; theInfo->totalSelfTime = 0.0; theInfo->totalWithChildrenTime = 0.0; - + return(theInfo); } - + /**************************************/ /* DeleteProfileData: */ /**************************************/ @@ -144,7 +153,7 @@ globle void DeleteProfileData( globle void ProfileCommand( void *theEnv) { - char *argument; + const char *argument; DATA_OBJECT theValue; if (EnvArgCountCheck(theEnv,"profile",EXACTLY,1) == -1) return; @@ -167,7 +176,7 @@ globle void ProfileCommand( /******************************/ globle intBool Profile( void *theEnv, - char *argument) + const char *argument) { /*======================================================*/ /* If the argument is the symbol "user-functions", then */ @@ -227,7 +236,7 @@ globle void ProfileInfoCommand( int argCount; DATA_OBJECT theValue; char buffer[512]; - + /*===================================*/ /* The profile-info command expects */ /* at most a single symbol argument. */ @@ -255,22 +264,22 @@ globle void ProfileInfoCommand( ProfileFunctionData(theEnv)->ProfileEndTime = gentime(); ProfileFunctionData(theEnv)->ProfileTotalTime += (ProfileFunctionData(theEnv)->ProfileEndTime - ProfileFunctionData(theEnv)->ProfileStartTime); } - + /*==================================*/ /* Print the profiling information. */ /*==================================*/ - + if (ProfileFunctionData(theEnv)->LastProfileInfo != NO_PROFILE) { - sprintf(buffer,"Profile elapsed time = %g seconds\n", + gensprintf(buffer,"Profile elapsed time = %g seconds\n", ProfileFunctionData(theEnv)->ProfileTotalTime); EnvPrintRouter(theEnv,WDISPLAY,buffer); if (ProfileFunctionData(theEnv)->LastProfileInfo == USER_FUNCTIONS) { EnvPrintRouter(theEnv,WDISPLAY,"Function Name "); } else if (ProfileFunctionData(theEnv)->LastProfileInfo == CONSTRUCTS_CODE) - { EnvPrintRouter(theEnv,WDISPLAY,"Construct Name "); } - + { EnvPrintRouter(theEnv,WDISPLAY,"Construct Name "); } + EnvPrintRouter(theEnv,WDISPLAY,"Entries Time % Time+Kids %+Kids\n"); if (ProfileFunctionData(theEnv)->LastProfileInfo == USER_FUNCTIONS) @@ -305,7 +314,7 @@ globle void StartProfile( } profileInfo = (struct constructProfileInfo *) FetchUserData(theEnv,ProfileFunctionData(theEnv)->ProfileDataID,theList); - + theFrame->profileOnExit = TRUE; theFrame->parentCall = FALSE; @@ -366,18 +375,18 @@ globle void EndProfile( /******************************************/ static intBool OutputProfileInfo( void *theEnv, - char *itemName, + const char *itemName, struct constructProfileInfo *profileInfo, - char *printPrefixBefore, - char *printPrefix, - char *printPrefixAfter, - char **banner) + const char *printPrefixBefore, + const char *printPrefix, + const char *printPrefixAfter, + const char **banner) { double percent = 0.0, percentWithKids = 0.0; char buffer[512]; - + if (profileInfo == NULL) return(FALSE); - + if (profileInfo->numberOfEntries == 0) return(FALSE); if (ProfileFunctionData(theEnv)->ProfileTotalTime != 0.0) @@ -398,7 +407,7 @@ static intBool OutputProfileInfo( if (printPrefixBefore != NULL) { EnvPrintRouter(theEnv,WDISPLAY,printPrefixBefore); } - + if (printPrefix != NULL) { EnvPrintRouter(theEnv,WDISPLAY,printPrefix); } @@ -412,7 +421,7 @@ static intBool OutputProfileInfo( itemName = ""; } - sprintf(buffer,ProfileFunctionData(theEnv)->OutputString, + gensprintf(buffer,ProfileFunctionData(theEnv)->OutputString, itemName, (long) profileInfo->numberOfEntries, @@ -451,7 +460,7 @@ globle void ProfileResetCommand( HANDLER *theHandler; unsigned handlerIndex; #endif - + ProfileFunctionData(theEnv)->ProfileStartTime = 0.0; ProfileFunctionData(theEnv)->ProfileEndTime = 0.0; ProfileFunctionData(theEnv)->ProfileTotalTime = 0.0; @@ -460,7 +469,7 @@ globle void ProfileResetCommand( for (theFunction = GetFunctionList(theEnv); theFunction != NULL; theFunction = theFunction->next) - { + { ResetProfileInfo((struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theFunction->usrData)); } @@ -468,7 +477,7 @@ globle void ProfileResetCommand( for (i = 0; i < MAXIMUM_PRIMITIVES; i++) { if (EvaluationData(theEnv)->PrimitivesArray[i] != NULL) - { + { ResetProfileInfo((struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,EvaluationData(theEnv)->PrimitivesArray[i]->usrData)); } @@ -478,9 +487,9 @@ globle void ProfileResetCommand( for (theDeffunction = (DEFFUNCTION *) EnvGetNextDeffunction(theEnv,NULL); theDeffunction != NULL; theDeffunction = (DEFFUNCTION *) EnvGetNextDeffunction(theEnv,theDeffunction)) - { + { ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDeffunction->header.usrData)); + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDeffunction->header.usrData)); } #endif @@ -488,9 +497,9 @@ globle void ProfileResetCommand( for (theDefrule = (struct defrule *) EnvGetNextDefrule(theEnv,NULL); theDefrule != NULL; theDefrule = (struct defrule *) EnvGetNextDefrule(theEnv,theDefrule)) - { + { ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefrule->header.usrData)); + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefrule->header.usrData)); } #endif @@ -500,15 +509,15 @@ globle void ProfileResetCommand( theDefgeneric = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,theDefgeneric)) { ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefgeneric->header.usrData)); - + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefgeneric->header.usrData)); + for (methodIndex = EnvGetNextDefmethod(theEnv,theDefgeneric,0); methodIndex != 0; methodIndex = EnvGetNextDefmethod(theEnv,theDefgeneric,methodIndex)) { theMethod = GetDefmethodPointer(theDefgeneric,methodIndex); ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theMethod->usrData)); + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theMethod->usrData)); } } #endif @@ -519,14 +528,14 @@ globle void ProfileResetCommand( theDefclass = (DEFCLASS *) EnvGetNextDefclass(theEnv,theDefclass)) { ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefclass->header.usrData)); + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefclass->header.usrData)); for (handlerIndex = EnvGetNextDefmessageHandler(theEnv,theDefclass,0); handlerIndex != 0; handlerIndex = EnvGetNextDefmessageHandler(theEnv,theDefclass,handlerIndex)) { theHandler = GetDefmessageHandlerPointer(theDefclass,handlerIndex); ResetProfileInfo((struct constructProfileInfo *) - TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theHandler->usrData)); + TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theHandler->usrData)); } } #endif @@ -541,7 +550,7 @@ globle void ResetProfileInfo( struct constructProfileInfo *profileInfo) { if (profileInfo == NULL) return; - + profileInfo->numberOfEntries = 0; profileInfo->childCall = FALSE; profileInfo->startTime = 0.0; @@ -563,7 +572,7 @@ static void OutputUserFunctionsInfo( theFunction = theFunction->next) { OutputProfileInfo(theEnv,ValueToString(theFunction->callFunctionName), - (struct constructProfileInfo *) + (struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID, theFunction->usrData), NULL,NULL,NULL,NULL); @@ -585,9 +594,6 @@ static void OutputUserFunctionsInfo( /*************************************************/ /* OutputConstructsCodeInfo: */ /*************************************************/ -#if IBM_TBC && (! DEFFUNCTION_CONSTRUCT) && (! DEFGENERIC_CONSTRUCT) && (! OBJECT_SYSTEM) && (! DEFRULE_CONSTRUCT) -#pragma argsused -#endif static void OutputConstructsCodeInfo( void *theEnv) { @@ -612,9 +618,9 @@ static void OutputConstructsCodeInfo( unsigned handlerIndex; #endif #if DEFGENERIC_CONSTRUCT || OBJECT_SYSTEM - char *prefix, *prefixBefore, *prefixAfter; + const char *prefix, *prefixBefore, *prefixAfter; #endif - char *banner; + const char *banner; banner = "\n*** Deffunctions ***\n\n"; @@ -624,7 +630,7 @@ static void OutputConstructsCodeInfo( theDeffunction = (DEFFUNCTION *) EnvGetNextDeffunction(theEnv,theDeffunction)) { OutputProfileInfo(theEnv,EnvGetDeffunctionName(theEnv,theDeffunction), - (struct constructProfileInfo *) + (struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDeffunction->header.usrData), NULL,NULL,NULL,&banner); } @@ -648,12 +654,12 @@ static void OutputConstructsCodeInfo( EnvGetDefmethodDescription(theEnv,methodBuffer,510,theDefgeneric,methodIndex); if (OutputProfileInfo(theEnv,methodBuffer, - (struct constructProfileInfo *) + (struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theMethod->usrData), prefixBefore,prefix,prefixAfter,&banner)) { - prefixBefore = NULL; - prefix = NULL; + prefixBefore = NULL; + prefix = NULL; prefixAfter = NULL; } } @@ -669,20 +675,20 @@ static void OutputConstructsCodeInfo( prefixAfter = "\n"; prefix = EnvGetDefclassName(theEnv,theDefclass); prefixBefore = "\n"; - + for (handlerIndex = EnvGetNextDefmessageHandler(theEnv,theDefclass,0); handlerIndex != 0; handlerIndex = EnvGetNextDefmessageHandler(theEnv,theDefclass,handlerIndex)) { theHandler = GetDefmessageHandlerPointer(theDefclass,handlerIndex); if (OutputProfileInfo(theEnv,EnvGetDefmessageHandlerName(theEnv,theDefclass,handlerIndex), - (struct constructProfileInfo *) + (struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID, theHandler->usrData), prefixBefore,prefix,prefixAfter,&banner)) { - prefixBefore = NULL; - prefix = NULL; + prefixBefore = NULL; + prefix = NULL; prefixAfter = NULL; } } @@ -698,7 +704,7 @@ static void OutputConstructsCodeInfo( theDefrule = (struct defrule *) EnvGetNextDefrule(theEnv,theDefrule)) { OutputProfileInfo(theEnv,EnvGetDefruleName(theEnv,theDefrule), - (struct constructProfileInfo *) + (struct constructProfileInfo *) TestUserData(ProfileFunctionData(theEnv)->ProfileDataID,theDefrule->header.usrData), NULL,NULL,NULL,&banner); } @@ -715,7 +721,7 @@ globle double SetProfilePercentThresholdCommand( { DATA_OBJECT theValue; double newThreshold; - + if (EnvArgCountCheck(theEnv,"set-profile-percent-threshold",EXACTLY,1) == -1) { return(ProfileFunctionData(theEnv)->PercentThreshold); } @@ -726,12 +732,12 @@ globle double SetProfilePercentThresholdCommand( { newThreshold = (double) DOToLong(theValue); } else { newThreshold = (double) DOToDouble(theValue); } - + if ((newThreshold < 0.0) || (newThreshold > 100.0)) - { + { ExpectedTypeError1(theEnv,"set-profile-percent-threshold",1, "number in the range 0 to 100"); - return(-1.0); + return(-1.0); } return(SetProfilePercentThreshold(theEnv,newThreshold)); @@ -749,7 +755,7 @@ globle double SetProfilePercentThreshold( if ((value < 0.0) || (value > 100.0)) { return(-1.0); } - + oldPercentThreshhold = ProfileFunctionData(theEnv)->PercentThreshold; ProfileFunctionData(theEnv)->PercentThreshold = value; @@ -763,7 +769,7 @@ globle double SetProfilePercentThreshold( /*********************************************************/ globle double GetProfilePercentThresholdCommand( void *theEnv) - { + { EnvArgCountCheck(theEnv,"get-profile-percent-threshold",EXACTLY,0); return(ProfileFunctionData(theEnv)->PercentThreshold); @@ -778,19 +784,19 @@ globle double GetProfilePercentThreshold( { return(ProfileFunctionData(theEnv)->PercentThreshold); } - + /**********************************************************/ /* SetProfileOutputString: Sets the output string global. */ /**********************************************************/ -globle char *SetProfileOutputString( +globle const char *SetProfileOutputString( void *theEnv, - char *value) + const char *value) { - char *oldOutputString; + const char *oldOutputString; if (value == NULL) { return(ProfileFunctionData(theEnv)->OutputString); } - + oldOutputString = ProfileFunctionData(theEnv)->OutputString; ProfileFunctionData(theEnv)->OutputString = value; @@ -798,7 +804,7 @@ globle char *SetProfileOutputString( return(oldOutputString); } -#if (! RUN_TIME) +#if (! RUN_TIME) /******************************************************************/ /* ProfileClearFunction: Profiling clear routine for use with the */ /* clear command. Removes user data attached to user functions. */ @@ -813,7 +819,7 @@ static void ProfileClearFunction( theFunction != NULL; theFunction = theFunction->next) { - theFunction->usrData = + theFunction->usrData = DeleteUserData(theEnv,ProfileFunctionData(theEnv)->ProfileDataID,theFunction->usrData); } @@ -821,7 +827,7 @@ static void ProfileClearFunction( { if (EvaluationData(theEnv)->PrimitivesArray[i] != NULL) { - EvaluationData(theEnv)->PrimitivesArray[i]->usrData = + EvaluationData(theEnv)->PrimitivesArray[i]->usrData = DeleteUserData(theEnv,ProfileFunctionData(theEnv)->ProfileDataID,EvaluationData(theEnv)->PrimitivesArray[i]->usrData); } } diff --git a/src/proflfun.h b/src/proflfun.h index e7703d0..4391409 100644 --- a/src/proflfun.h +++ b/src/proflfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* CONSTRUCT PROFILING FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -16,8 +16,27 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Modified OutputProfileInfo to allow a before */ +/* and after prefix so that a string buffer does */ +/* not need to be created to contain the entire */ +/* prefix. This allows a buffer overflow problem */ +/* to be corrected. DR0857. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Added pragmas to remove compilation warnings. */ +/* */ +/* Corrected code to remove run-time program */ +/* compiler warnings. */ +/* */ +/* 6.30: Used gensprintf instead of sprintf. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_proflfun @@ -53,11 +72,11 @@ struct profileFrameInfo double parentStartTime; struct constructProfileInfo *oldProfileFrame; }; - + #define PROFLFUN_DATA 15 struct profileFunctionData - { + { double ProfileStartTime; double ProfileEndTime; double ProfileTotalTime; @@ -68,7 +87,7 @@ struct profileFunctionData int ProfileUserFunctions; int ProfileConstructs; struct constructProfileInfo *ActiveProfileFrame; - char *OutputString; + const char *OutputString; }; #define ProfileFunctionData(theEnv) ((struct profileFunctionData *) GetEnvironmentData(theEnv,PROFLFUN_DATA)) @@ -88,11 +107,11 @@ struct profileFunctionData LOCALE double SetProfilePercentThreshold(void *,double); LOCALE double GetProfilePercentThresholdCommand(void *); LOCALE double GetProfilePercentThreshold(void *); - LOCALE intBool Profile(void *,char *); + LOCALE intBool Profile(void *,const char *); LOCALE void DeleteProfileData(void *,void *); LOCALE void *CreateProfileData(void *); - LOCALE char *SetProfileOutputString(void *,char *); + LOCALE const char *SetProfileOutputString(void *,const char *); -#endif +#endif /* _H_proflfun */ diff --git a/src/reorder.c b/src/reorder.c index 92bf3c1..461dc0a 100644 --- a/src/reorder.c +++ b/src/reorder.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 06/14/14 */ /* */ /* REORDER MODULE */ /*******************************************************/ @@ -25,6 +25,16 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Support for join network changes. */ +/* */ +/* Changes to the algorithm for processing */ +/* not/and CE groups. */ +/* */ +/* Additional optimizations for combining */ +/* conditional elements. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ /*************************************************************/ #define _REORDER_SOURCE_ @@ -45,29 +55,54 @@ #include "router.h" #include "rulelhs.h" +#if DEVELOPER && DEBUGGING_FUNCTIONS +#include "watch.h" +#include "rulepsr.h" +#endif + #include "reorder.h" +struct variableReference + { + struct symbolHashNode *name; + int depth; + struct variableReference *next; + }; + +struct groupReference + { + struct lhsParseNode *theGroup; + int depth; + struct groupReference *next; + }; + /***************************************/ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ static struct lhsParseNode *ReverseAndOr(void *,struct lhsParseNode *,struct lhsParseNode *,int); - static struct lhsParseNode *PerformReorder1(void *,struct lhsParseNode *,int *); - static struct lhsParseNode *PerformReorder2(void *,struct lhsParseNode *,int *); - static struct lhsParseNode *CompressCEs(void *,struct lhsParseNode *,int *); + static struct lhsParseNode *PerformReorder1(void *,struct lhsParseNode *,int *,int); + static struct lhsParseNode *PerformReorder2(void *,struct lhsParseNode *,int *,int); + static struct lhsParseNode *CompressCEs(void *,struct lhsParseNode *,int *,int); static void IncrementNandDepth(void *,struct lhsParseNode *,int); - static struct lhsParseNode *CreateInitialPattern(void *,struct patternParser *); - static struct lhsParseNode *ReorderDriver(void *,struct lhsParseNode *,int *,int); - static void AddRemainingInitialPatterns(void *,struct lhsParseNode *,struct patternParser *); -// static void PrintNodes(void *,char *,struct lhsParseNode *); - static struct lhsParseNode *AssignPatternIndices(struct lhsParseNode *,short); + static struct lhsParseNode *CreateInitialPattern(void *); + static struct lhsParseNode *ReorderDriver(void *,struct lhsParseNode *,int *,int,int); + static struct lhsParseNode *AddRemainingInitialPatterns(void *,struct lhsParseNode *); + static struct lhsParseNode *AssignPatternIndices(struct lhsParseNode *,short,int,short); static void PropagateIndexSlotPatternValues(struct lhsParseNode *, short,short, struct symbolHashNode *, short); - + static void PropagateJoinDepth(struct lhsParseNode *,short); + static void PropagateNandDepth(struct lhsParseNode *,int,int); + static void MarkExistsNands(struct lhsParseNode *); + static int PropagateWhichCE(struct lhsParseNode *,int); + /* + static void PrintNodes(void *,const char *,struct lhsParseNode *); + */ + /********************************************/ -/* ReorderPatterns: Reorders a group of CEs */ +/* ReorderPatterns: Reorders a group of CEs */ /* to accommodate KB Rete topology. */ /********************************************/ globle struct lhsParseNode *ReorderPatterns( @@ -75,33 +110,36 @@ globle struct lhsParseNode *ReorderPatterns( struct lhsParseNode *theLHS, int *anyChange) { - struct lhsParseNode *newLHS, *patternPtr, *tempLHS, *lastLHS; - unsigned int whichCE; + struct lhsParseNode *newLHS, *tempLHS, *lastLHS; + /*=============================================*/ + /* If the LHS of the rule was left unspecified */ + /* (e.g., (defrule x => ...)), then nothing */ + /* more needs to be done. */ + /*=============================================*/ + + if (theLHS == NULL) return(theLHS); + /*===========================================================*/ /* The LHS of a rule is enclosed within an implied "and" CE. */ /*===========================================================*/ newLHS = GetLHSParseNode(theEnv); newLHS->type = AND_CE; - - /*=============================================*/ - /* If the LHS of the rule was left unspecified */ - /* (e.g., (defrule x => ...)), then add an */ - /* initial fact or instance pattern to the LHS */ - /* of the rule. Otherwise, attach the user */ - /* specified LHS to the implied "and" Ce. */ - /*=============================================*/ - - if (theLHS == NULL) newLHS->right = CreateInitialPattern(theEnv,NULL); - else newLHS->right = theLHS; - + newLHS->right = theLHS; + + /*==============================================================*/ + /* Mark the nodes to indicate which CE they're associated with. */ + /*==============================================================*/ + + PropagateWhichCE(newLHS,0); + /*=======================================================*/ /* Reorder the patterns to support the KB Rete topology. */ /*=======================================================*/ - newLHS = ReorderDriver(theEnv,newLHS,anyChange,1); - newLHS = ReorderDriver(theEnv,newLHS,anyChange,2); + newLHS = ReorderDriver(theEnv,newLHS,anyChange,1,1); + newLHS = ReorderDriver(theEnv,newLHS,anyChange,2,1); /*===========================================*/ /* The top level and CE may have disappeared */ @@ -137,6 +175,20 @@ globle struct lhsParseNode *ReorderPatterns( newLHS->right = theLHS; } + /*================================================*/ + /* Mark exist not/and groups within the patterns. */ + /*================================================*/ + + if (newLHS->type == OR_CE) + { + for (theLHS = newLHS->right; + theLHS != NULL; + theLHS = theLHS->bottom) + { MarkExistsNands(theLHS->right); } + } + else + { MarkExistsNands(newLHS->right); } + /*=====================================================*/ /* Add initial patterns where needed (such as before a */ /* "test" CE or "not" CE which is the first CE within */ @@ -159,15 +211,7 @@ globle struct lhsParseNode *ReorderPatterns( for (; theLHS != NULL; theLHS = theLHS->bottom) - { - whichCE = 1; - for (patternPtr = theLHS->right; - patternPtr != NULL; - patternPtr = patternPtr->bottom) - { if (patternPtr->userCE) patternPtr->whichCE = whichCE++; } - - AssignPatternIndices(theLHS->right,1); - } + { AssignPatternIndices(theLHS->right,1,1,0); } /*===========================*/ /* Return the processed LHS. */ @@ -184,7 +228,8 @@ static struct lhsParseNode *ReorderDriver( void *theEnv, struct lhsParseNode *theLHS, int *anyChange, - int pass) + int pass, + int depth) { struct lhsParseNode *argPtr; struct lhsParseNode *before, *save; @@ -213,8 +258,8 @@ static struct lhsParseNode *ReorderDriver( (theLHS->type == NOT_CE) || (theLHS->type == OR_CE)) { - if (pass == 1) theLHS = PerformReorder1(theEnv,theLHS,&newChange); - else theLHS = PerformReorder2(theEnv,theLHS,&newChange); + if (pass == 1) theLHS = PerformReorder1(theEnv,theLHS,&newChange,depth); + else theLHS = PerformReorder2(theEnv,theLHS,&newChange,depth); if (newChange) { @@ -222,7 +267,7 @@ static struct lhsParseNode *ReorderDriver( change = TRUE; } - theLHS = CompressCEs(theEnv,theLHS,&newChange); + theLHS = CompressCEs(theEnv,theLHS,&newChange,depth); if (newChange) { @@ -257,14 +302,14 @@ static struct lhsParseNode *ReorderDriver( if (before == NULL) { argPtr->bottom = NULL; - theLHS->right = ReorderDriver(theEnv,argPtr,&newChange,pass); + theLHS->right = ReorderDriver(theEnv,argPtr,&newChange,pass,depth+1); theLHS->right->bottom = save; before = theLHS->right; } else { argPtr->bottom = NULL; - before->bottom = ReorderDriver(theEnv,argPtr,&newChange,pass); + before->bottom = ReorderDriver(theEnv,argPtr,&newChange,pass,depth+1); before->bottom->bottom = save; before = before->bottom; } @@ -293,6 +338,38 @@ static struct lhsParseNode *ReorderDriver( return(theLHS); } +/********************/ +/* MarkExistsNands: */ +/********************/ +static void MarkExistsNands( + struct lhsParseNode *theLHS) + { + int currentDepth = 1; + struct lhsParseNode *tmpLHS; + + while (theLHS != NULL) + { + if (IsExistsSubjoin(theLHS,currentDepth)) + { + theLHS->existsNand = TRUE; + + for (tmpLHS = theLHS; + tmpLHS != NULL; + tmpLHS = tmpLHS->bottom) + { + tmpLHS->beginNandDepth--; + if (tmpLHS->endNandDepth <= currentDepth) + { break; } + else + { tmpLHS->endNandDepth--; } + } + } + + currentDepth = theLHS->endNandDepth; + theLHS = theLHS->bottom; + } + } + /****************************************************************/ /* AddInitialPatterns: Add initial patterns to CEs where needed */ /* (such as before a "test" CE or "not" CE which is the first */ @@ -303,7 +380,6 @@ globle void AddInitialPatterns( struct lhsParseNode *theLHS) { struct lhsParseNode *thePattern; - struct patternParser *lastType; /*====================================================*/ /* If there are multiple disjuncts for the rule, then */ @@ -320,47 +396,11 @@ globle void AddInitialPatterns( return; } - /*======================================================*/ - /* Determine what the default pattern type for the rule */ - /* should be (in case the rule begins with a test CE). */ - /* The default pattern type is the type of the data */ - /* entity associated with the first pattern CE found in */ - /* the LHS of the rule. */ - /*======================================================*/ - - for (lastType = NULL, thePattern = theLHS->right; - thePattern != NULL; - thePattern = thePattern->bottom) - { - if (thePattern->type == PATTERN_CE) - { - lastType = thePattern->patternType; - break; - } - } - - /*===================================================*/ - /* Add an initial pattern to the first CE of a rule */ - /* if the CE is a "test" CE, "not" CE or a join from */ - /* the right. */ - /*===================================================*/ - - if ((theLHS->right->negated) || - (theLHS->right->type == TEST_CE) || - (theLHS->right->beginNandDepth > 1)) - { - thePattern = CreateInitialPattern(theEnv,lastType); - - thePattern->logical = (theLHS->logical || theLHS->right->logical); - thePattern->bottom = theLHS->right; - theLHS->right = thePattern; - } - /*================================*/ /* Handle the remaining patterns. */ /*================================*/ - AddRemainingInitialPatterns(theEnv,theLHS->right,lastType); + theLHS->right = AddRemainingInitialPatterns(theEnv,theLHS->right); } /***********************************************************/ @@ -371,7 +411,8 @@ globle void AddInitialPatterns( static struct lhsParseNode *PerformReorder1( void *theEnv, struct lhsParseNode *theLHS, - int *newChange) + int *newChange, + int depth) { struct lhsParseNode *argPtr, *lastArg, *nextArg; struct lhsParseNode *tempArg, *newNode; @@ -433,9 +474,12 @@ static struct lhsParseNode *PerformReorder1( tempArg->type = NOT_CE; tempArg->negated = FALSE; + tempArg->exists = FALSE; + tempArg->existsNand = FALSE; tempArg->logical = FALSE; tempArg->value = NULL; tempArg->expression = NULL; + tempArg->secondaryExpression = NULL; tempArg->right = newNode; tempArg = tempArg->bottom; @@ -500,7 +544,8 @@ static struct lhsParseNode *PerformReorder1( static struct lhsParseNode *PerformReorder2( void *theEnv, struct lhsParseNode *theLHS, - int *newChange) + int *newChange, + int depth) { struct lhsParseNode *argPtr; int change; @@ -519,12 +564,71 @@ static struct lhsParseNode *PerformReorder2( for (argPtr = theLHS->right; argPtr != NULL;) { + /*=======================================================*/ + /* A sequence of three not CEs grouped within each other */ + /* can be replaced with a single not CE. For example, */ + /* (not (not (not (a)))) can be replaced with (not (a)). */ + /*=======================================================*/ + + if ((theLHS->type == NOT_CE) && + (argPtr->type == NOT_CE) && + (argPtr->right != NULL) && + (argPtr->right->type == NOT_CE)) + { + change = TRUE; + *newChange = TRUE; + + theLHS->right = argPtr->right->right; + + argPtr->right->right = NULL; + ReturnLHSParseNodes(theEnv,argPtr); + + break; + } + + /*==========================================*/ + /* Replace two not CEs containing a pattern */ + /* CE with an exists pattern CE. */ + /*==========================================*/ + + else if ((theLHS->type == NOT_CE) && + (argPtr->type == NOT_CE) && + (argPtr->right != NULL) && + (argPtr->right->type == PATTERN_CE)) + { + change = TRUE; + *newChange = TRUE; + + CopyLHSParseNode(theEnv,theLHS,argPtr->right,FALSE); + + theLHS->negated = TRUE; + theLHS->exists = TRUE; + theLHS->existsNand = FALSE; + theLHS->right = argPtr->right->right; + + argPtr->right->networkTest = NULL; + argPtr->right->externalNetworkTest = NULL; + argPtr->right->secondaryNetworkTest = NULL; + argPtr->right->externalRightHash = NULL; + argPtr->right->externalLeftHash = NULL; + argPtr->right->leftHash = NULL; + argPtr->right->rightHash = NULL; + argPtr->right->betaHash = NULL; + argPtr->right->expression = NULL; + argPtr->right->secondaryExpression = NULL; + argPtr->right->userData = NULL; + argPtr->right->right = NULL; + argPtr->right->bottom = NULL; + ReturnLHSParseNodes(theEnv,argPtr); + break; + } + /*======================================*/ /* Replace not CEs containing a pattern */ /* CE with a negated pattern CE. */ /*======================================*/ - if ((theLHS->type == NOT_CE) && (argPtr->type == PATTERN_CE)) + else if ((theLHS->type == NOT_CE) && (argPtr->type == PATTERN_CE)) { change = TRUE; *newChange = TRUE; @@ -532,10 +636,22 @@ static struct lhsParseNode *PerformReorder2( CopyLHSParseNode(theEnv,theLHS,argPtr,FALSE); theLHS->negated = TRUE; + theLHS->exists = FALSE; + theLHS->existsNand = FALSE; theLHS->right = argPtr->right; - argPtr->networkTest = NULL; + argPtr->networkTest = NULL; + argPtr->externalNetworkTest = NULL; + argPtr->secondaryNetworkTest = NULL; + argPtr->externalRightHash = NULL; + argPtr->externalLeftHash = NULL; + argPtr->constantSelector = NULL; + argPtr->constantValue = NULL; + argPtr->leftHash = NULL; + argPtr->rightHash = NULL; + argPtr->betaHash = NULL; argPtr->expression = NULL; + argPtr->secondaryExpression = NULL; argPtr->userData = NULL; argPtr->right = NULL; argPtr->bottom = NULL; @@ -558,6 +674,8 @@ static struct lhsParseNode *PerformReorder2( theLHS->type = argPtr->type; theLHS->negated = argPtr->negated; + theLHS->exists = argPtr->exists; + theLHS->existsNand = argPtr->existsNand; theLHS->value = argPtr->value; theLHS->logical = argPtr->logical; theLHS->right = argPtr->right; @@ -702,13 +820,14 @@ static struct lhsParseNode *ReverseAndOr( return(copyOfCEs); } -/***********************************************************/ -/* CompressCEs: */ -/***********************************************************/ +/****************/ +/* CompressCEs: */ +/****************/ static struct lhsParseNode *CompressCEs( void *theEnv, struct lhsParseNode *theLHS, - int *newChange) + int *newChange, + int depth) { struct lhsParseNode *argPtr, *lastArg, *nextArg; struct lhsParseNode *tempArg; @@ -768,19 +887,15 @@ static struct lhsParseNode *CompressCEs( change = TRUE; *newChange = TRUE; - e1 = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_NOT); - e2 = LHSParseNodesToExpression(theEnv,argPtr->expression); - e1->arg_list = e2; + tempArg = GetLHSParseNode(theEnv); + tempArg->type = FCALL; + tempArg->value = ExpressionData(theEnv)->PTR_NOT; + tempArg->bottom = argPtr->expression; + argPtr->expression = tempArg; CopyLHSParseNode(theEnv,theLHS,argPtr,TRUE); - ReturnLHSParseNodes(theEnv,argPtr); - ReturnLHSParseNodes(theEnv,theLHS->expression); - - theLHS->expression = ExpressionToLHSParseNodes(theEnv,e1); theLHS->right = NULL; - ReturnExpression(theEnv,e1); - break; } @@ -798,14 +913,83 @@ static struct lhsParseNode *CompressCEs( change = TRUE; *newChange = TRUE; - e1 = LHSParseNodesToExpression(theEnv,argPtr->expression); - e2 = LHSParseNodesToExpression(theEnv,argPtr->bottom->expression); - e1 = CombineExpressions(theEnv,e1,e2); + argPtr->expression = CombineLHSParseNodes(theEnv,argPtr->expression,argPtr->bottom->expression); + argPtr->bottom->expression = NULL; + + tempArg = argPtr->bottom; + argPtr->bottom = tempArg->bottom; + tempArg->bottom = NULL; + + ReturnLHSParseNodes(theEnv,tempArg); + } - ReturnLHSParseNodes(theEnv,argPtr->expression); - argPtr->expression = ExpressionToLHSParseNodes(theEnv,e1); - ReturnExpression(theEnv,e1); + /*========================================================*/ + /* A test CE can be attached to the preceding pattern CE. */ + /*========================================================*/ + else if ((theLHS->type == AND_CE) && (argPtr->type == PATTERN_CE) && + ((argPtr->bottom != NULL) ? argPtr->bottom->type == TEST_CE : + FALSE) && + (argPtr->negated == FALSE) && + (argPtr->exists == FALSE) && + (argPtr->beginNandDepth == argPtr->endNandDepth) && + (argPtr->endNandDepth == argPtr->bottom->beginNandDepth)) + { + int endNandDepth; + change = TRUE; + *newChange = TRUE; + + endNandDepth = argPtr->bottom->endNandDepth; + + if (argPtr->negated || argPtr->exists) + { + e1 = LHSParseNodesToExpression(theEnv,argPtr->secondaryExpression); + e2 = LHSParseNodesToExpression(theEnv,argPtr->bottom->expression); + e1 = CombineExpressions(theEnv,e1,e2); + ReturnLHSParseNodes(theEnv,argPtr->secondaryExpression); + argPtr->secondaryExpression = ExpressionToLHSParseNodes(theEnv,e1); + ReturnExpression(theEnv,e1); + } + else + { + argPtr->expression = CombineLHSParseNodes(theEnv,argPtr->expression,argPtr->bottom->expression); + argPtr->bottom->expression = NULL; + } + + if ((theLHS->right == argPtr) && ((argPtr->beginNandDepth - 1) == endNandDepth)) + { + if (argPtr->negated) + { + argPtr->negated = FALSE; + argPtr->exists = TRUE; + e1 = LHSParseNodesToExpression(theEnv,argPtr->secondaryExpression); + e1 = NegateExpression(theEnv,e1); + ReturnLHSParseNodes(theEnv,argPtr->secondaryExpression); + argPtr->secondaryExpression = ExpressionToLHSParseNodes(theEnv,e1); + ReturnExpression(theEnv,e1); + } + else if (argPtr->exists) + { + argPtr->negated = TRUE; + argPtr->exists = FALSE; + e1 = LHSParseNodesToExpression(theEnv,argPtr->secondaryExpression); + e1 = NegateExpression(theEnv,e1); + ReturnLHSParseNodes(theEnv,argPtr->secondaryExpression); + argPtr->secondaryExpression = ExpressionToLHSParseNodes(theEnv,e1); + ReturnExpression(theEnv,e1); + } + else + { + argPtr->negated = TRUE; + } + PropagateNandDepth(argPtr,endNandDepth,endNandDepth); + } + + /*========================================*/ + /* Detach the test CE from its parent and */ + /* dispose of the data structures. */ + /*========================================*/ + tempArg = argPtr->bottom; argPtr->bottom = tempArg->bottom; tempArg->bottom = NULL; @@ -830,6 +1014,40 @@ static struct lhsParseNode *CompressCEs( break; } + /*=======================================================*/ + /* Replace and CEs containing a single pattern CE with */ + /* just a pattern CE if this is not the top most and CE. */ + /*=======================================================*/ + + else if ((theLHS->type == AND_CE) && (argPtr->type == PATTERN_CE) && + (theLHS->right == argPtr) && (argPtr->bottom == NULL) && (depth > 1)) + { + change = TRUE; + *newChange = TRUE; + + CopyLHSParseNode(theEnv,theLHS,argPtr,FALSE); + + theLHS->right = argPtr->right; + + argPtr->networkTest = NULL; + argPtr->externalNetworkTest = NULL; + argPtr->secondaryNetworkTest = NULL; + argPtr->externalRightHash = NULL; + argPtr->externalLeftHash = NULL; + argPtr->constantSelector = NULL; + argPtr->constantValue = NULL; + argPtr->leftHash = NULL; + argPtr->rightHash = NULL; + argPtr->betaHash = NULL; + argPtr->expression = NULL; + argPtr->secondaryExpression = NULL; + argPtr->userData = NULL; + argPtr->right = NULL; + argPtr->bottom = NULL; + ReturnLHSParseNodes(theEnv,argPtr); + break; + } + /*===================================================*/ /* If no changes are needed, move on to the next CE. */ /*===================================================*/ @@ -882,6 +1100,8 @@ globle void CopyLHSParseNode( dest->type = src->type; dest->value = src->value; dest->negated = src->negated; + dest->exists = src->exists; + dest->existsNand = src->existsNand; dest->bindingVariable = src->bindingVariable; dest->withinMultifieldSlot = src->withinMultifieldSlot; dest->multifieldSlot = src->multifieldSlot; @@ -891,6 +1111,8 @@ globle void CopyLHSParseNode( dest->singleFieldsAfter = src->singleFieldsAfter; dest->logical = src->logical; dest->userCE = src->userCE; + dest->marked = src->marked; + dest->whichCE = src->whichCE; dest->referringNode = src->referringNode; dest->patternType = src->patternType; dest->pattern = src->pattern; @@ -899,6 +1121,7 @@ globle void CopyLHSParseNode( dest->slotNumber = src->slotNumber; dest->beginNandDepth = src->beginNandDepth; dest->endNandDepth = src->endNandDepth; + dest->joinDepth = src->joinDepth; /*==========================================================*/ /* The duplicate flag controls whether pointers to existing */ @@ -909,6 +1132,15 @@ globle void CopyLHSParseNode( if (duplicate) { dest->networkTest = CopyExpression(theEnv,src->networkTest); + dest->externalNetworkTest = CopyExpression(theEnv,src->externalNetworkTest); + dest->secondaryNetworkTest = CopyExpression(theEnv,src->secondaryNetworkTest); + dest->externalRightHash = CopyExpression(theEnv,src->externalRightHash); + dest->externalLeftHash = CopyExpression(theEnv,src->externalLeftHash); + dest->constantSelector = CopyExpression(theEnv,src->constantSelector); + dest->constantValue = CopyExpression(theEnv,src->constantValue); + dest->leftHash = CopyExpression(theEnv,src->leftHash); + dest->betaHash = CopyExpression(theEnv,src->betaHash); + dest->rightHash = CopyExpression(theEnv,src->rightHash); if (src->userData == NULL) { dest->userData = NULL; } else if (src->patternType->copyUserDataFunction == NULL) @@ -916,6 +1148,7 @@ globle void CopyLHSParseNode( else { dest->userData = (*src->patternType->copyUserDataFunction)(theEnv,src->userData); } dest->expression = CopyLHSParseNodes(theEnv,src->expression); + dest->secondaryExpression = CopyLHSParseNodes(theEnv,src->secondaryExpression); dest->constraints = CopyConstraintRecord(theEnv,src->constraints); if (dest->constraints != NULL) dest->derivedConstraints = TRUE; else dest->derivedConstraints = FALSE; @@ -923,8 +1156,18 @@ globle void CopyLHSParseNode( else { dest->networkTest = src->networkTest; + dest->externalNetworkTest = src->externalNetworkTest; + dest->secondaryNetworkTest = src->secondaryNetworkTest; + dest->externalRightHash = src->externalRightHash; + dest->externalLeftHash = src->externalLeftHash; + dest->constantSelector = src->constantSelector; + dest->constantValue = src->constantValue; + dest->leftHash = src->leftHash; + dest->betaHash = src->betaHash; + dest->rightHash = src->rightHash; dest->userData = src->userData; dest->expression = src->expression; + dest->secondaryExpression = src->secondaryExpression; dest->derivedConstraints = FALSE; dest->constraints = src->constraints; } @@ -943,6 +1186,8 @@ globle struct lhsParseNode *GetLHSParseNode( newNode->type = UNKNOWN_VALUE; newNode->value = NULL; newNode->negated = FALSE; + newNode->exists = FALSE; + newNode->existsNand = FALSE; newNode->bindingVariable = FALSE; newNode->withinMultifieldSlot = FALSE; newNode->multifieldSlot = FALSE; @@ -953,6 +1198,8 @@ globle struct lhsParseNode *GetLHSParseNode( newNode->logical = FALSE; newNode->derivedConstraints = FALSE; newNode->userCE = TRUE; + newNode->marked = FALSE; + newNode->whichCE = 0; newNode->constraints = NULL; newNode->referringNode = NULL; newNode->patternType = NULL; @@ -962,9 +1209,20 @@ globle struct lhsParseNode *GetLHSParseNode( newNode->slotNumber = -1; newNode->beginNandDepth = 1; newNode->endNandDepth = 1; + newNode->joinDepth = 0; newNode->userData = NULL; newNode->networkTest = NULL; + newNode->externalNetworkTest = NULL; + newNode->secondaryNetworkTest = NULL; + newNode->externalRightHash = NULL; + newNode->externalLeftHash = NULL; + newNode->constantSelector = NULL; + newNode->constantValue = NULL; + newNode->leftHash = NULL; + newNode->betaHash = NULL; + newNode->rightHash = NULL; newNode->expression = NULL; + newNode->secondaryExpression = NULL; newNode->right = NULL; newNode->bottom = NULL; @@ -982,9 +1240,19 @@ globle void ReturnLHSParseNodes( if (waste != NULL) { ReturnExpression(theEnv,waste->networkTest); + ReturnExpression(theEnv,waste->externalNetworkTest); + ReturnExpression(theEnv,waste->secondaryNetworkTest); + ReturnExpression(theEnv,waste->externalRightHash); + ReturnExpression(theEnv,waste->externalLeftHash); + ReturnExpression(theEnv,waste->constantSelector); + ReturnExpression(theEnv,waste->constantValue); + ReturnExpression(theEnv,waste->leftHash); + ReturnExpression(theEnv,waste->betaHash); + ReturnExpression(theEnv,waste->rightHash); ReturnLHSParseNodes(theEnv,waste->right); ReturnLHSParseNodes(theEnv,waste->bottom); ReturnLHSParseNodes(theEnv,waste->expression); + ReturnLHSParseNodes(theEnv,waste->secondaryExpression); if (waste->derivedConstraints) RemoveConstraint(theEnv,waste->constraints); if ((waste->userData != NULL) && (waste->patternType->returnUserDataFunction != NULL)) @@ -1151,8 +1419,7 @@ static void IncrementNandDepth( /* CE or when no CEs are specified in the LHS of a rule. */ /***********************************************************/ static struct lhsParseNode *CreateInitialPattern( - void *theEnv, - struct patternParser *theParser) + void *theEnv) { struct lhsParseNode *topNode; @@ -1164,54 +1431,8 @@ static struct lhsParseNode *CreateInitialPattern( topNode->type = PATTERN_CE; topNode->userCE = FALSE; topNode->bottom = NULL; - - /*==============================================*/ - /* If a pattern type was not supplied, then try */ - /* to use the (initial-fact) fact pattern. */ - /*==============================================*/ - - if (theParser == NULL) - { theParser = FindPatternParser(theEnv,"facts"); } - - /*====================================================*/ - /* If a pattern type was supplied or the initial fact */ - /* pattern is available, create the initial pattern */ - /* with one of those in the given order. */ - /*====================================================*/ - - if (theParser != NULL) - { - topNode->right = (*theParser->initialPatternFunction)(theEnv); - PropagatePatternType(topNode,theParser); - return(topNode); - } - - /*=============================================*/ - /* If neither a pattern type was supplied nor */ - /* the initial fact pattern was available, use */ - /* any available initial pattern. */ - /*=============================================*/ - - for (theParser = PatternData(theEnv)->ListOfPatternParsers; - theParser != NULL; - theParser = theParser->next) - { - if (theParser->initialPatternFunction != NULL) - { - topNode->right = (*theParser->initialPatternFunction)(theEnv); - PropagatePatternType(topNode,theParser); - return(topNode); - } - } - - /*===========================================*/ - /* There must be at least one pattern parser */ - /* capable of creating an initial pattern. */ - /*===========================================*/ - - SystemError(theEnv,"REORDER",2); - - return(NULL); + + return(topNode); } /*****************************************************************/ @@ -1220,196 +1441,41 @@ static struct lhsParseNode *CreateInitialPattern( /* pattern has been added to the beginning of the rule if one */ /* was needed. */ /*****************************************************************/ -static void AddRemainingInitialPatterns( +static struct lhsParseNode *AddRemainingInitialPatterns( void *theEnv, - struct lhsParseNode *theLHS, - struct patternParser *defaultType) + struct lhsParseNode *theLHS) { - struct lhsParseNode *trackNode, *tempNode, *lastNode; - - /*====================================================*/ - /* Set the mark flag for each CE in the LHS to FALSE. */ - /*====================================================*/ - - for (trackNode = theLHS; trackNode != NULL; trackNode = trackNode->bottom) - { trackNode->marked = FALSE; } - - /*==================================*/ - /* Loop through each CE in the LHS. */ - /*==================================*/ - - lastNode = NULL; + struct lhsParseNode *lastNode = NULL, *thePattern, *rv = theLHS; + int currentDepth = 1; + while (theLHS != NULL) { - /*===================================*/ - /* A "not" CE will not propagate its */ - /* pattern type to following CEs. */ - /*===================================*/ - - if ((theLHS->negated) && (theLHS->marked)) - { trackNode = NULL; } - - /*==================================================*/ - /* A "test" or "not" CE was found that has not been */ - /* marked. Add an initial pattern before the CE. */ - /*==================================================*/ - - else if (((theLHS->type == TEST_CE) || (theLHS->negated)) && - (theLHS->marked == FALSE)) + if ((theLHS->type == TEST_CE) && + (theLHS->beginNandDepth > currentDepth)) { - if (theLHS->negated) tempNode = CreateInitialPattern(theEnv,theLHS->patternType); - else tempNode = CreateInitialPattern(theEnv,defaultType); - - tempNode->logical = theLHS->logical; - tempNode->beginNandDepth = theLHS->beginNandDepth; - tempNode->endNandDepth = theLHS->beginNandDepth; - + thePattern = CreateInitialPattern(theEnv); + thePattern->beginNandDepth = theLHS->beginNandDepth; + thePattern->endNandDepth = theLHS->beginNandDepth; + thePattern->logical = theLHS->logical; + thePattern->existsNand = theLHS->existsNand; + theLHS->existsNand = FALSE; + + thePattern->bottom = theLHS; + if (lastNode == NULL) - { SystemError(theEnv,"REORDER",3); } - - lastNode->bottom = tempNode; - tempNode->bottom = theLHS; - theLHS = tempNode; - - trackNode = theLHS->bottom; - } - - /*===================================================*/ - /* If a pattern CE is found, then propagate its type */ - /* to following test CEs in the same lexical scope. */ - /*===================================================*/ - - else - { trackNode = theLHS->bottom; } - - /*=======================================================*/ - /* Mark the pattern type of a "test" or "not" CE as the */ - /* same type as the last pattern CE found that is within */ - /* the same lexical scope as the "test" or "not" CE. */ - /*=======================================================*/ - - for (; - trackNode != NULL; - trackNode = trackNode->bottom) - { - /*=====================================*/ - /* If the CE isn't in the same lexical */ - /* scope, move on to the next CE. */ - /*=====================================*/ - - if (trackNode->beginNandDepth != theLHS->beginNandDepth) - { continue; } - - /*=======================================================*/ - /* Mark a negated CE that is in the same lexical scope. */ - /* This signifies that there is a preceeding non-negated */ - /* pattern and thus no need for an initial pattern to be */ - /* placed before this CE. */ - /*=======================================================*/ - - else if (trackNode->negated) - { trackNode->marked = TRUE; } - - /*====================================================*/ - /* If another non-negated pattern in the same lexical */ - /* scope if found, stop propagation of the current */ - /* pattern type. */ - /*====================================================*/ - - else if (trackNode->type == PATTERN_CE) - { break; } - - /*====================================================*/ - /* A "test" CE in the same lexical scope is marked to */ - /* indicate that it has a non-negated pattern that it */ - /* can be attached to. */ - /*====================================================*/ - - else if (trackNode->type == TEST_CE) - { - trackNode->marked = TRUE; - trackNode->patternType = theLHS->patternType; - } + { rv = thePattern; } + else + { lastNode->bottom = thePattern; } } - - /*====================================*/ - /* Move on to the next CE in the LHS. */ - /*====================================*/ - + lastNode = theLHS; + currentDepth = theLHS->endNandDepth; theLHS = theLHS->bottom; } - } + + return(rv); + } -/**********************************************/ -/* PrintNodes: Debugging routine which prints */ -/* the representation of a CE. */ -/**********************************************/ -/*static void PrintNodes( - void *theEnv, - char *fileid, - struct lhsParseNode *theNode) - { - if (theNode == NULL) return; - - while (theNode != NULL) - { - switch (theNode->type) - { - case PATTERN_CE: - EnvPrintRouter(theEnv,fileid,"("); - if (theNode->negated) EnvPrintRouter(theEnv,fileid,"n"); - if (theNode->logical) EnvPrintRouter(theEnv,fileid,"l"); - PrintLongInteger(theEnv,fileid,(long) theNode->beginNandDepth); - EnvPrintRouter(theEnv,fileid,"-"); - PrintLongInteger(theEnv,fileid,(long) theNode->endNandDepth); - EnvPrintRouter(theEnv,fileid," "); - EnvPrintRouter(theEnv,fileid,ValueToString(theNode->right->bottom->value)); - EnvPrintRouter(theEnv,fileid,")"); - break; - - case TEST_CE: - EnvPrintRouter(theEnv,fileid,"(test "); - PrintLongInteger(theEnv,fileid,(long) theNode->beginNandDepth); - EnvPrintRouter(theEnv,fileid,"-"); - PrintLongInteger(theEnv,fileid,(long) theNode->endNandDepth); - EnvPrintRouter(theEnv,fileid,")"); - break; - - case NOT_CE: - if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(lnot "); - else EnvPrintRouter(theEnv,fileid,"(not ");; - PrintNodes(theEnv,fileid,theNode->right); - EnvPrintRouter(theEnv,fileid,")"); - break; - - case OR_CE: - if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(lor "); - else EnvPrintRouter(theEnv,fileid,"(or "); - PrintNodes(theEnv,fileid,theNode->right); - EnvPrintRouter(theEnv,fileid,")"); - break; - - case AND_CE: - if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(land "); - else EnvPrintRouter(theEnv,fileid,"(and "); - PrintNodes(theEnv,fileid,theNode->right); - EnvPrintRouter(theEnv,fileid,")"); - break; - - default: - EnvPrintRouter(theEnv,fileid,"(unknown)"); - break; - - } - - theNode = theNode->bottom; - if (theNode != NULL) EnvPrintRouter(theEnv,fileid," "); - } - - return; - } -*/ /*************************************************************/ /* AssignPatternIndices: For each pattern CE in the LHS of a */ /* rule, determines the pattern index for the CE. A simple */ @@ -1425,13 +1491,12 @@ static void AddRemainingInitialPatterns( /*************************************************************/ static struct lhsParseNode *AssignPatternIndices( struct lhsParseNode *theLHS, - short startIndex) + short startIndex, + int nandDepth, + short joinDepth) { - int depth; struct lhsParseNode *theField; - depth = theLHS->beginNandDepth; - /*====================================*/ /* Loop through the CEs at this level */ /* assigning each CE a pattern index. */ @@ -1449,21 +1514,31 @@ static struct lhsParseNode *AssignPatternIndices( /* return to the previous level. */ /*============================================================*/ - if (theLHS->beginNandDepth > depth) + if (theLHS->beginNandDepth > nandDepth) { - theLHS = AssignPatternIndices(theLHS,startIndex); - if (theLHS->endNandDepth < depth) return(theLHS); + theLHS = AssignPatternIndices(theLHS,startIndex,theLHS->beginNandDepth,joinDepth); + if (theLHS->endNandDepth < nandDepth) return(theLHS); startIndex++; + joinDepth++; } /*=====================================================*/ /* A test CE is not assigned a pattern index, however, */ /* if it is the last CE at the end of this level, then */ - /* return to the previous level. */ + /* return to the previous level. If this is the first */ + /* CE in a group, it will have a join created so the */ + /* depth should be incremented. */ /*=====================================================*/ else if (theLHS->type == TEST_CE) - { if (theLHS->endNandDepth < depth) return(theLHS); } + { + if (joinDepth == 0) + { joinDepth++; } + theLHS->joinDepth = joinDepth - 1; + PropagateJoinDepth(theLHS->expression,(short) (joinDepth - 1)); + PropagateNandDepth(theLHS->expression,theLHS->beginNandDepth,theLHS->endNandDepth); + if (theLHS->endNandDepth < nandDepth) return(theLHS); + } /*==========================================================*/ /* The fields of a pattern CE need to be assigned a pattern */ @@ -1474,7 +1549,16 @@ static struct lhsParseNode *AssignPatternIndices( else if (theLHS->type == PATTERN_CE) { + if (theLHS->expression != NULL) + { + PropagateJoinDepth(theLHS->expression,(short) joinDepth); + PropagateNandDepth(theLHS->expression,theLHS->beginNandDepth,theLHS->endNandDepth); + } + theLHS->pattern = startIndex; + theLHS->joinDepth = joinDepth; + PropagateJoinDepth(theLHS->right,joinDepth); + PropagateNandDepth(theLHS->right,theLHS->beginNandDepth,theLHS->endNandDepth); for (theField = theLHS->right; theField != NULL; theField = theField->right) { theField->pattern = startIndex; @@ -1483,8 +1567,9 @@ static struct lhsParseNode *AssignPatternIndices( theField->slotNumber); } - if (theLHS->endNandDepth < depth) return(theLHS); + if (theLHS->endNandDepth < nandDepth) return(theLHS); startIndex++; + joinDepth++; } /*=========================*/ @@ -1571,5 +1656,299 @@ static void PropagateIndexSlotPatternValues( } } +/***************************************************/ +/* AssignPatternMarkedFlag: Recursively assigns */ +/* value to the marked field of a LHSParseNode. */ +/***************************************************/ +globle void AssignPatternMarkedFlag( + struct lhsParseNode *theField, + short markedValue) + { + while (theField != NULL) + { + theField->marked = markedValue; + if (theField->bottom != NULL) + { AssignPatternMarkedFlag(theField->bottom,markedValue); } + if (theField->expression != NULL) + { AssignPatternMarkedFlag(theField->expression,markedValue); } + if (theField->secondaryExpression != NULL) + { AssignPatternMarkedFlag(theField->secondaryExpression,markedValue); } + theField = theField->right; + } + } + +/*****************************************************************/ +/* PropagateJoinDepth: Recursively assigns a joinDepth to each */ +/* node in a LHS node by following the right and bottom links. */ +/*****************************************************************/ +static void PropagateJoinDepth( + struct lhsParseNode *theField, + short joinDepth) + { + while (theField != NULL) + { + theField->joinDepth = joinDepth; + if (theField->bottom != NULL) + { PropagateJoinDepth(theField->bottom,joinDepth); } + if (theField->expression != NULL) + { PropagateJoinDepth(theField->expression,joinDepth); } + if (theField->secondaryExpression != NULL) + { PropagateJoinDepth(theField->secondaryExpression,joinDepth); } + theField = theField->right; + } + } + +/**************************************************************/ +/* PropagateNandDepth: Recursively assigns the not/and (nand) */ +/* depth to each node in a LHS node by following the right, */ +/* bottom, and expression links. */ +/**************************************************************/ +static void PropagateNandDepth( + struct lhsParseNode *theField, + int beginDepth, + int endDepth) + { + if (theField == NULL) return; + + for (; theField != NULL; theField = theField->right) + { + theField->beginNandDepth = beginDepth; + theField->endNandDepth = endDepth; + PropagateNandDepth(theField->expression,beginDepth,endDepth); + PropagateNandDepth(theField->secondaryExpression,beginDepth,endDepth); + PropagateNandDepth(theField->bottom,beginDepth,endDepth); + } + } + +/*****************************************/ +/* PropagateWhichCE: Recursively assigns */ +/* an index indicating the user CE. */ +/*****************************************/ +static int PropagateWhichCE( + struct lhsParseNode *theField, + int whichCE) + { + while (theField != NULL) + { + if ((theField->type == PATTERN_CE) || (theField->type == TEST_CE)) + { whichCE++; } + + theField->whichCE = whichCE; + + whichCE = PropagateWhichCE(theField->right,whichCE); + PropagateWhichCE(theField->expression,whichCE); + + theField = theField->bottom; + } + + return whichCE; + } + +/********************/ +/* IsExistsSubjoin: */ +/********************/ +globle int IsExistsSubjoin( + struct lhsParseNode *theLHS, + int parentDepth) + { + int startDepth = theLHS->beginNandDepth; + + if ((startDepth - parentDepth) != 2) + { return(FALSE); } + + while (theLHS->endNandDepth >= startDepth) + { theLHS = theLHS->bottom; } + + if (theLHS->endNandDepth <= parentDepth) + { return(TRUE); } + + return(FALSE); + } + +/***************************************************************************/ +/* CombineLHSParseNodes: Combines two expressions into a single equivalent */ +/* expression. Mainly serves to merge expressions containing "and" */ +/* and "or" expressions without unnecessary duplication of the "and" */ +/* and "or" expressions (i.e., two "and" expressions can be merged by */ +/* placing them as arguments within another "and" expression, but it */ +/* is more efficient to add the arguments of one of the "and" */ +/* expressions to the list of arguments for the other and expression). */ +/***************************************************************************/ +globle struct lhsParseNode *CombineLHSParseNodes( + void *theEnv, + struct lhsParseNode *expr1, + struct lhsParseNode *expr2) + { + struct lhsParseNode *tempPtr; + + /*===========================================================*/ + /* If the 1st expression is NULL, return the 2nd expression. */ + /*===========================================================*/ + + if (expr1 == NULL) return(expr2); + + /*===========================================================*/ + /* If the 2nd expression is NULL, return the 1st expression. */ + /*===========================================================*/ + + if (expr2 == NULL) return(expr1); + + /*============================================================*/ + /* If the 1st expression is an "and" expression, and the 2nd */ + /* expression is not an "and" expression, then include the */ + /* 2nd expression in the argument list of the 1st expression. */ + /*============================================================*/ + + if ((expr1->value == ExpressionData(theEnv)->PTR_AND) && + (expr2->value != ExpressionData(theEnv)->PTR_AND)) + { + tempPtr = expr1->bottom; + if (tempPtr == NULL) + { + rtn_struct(theEnv,lhsParseNode,expr1); + return(expr2); + } + + while (tempPtr->right != NULL) + { tempPtr = tempPtr->right; } + + tempPtr->right = expr2; + return(expr1); + } + + /*============================================================*/ + /* If the 2nd expression is an "and" expression, and the 1st */ + /* expression is not an "and" expression, then include the */ + /* 1st expression in the argument list of the 2nd expression. */ + /*============================================================*/ + + if ((expr1->value != ExpressionData(theEnv)->PTR_AND) && + (expr2->value == ExpressionData(theEnv)->PTR_AND)) + { + tempPtr = expr2->bottom; + if (tempPtr == NULL) + { + rtn_struct(theEnv,lhsParseNode,expr2); + return(expr1); + } + + expr2->bottom = expr1; + expr1->right = tempPtr; + + return(expr2); + } + + /*===========================================================*/ + /* If both expressions are "and" expressions, then add the */ + /* 2nd expression to the argument list of the 1st expression */ + /* and throw away the extraneous "and" expression. */ + /*===========================================================*/ + + if ((expr1->value == ExpressionData(theEnv)->PTR_AND) && + (expr2->value == ExpressionData(theEnv)->PTR_AND)) + { + tempPtr = expr1->bottom; + if (tempPtr == NULL) + { + rtn_struct(theEnv,lhsParseNode,expr1); + return(expr2); + } + + while (tempPtr->right != NULL) + { tempPtr = tempPtr->right; } + + tempPtr->right = expr2->bottom; + rtn_struct(theEnv,lhsParseNode,expr2); + + return(expr1); + } + + /*=====================================================*/ + /* If neither expression is an "and" expression, then */ + /* create an "and" expression and add both expressions */ + /* to the argument list of that "and" expression. */ + /*=====================================================*/ + + tempPtr = GetLHSParseNode(theEnv); + tempPtr->type = FCALL; + tempPtr->value = ExpressionData(theEnv)->PTR_AND; + + tempPtr->bottom = expr1; + expr1->right = expr2; + return(tempPtr); + } + +/**********************************************/ +/* PrintNodes: Debugging routine which prints */ +/* the representation of a CE. */ +/**********************************************/ +/* +static void PrintNodes( + void *theEnv, + const char *fileid, + struct lhsParseNode *theNode) + { + if (theNode == NULL) return; + + while (theNode != NULL) + { + switch (theNode->type) + { + case PATTERN_CE: + EnvPrintRouter(theEnv,fileid,"("); + if (theNode->negated) EnvPrintRouter(theEnv,fileid,"n"); + if (theNode->exists) EnvPrintRouter(theEnv,fileid,"x"); + if (theNode->logical) EnvPrintRouter(theEnv,fileid,"l"); + PrintLongInteger(theEnv,fileid,(long long) theNode->beginNandDepth); + EnvPrintRouter(theEnv,fileid,"-"); + PrintLongInteger(theEnv,fileid,(long long) theNode->endNandDepth); + EnvPrintRouter(theEnv,fileid," "); + EnvPrintRouter(theEnv,fileid,ValueToString(theNode->right->bottom->value)); + EnvPrintRouter(theEnv,fileid,")"); + break; + + case TEST_CE: + EnvPrintRouter(theEnv,fileid,"(test "); + PrintLongInteger(theEnv,fileid,(long long) theNode->beginNandDepth); + EnvPrintRouter(theEnv,fileid,"-"); + PrintLongInteger(theEnv,fileid,(long long) theNode->endNandDepth); + EnvPrintRouter(theEnv,fileid,")"); + break; + + case NOT_CE: + if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(lnot "); + else EnvPrintRouter(theEnv,fileid,"(not ");; + PrintNodes(theEnv,fileid,theNode->right); + EnvPrintRouter(theEnv,fileid,")"); + break; + + case OR_CE: + if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(lor "); + else EnvPrintRouter(theEnv,fileid,"(or "); + PrintNodes(theEnv,fileid,theNode->right); + EnvPrintRouter(theEnv,fileid,")"); + break; + + case AND_CE: + if (theNode->logical) EnvPrintRouter(theEnv,fileid,"(land "); + else EnvPrintRouter(theEnv,fileid,"(and "); + PrintNodes(theEnv,fileid,theNode->right); + EnvPrintRouter(theEnv,fileid,")"); + break; + + default: + EnvPrintRouter(theEnv,fileid,"(unknown)"); + break; + + } + + theNode = theNode->bottom; + if (theNode != NULL) EnvPrintRouter(theEnv,fileid," "); + } + + return; + } +*/ + #endif diff --git a/src/reorder.h b/src/reorder.h index 4305e9f..237f1d2 100644 --- a/src/reorder.h +++ b/src/reorder.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* REORDER HEADER FILE */ /*******************************************************/ @@ -25,6 +25,16 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Support for join network changes. */ +/* */ +/* Changes to the algorithm for processing */ +/* not/and CE groups. */ +/* */ +/* Additional optimizations for combining */ +/* conditional elements. */ +/* */ +/* Added support for hashed alpha memories. */ +/* */ /*************************************************************/ #ifndef _H_reorder @@ -61,6 +71,8 @@ struct lhsParseNode unsigned short type; void *value; unsigned int negated : 1; + unsigned int exists : 1; + unsigned int existsNand : 1; unsigned int logical : 1; unsigned int multifieldSlot : 1; unsigned int bindingVariable : 1; @@ -82,23 +94,37 @@ struct lhsParseNode short slotNumber; int beginNandDepth; int endNandDepth; + int joinDepth; struct expr *networkTest; + struct expr *externalNetworkTest; + struct expr *secondaryNetworkTest; + struct expr *externalLeftHash; + struct expr *externalRightHash; + struct expr *constantSelector; + struct expr *constantValue; + struct expr *leftHash; + struct expr *rightHash; + struct expr *betaHash; struct lhsParseNode *expression; + struct lhsParseNode *secondaryExpression; void *userData; struct lhsParseNode *right; struct lhsParseNode *bottom; }; -LOCALE struct lhsParseNode *ReorderPatterns(void *,struct lhsParseNode *,int *); -LOCALE struct lhsParseNode *CopyLHSParseNodes(void *,struct lhsParseNode *); -LOCALE void CopyLHSParseNode(void *,struct lhsParseNode *,struct lhsParseNode *,int); -LOCALE struct lhsParseNode *GetLHSParseNode(void *); -LOCALE void ReturnLHSParseNodes(void *,struct lhsParseNode *); -LOCALE struct lhsParseNode *ExpressionToLHSParseNodes(void *,struct expr *); -LOCALE struct expr *LHSParseNodesToExpression(void *,struct lhsParseNode *); -LOCALE void AddInitialPatterns(void *,struct lhsParseNode *); + LOCALE struct lhsParseNode *ReorderPatterns(void *,struct lhsParseNode *,int *); + LOCALE struct lhsParseNode *CopyLHSParseNodes(void *,struct lhsParseNode *); + LOCALE void CopyLHSParseNode(void *,struct lhsParseNode *,struct lhsParseNode *,int); + LOCALE struct lhsParseNode *GetLHSParseNode(void *); + LOCALE void ReturnLHSParseNodes(void *,struct lhsParseNode *); + LOCALE struct lhsParseNode *ExpressionToLHSParseNodes(void *,struct expr *); + LOCALE struct expr *LHSParseNodesToExpression(void *,struct lhsParseNode *); + LOCALE void AddInitialPatterns(void *,struct lhsParseNode *); + LOCALE int IsExistsSubjoin(struct lhsParseNode *,int); + LOCALE struct lhsParseNode *CombineLHSParseNodes(void *,struct lhsParseNode *,struct lhsParseNode *); + LOCALE void AssignPatternMarkedFlag(struct lhsParseNode *,short); -#endif +#endif /* _H_reorder */ diff --git a/src/reteutil.c b/src/reteutil.c index c553335..0bd8949 100644 --- a/src/reteutil.c +++ b/src/reteutil.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* RETE UTILITY MODULE */ /*******************************************************/ @@ -22,6 +22,26 @@ /* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for join network changes. */ +/* */ +/* Support for using an asterick (*) to indicate */ +/* that existential patterns are matched. */ +/* */ +/* Support for partial match changes. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _RETEUTIL_SOURCE_ @@ -43,6 +63,7 @@ #include "pattern.h" #include "retract.h" #include "router.h" +#include "rulecom.h" #include "reteutil.h" @@ -50,8 +71,20 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void TraceErrorToRuleDriver(void *,struct joinNode *,char *); - + static void TraceErrorToRuleDriver(void *,struct joinNode *,const char *,int,int); + static struct alphaMemoryHash *FindAlphaMemory(void *,struct patternNodeHeader *,unsigned long); + static unsigned long AlphaMemoryHashValue(struct patternNodeHeader *,unsigned long); + static void UnlinkAlphaMemory(void *,struct patternNodeHeader *,struct alphaMemoryHash *); + static void UnlinkAlphaMemoryBucketSiblings(void *,struct alphaMemoryHash *); + static void InitializePMLinks(struct partialMatch *); + static void UnlinkBetaPartialMatchfromAlphaAndBetaLineage(struct partialMatch *); + static int CountPriorPatterns(struct joinNode *); + static void ResizeBetaMemory(void *,struct betaMemory *); + static void ResetBetaMemory(void *,struct betaMemory *); +#if (CONSTRUCT_COMPILER || BLOAD_AND_BSAVE) && (! RUN_TIME) + static void TagNetworkTraverseJoins(void *,long int *,long int *,struct joinNode *); +#endif + /***********************************************************/ /* PrintPartialMatch: Prints out the list of fact indices */ /* and/or instance names associated with a partial match */ @@ -59,21 +92,24 @@ /***********************************************************/ globle void PrintPartialMatch( void *theEnv, - char *logicalName, + const char *logicalName, struct partialMatch *list) { struct patternEntity *matchingItem; - short int i; + unsigned short i; - for (i = 0; i < (int) list->bcount;) + for (i = 0; i < list->bcount;) { - if (get_nth_pm_match(list,i)->matchingItem != NULL) + if ((get_nth_pm_match(list,i) != NULL) && + (get_nth_pm_match(list,i)->matchingItem != NULL)) { matchingItem = get_nth_pm_match(list,i)->matchingItem; - if (matchingItem != NULL) (*matchingItem->theInfo->base.shortPrintFunction)(theEnv,logicalName,matchingItem); + (*matchingItem->theInfo->base.shortPrintFunction)(theEnv,logicalName,matchingItem); } + else + { EnvPrintRouter(theEnv,logicalName,"*"); } i++; - if (i < (int) list->bcount) EnvPrintRouter(theEnv,logicalName,","); + if (i < list->bcount) EnvPrintRouter(theEnv,logicalName,","); } } @@ -82,67 +118,493 @@ globle void PrintPartialMatch( /**********************************************/ globle struct partialMatch *CopyPartialMatch( void *theEnv, - struct partialMatch *list, - int addActivationSlot, - int addDependencySlot) + struct partialMatch *list) { struct partialMatch *linker; - short int i; + unsigned short i; linker = get_var_struct(theEnv,partialMatch,sizeof(struct genericMatch) * - (list->bcount + addActivationSlot + addDependencySlot - 1)); + (list->bcount - 1)); - linker->next = NULL; + InitializePMLinks(linker); linker->betaMemory = TRUE; linker->busy = FALSE; - linker->activationf = addActivationSlot; - linker->dependentsf = addDependencySlot; - linker->notOriginf = FALSE; - linker->counterf = FALSE; + linker->rhsMemory = FALSE; linker->bcount = list->bcount; + linker->hashValue = 0; + + for (i = 0; i < linker->bcount; i++) linker->binds[i] = list->binds[i]; + + return(linker); + } + +/**********************************************/ +/* CreateEmptyPartialMatch: */ +/**********************************************/ +globle struct partialMatch *CreateEmptyPartialMatch( + void *theEnv) + { + struct partialMatch *linker; - for (i = 0; i < (int) linker->bcount; i++) linker->binds[i] = list->binds[i]; + linker = get_struct(theEnv,partialMatch); - if (addActivationSlot) linker->binds[i++].gm.theValue = NULL; - if (addDependencySlot) linker->binds[i].gm.theValue = NULL; + InitializePMLinks(linker); + linker->betaMemory = TRUE; + linker->busy = FALSE; + linker->rhsMemory = FALSE; + linker->bcount = 1; + linker->hashValue = 0; + linker->binds[0].gm.theValue = NULL; return(linker); } /****************************************************/ -/* MergePartialMatches: Merges two partial matches. */ +/* InitializePMLinks: */ /****************************************************/ -globle struct partialMatch *MergePartialMatches( +static void InitializePMLinks( + struct partialMatch *theMatch) + { + theMatch->nextInMemory = NULL; + theMatch->prevInMemory = NULL; + theMatch->nextRightChild = NULL; + theMatch->prevRightChild = NULL; + theMatch->nextLeftChild = NULL; + theMatch->prevLeftChild = NULL; + theMatch->children = NULL; + theMatch->rightParent = NULL; + theMatch->leftParent = NULL; + theMatch->blockList = NULL; + theMatch->nextBlocked = NULL; + theMatch->prevBlocked = NULL; + theMatch->marker = NULL; + theMatch->dependents = NULL; + } + +/***********************************************************/ +/* UpdateBetaPMLinks: . */ +/***********************************************************/ +globle void UpdateBetaPMLinks( void *theEnv, - struct partialMatch *list1, - struct partialMatch *list2, - int addActivationSlot, - int addDependencySlot) + struct partialMatch *thePM, + struct partialMatch *lhsBinds, + struct partialMatch *rhsBinds, + struct joinNode *join, + unsigned long hashValue, + int side) { - struct partialMatch *linker; - short int i, j; + unsigned long betaLocation; + struct betaMemory *theMemory; + + if (side == LHS) + { + theMemory = join->leftMemory; + thePM->rhsMemory = FALSE; + } + else + { + theMemory = join->rightMemory; + thePM->rhsMemory = TRUE; + } + + thePM->hashValue = hashValue; + + /*================================*/ + /* Update the node's linked list. */ + /*================================*/ + + betaLocation = hashValue % theMemory->size; + + if (side == LHS) + { + thePM->nextInMemory = theMemory->beta[betaLocation]; + if (theMemory->beta[betaLocation] != NULL) + { theMemory->beta[betaLocation]->prevInMemory = thePM; } + theMemory->beta[betaLocation] = thePM; + } + else + { + if (theMemory->last[betaLocation] != NULL) + { + theMemory->last[betaLocation]->nextInMemory = thePM; + thePM->prevInMemory = theMemory->last[betaLocation]; + } + else + { theMemory->beta[betaLocation] = thePM; } + + theMemory->last[betaLocation] = thePM; + } + + theMemory->count++; + if (side == LHS) + { join->memoryLeftAdds++; } + else + { join->memoryRightAdds++; } + + thePM->owner = join; + + /*======================================*/ + /* Update the alpha memory linked list. */ + /*======================================*/ + + if (rhsBinds != NULL) + { + thePM->nextRightChild = rhsBinds->children; + if (rhsBinds->children != NULL) + { rhsBinds->children->prevRightChild = thePM; } + rhsBinds->children = thePM; + thePM->rightParent = rhsBinds; + } + + /*=====================================*/ + /* Update the beta memory linked list. */ + /*=====================================*/ + + if (lhsBinds != NULL) + { + thePM->nextLeftChild = lhsBinds->children; + if (lhsBinds->children != NULL) + { lhsBinds->children->prevLeftChild = thePM; } + lhsBinds->children = thePM; + thePM->leftParent = lhsBinds; + } - linker = get_var_struct(theEnv,partialMatch, - sizeof(struct genericMatch) * - (list1->bcount + list2->bcount + addActivationSlot + addDependencySlot - 1)); + if (! DefruleData(theEnv)->BetaMemoryResizingFlag) + { return; } - linker->next = NULL; - linker->betaMemory = TRUE; - linker->busy = FALSE; - linker->activationf = addActivationSlot; - linker->dependentsf = addDependencySlot; - linker->notOriginf = FALSE; - linker->counterf = FALSE; - linker->bcount = list1->bcount + list2->bcount; + if ((theMemory->size > 1) && + (theMemory->count > (theMemory->size * 11))) + { ResizeBetaMemory(theEnv,theMemory); } + } + +/**********************************************************/ +/* AddBlockedLink: Adds a link between a partial match in */ +/* the beta memory of a join (with a negated RHS) and a */ +/* partial match in its right memory that prevents the */ +/* partial match from being satisfied and propagated to */ +/* the next join in the rule. */ +/**********************************************************/ +globle void AddBlockedLink( + struct partialMatch *thePM, + struct partialMatch *rhsBinds) + { + thePM->marker = rhsBinds; + thePM->nextBlocked = rhsBinds->blockList; + if (rhsBinds->blockList != NULL) + { rhsBinds->blockList->prevBlocked = thePM; } + rhsBinds->blockList = thePM; + } + +/*************************************************************/ +/* RemoveBlockedLink: Removes a link between a partial match */ +/* in the beta memory of a join (with a negated RHS) and a */ +/* partial match in its right memory that prevents the */ +/* partial match from being satisfied and propagated to */ +/* the next join in the rule. */ +/*************************************************************/ +globle void RemoveBlockedLink( + struct partialMatch *thePM) + { + struct partialMatch *blocker; + + if (thePM->prevBlocked == NULL) + { + blocker = (struct partialMatch *) thePM->marker; + blocker->blockList = thePM->nextBlocked; + } + else + { thePM->prevBlocked->nextBlocked = thePM->nextBlocked; } + + if (thePM->nextBlocked != NULL) + { thePM->nextBlocked->prevBlocked = thePM->prevBlocked; } + + thePM->nextBlocked = NULL; + thePM->prevBlocked = NULL; + thePM->marker = NULL; + } + +/***********************************************************/ +/* UnlinkBetaPMFromNodeAndLineage: . */ +/***********************************************************/ +globle void UnlinkBetaPMFromNodeAndLineage( + void *theEnv, + struct joinNode *join, + struct partialMatch *thePM, + int side) + { + unsigned long betaLocation; + struct betaMemory *theMemory; + + if (side == LHS) + { theMemory = join->leftMemory; } + else + { theMemory = join->rightMemory; } + + /*=============================================*/ + /* Update the nextInMemory/prevInMemory links. */ + /*=============================================*/ + + theMemory->count--; + + if (side == LHS) + { join->memoryLeftDeletes++; } + else + { join->memoryRightDeletes++; } + + betaLocation = thePM->hashValue % theMemory->size; + + if ((side == RHS) && + (theMemory->last[betaLocation] == thePM)) + { theMemory->last[betaLocation] = thePM->prevInMemory; } + + if (thePM->prevInMemory == NULL) + { + betaLocation = thePM->hashValue % theMemory->size; + theMemory->beta[betaLocation] = thePM->nextInMemory; + } + else + { thePM->prevInMemory->nextInMemory = thePM->nextInMemory; } + + if (thePM->nextInMemory != NULL) + { thePM->nextInMemory->prevInMemory = thePM->prevInMemory; } + + thePM->nextInMemory = NULL; + thePM->prevInMemory = NULL; + + UnlinkBetaPartialMatchfromAlphaAndBetaLineage(thePM); + + if (! DefruleData(theEnv)->BetaMemoryResizingFlag) + { return; } + + if ((theMemory->count == 0) && (theMemory->size > 1)) + { ResetBetaMemory(theEnv,theMemory); } + } + +/***********************************************************/ +/* UnlinkNonLeftLineage: . */ +/***********************************************************/ +globle void UnlinkNonLeftLineage( + void *theEnv, + struct joinNode *join, + struct partialMatch *thePM, + int side) + { + unsigned long betaLocation; + struct betaMemory *theMemory; + struct partialMatch *tempPM; + + if (side == LHS) + { theMemory = join->leftMemory; } + else + { theMemory = join->rightMemory; } + + /*=============================================*/ + /* Update the nextInMemory/prevInMemory links. */ + /*=============================================*/ + + theMemory->count--; + + if (side == LHS) + { join->memoryLeftDeletes++; } + else + { join->memoryRightDeletes++; } + + betaLocation = thePM->hashValue % theMemory->size; + + if ((side == RHS) && + (theMemory->last[betaLocation] == thePM)) + { theMemory->last[betaLocation] = thePM->prevInMemory; } + + if (thePM->prevInMemory == NULL) + { + betaLocation = thePM->hashValue % theMemory->size; + theMemory->beta[betaLocation] = thePM->nextInMemory; + } + else + { thePM->prevInMemory->nextInMemory = thePM->nextInMemory; } + + if (thePM->nextInMemory != NULL) + { thePM->nextInMemory->prevInMemory = thePM->prevInMemory; } + + /*=========================*/ + /* Update the alpha lists. */ + /*=========================*/ + + if (thePM->prevRightChild == NULL) + { + if (thePM->rightParent != NULL) + { + thePM->rightParent->children = thePM->nextRightChild; + if (thePM->nextRightChild != NULL) + { + thePM->rightParent->children = thePM->nextRightChild; + thePM->nextRightChild->rightParent = thePM->rightParent; + } + } + } + else + { thePM->prevRightChild->nextRightChild = thePM->nextRightChild; } + + if (thePM->nextRightChild != NULL) + { thePM->nextRightChild->prevRightChild = thePM->prevRightChild; } + + /*===========================*/ + /* Update the blocked lists. */ + /*===========================*/ + + if (thePM->prevBlocked == NULL) + { + tempPM = (struct partialMatch *) thePM->marker; + + if (tempPM != NULL) + { tempPM->blockList = thePM->nextBlocked; } + } + else + { thePM->prevBlocked->nextBlocked = thePM->nextBlocked; } + + if (thePM->nextBlocked != NULL) + { thePM->nextBlocked->prevBlocked = thePM->prevBlocked; } + + if (! DefruleData(theEnv)->BetaMemoryResizingFlag) + { return; } + + if ((theMemory->count == 0) && (theMemory->size > 1)) + { ResetBetaMemory(theEnv,theMemory); } + } + +/*******************************************************************/ +/* UnlinkBetaPartialMatchfromAlphaAndBetaLineage: Removes the */ +/* lineage links from a beta memory partial match. This removes */ +/* the links between this partial match and its left and right */ +/* memory parents. It also removes the links between this */ +/* partial match and any of its children in other beta memories. */ +/*******************************************************************/ +static void UnlinkBetaPartialMatchfromAlphaAndBetaLineage( + struct partialMatch *thePM) + { + struct partialMatch *tempPM; + + /*=========================*/ + /* Update the alpha lists. */ + /*=========================*/ + + if (thePM->prevRightChild == NULL) + { + if (thePM->rightParent != NULL) + { thePM->rightParent->children = thePM->nextRightChild; } + } + else + { thePM->prevRightChild->nextRightChild = thePM->nextRightChild; } + + if (thePM->nextRightChild != NULL) + { thePM->nextRightChild->prevRightChild = thePM->prevRightChild; } + + thePM->rightParent = NULL; + thePM->nextRightChild = NULL; + thePM->prevRightChild = NULL; + + /*========================*/ + /* Update the beta lists. */ + /*========================*/ + + if (thePM->prevLeftChild == NULL) + { + if (thePM->leftParent != NULL) + { thePM->leftParent->children = thePM->nextLeftChild; } + } + else + { thePM->prevLeftChild->nextLeftChild = thePM->nextLeftChild; } + + if (thePM->nextLeftChild != NULL) + { thePM->nextLeftChild->prevLeftChild = thePM->prevLeftChild; } - for (i = 0; i < (int) list1->bcount; i++) - { linker->binds[i] = list1->binds[i]; } + thePM->leftParent = NULL; + thePM->nextLeftChild = NULL; + thePM->prevLeftChild = NULL; - for (i = (short) list1->bcount, j = 0; i < (short) linker->bcount; i++, j++) - { linker->binds[i] = list2->binds[j]; } + /*===========================*/ + /* Update the blocked lists. */ + /*===========================*/ - if (addActivationSlot) linker->binds[i++].gm.theValue = NULL; - if (addDependencySlot) linker->binds[i].gm.theValue = NULL; + if (thePM->prevBlocked == NULL) + { + tempPM = (struct partialMatch *) thePM->marker; + + if (tempPM != NULL) + { tempPM->blockList = thePM->nextBlocked; } + } + else + { thePM->prevBlocked->nextBlocked = thePM->nextBlocked; } + + if (thePM->nextBlocked != NULL) + { thePM->nextBlocked->prevBlocked = thePM->prevBlocked; } + + thePM->marker = NULL; + thePM->nextBlocked = NULL; + thePM->prevBlocked = NULL; + + /*===============================================*/ + /* Remove parent reference from the child links. */ + /*===============================================*/ + + if (thePM->children != NULL) + { + if (thePM->rhsMemory) + { + for (tempPM = thePM->children; tempPM != NULL; tempPM = tempPM->nextRightChild) + { tempPM->rightParent = NULL; } + } + else + { + for (tempPM = thePM->children; tempPM != NULL; tempPM = tempPM->nextLeftChild) + { tempPM->leftParent = NULL; } + } + + thePM->children = NULL; + } + } + +/********************************************************/ +/* MergePartialMatches: Merges two partial matches. The */ +/* second match should either be NULL (indicating a */ +/* negated CE) or contain a single match. */ +/********************************************************/ +globle struct partialMatch *MergePartialMatches( + void *theEnv, + struct partialMatch *lhsBind, + struct partialMatch *rhsBind) + { + struct partialMatch *linker; + static struct partialMatch mergeTemplate = { 1 }; /* betaMemory is TRUE, remainder are 0 or NULL */ + + /*=================================*/ + /* Allocate the new partial match. */ + /*=================================*/ + + linker = get_var_struct(theEnv,partialMatch,sizeof(struct genericMatch) * lhsBind->bcount); + + /*============================================*/ + /* Set the flags to their appropriate values. */ + /*============================================*/ + + memcpy(linker,&mergeTemplate,sizeof(struct partialMatch) - sizeof(struct genericMatch)); + + linker->bcount = (unsigned short) (lhsBind->bcount + 1); + + /*========================================================*/ + /* Copy the bindings of the partial match being extended. */ + /*========================================================*/ + + memcpy(linker->binds,lhsBind->binds,sizeof(struct genericMatch) * lhsBind->bcount); + + /*===================================*/ + /* Add the binding of the rhs match. */ + /*===================================*/ + + if (rhsBind == NULL) + { linker->binds[lhsBind->bcount].gm.theValue = NULL; } + else + { linker->binds[lhsBind->bcount].gm.theValue = rhsBind->binds[0].gm.theValue; } return(linker); } @@ -155,12 +617,13 @@ globle void InitializePatternHeader( void *theEnv, struct patternNodeHeader *theHeader) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif + theHeader->firstHash = NULL; + theHeader->lastHash = NULL; theHeader->entryJoin = NULL; - theHeader->alphaMemory = NULL; - theHeader->endOfQueue = NULL; + theHeader->rightHash = NULL; theHeader->singlefieldNode = FALSE; theHeader->multifieldNode = FALSE; theHeader->stopNode = FALSE; @@ -172,6 +635,7 @@ globle void InitializePatternHeader( theHeader->marked = FALSE; theHeader->beginSlot = FALSE; theHeader->endSlot = FALSE; + theHeader->selector = FALSE; } /******************************************************************/ @@ -186,24 +650,24 @@ globle struct partialMatch *CreateAlphaMatch( void *theEnv, void *theEntity, struct multifieldMarker *markers, - struct patternNodeHeader *theHeader) + struct patternNodeHeader *theHeader, + unsigned long hashOffset) { struct partialMatch *theMatch; struct alphaMatch *afbtemp; + unsigned long hashValue; + struct alphaMemoryHash *theAlphaMemory; /*==================================================*/ /* Create the alpha match and intialize its values. */ /*==================================================*/ theMatch = get_struct(theEnv,partialMatch); - theMatch->next = NULL; + InitializePMLinks(theMatch); theMatch->betaMemory = FALSE; theMatch->busy = FALSE; - theMatch->activationf = FALSE; - theMatch->dependentsf = FALSE; - theMatch->notOriginf = FALSE; - theMatch->counterf = FALSE; theMatch->bcount = 1; + theMatch->hashValue = hashOffset; afbtemp = get_struct(theEnv,alphaMatch); afbtemp->next = NULL; @@ -216,20 +680,63 @@ globle struct partialMatch *CreateAlphaMatch( theMatch->binds[0].gm.theMatch = afbtemp; + /*============================================*/ + /* Find the alpha memory of the pattern node. */ + /*============================================*/ + + hashValue = AlphaMemoryHashValue(theHeader,hashOffset); + theAlphaMemory = FindAlphaMemory(theEnv,theHeader,hashValue); + afbtemp->bucket = hashValue; + + /*============================================*/ + /* Create an alpha memory if it wasn't found. */ + /*============================================*/ + + if (theAlphaMemory == NULL) + { + theAlphaMemory = get_struct(theEnv,alphaMemoryHash); + theAlphaMemory->bucket = hashValue; + theAlphaMemory->owner = theHeader; + theAlphaMemory->alphaMemory = NULL; + theAlphaMemory->endOfQueue = NULL; + theAlphaMemory->nextHash = NULL; + + theAlphaMemory->next = DefruleData(theEnv)->AlphaMemoryTable[hashValue]; + if (theAlphaMemory->next != NULL) + { theAlphaMemory->next->prev = theAlphaMemory; } + + theAlphaMemory->prev = NULL; + DefruleData(theEnv)->AlphaMemoryTable[hashValue] = theAlphaMemory; + + if (theHeader->firstHash == NULL) + { + theHeader->firstHash = theAlphaMemory; + theHeader->lastHash = theAlphaMemory; + theAlphaMemory->prevHash = NULL; + } + else + { + theHeader->lastHash->nextHash = theAlphaMemory; + theAlphaMemory->prevHash = theHeader->lastHash; + theHeader->lastHash = theAlphaMemory; + } + } + /*====================================*/ /* Store the alpha match in the alpha */ /* memory of the pattern node. */ /*====================================*/ - - if (theHeader->endOfQueue == NULL) + + theMatch->prevInMemory = theAlphaMemory->endOfQueue; + if (theAlphaMemory->endOfQueue == NULL) { - theHeader->alphaMemory = theMatch; - theHeader->endOfQueue = theMatch; + theAlphaMemory->alphaMemory = theMatch; + theAlphaMemory->endOfQueue = theMatch; } else { - theHeader->endOfQueue->next = theMatch; - theHeader->endOfQueue = theMatch; + theAlphaMemory->endOfQueue->nextInMemory = theMatch; + theAlphaMemory->endOfQueue = theMatch; } /*===================================================*/ @@ -238,45 +745,7 @@ globle struct partialMatch *CreateAlphaMatch( return(theMatch); } - -/*********************************************************/ -/* AddSingleMatch: Combines an alpha match and a partial */ -/* match into a new partial match. */ -/*********************************************************/ -globle struct partialMatch *AddSingleMatch( - void *theEnv, - struct partialMatch *list, - struct alphaMatch *afb, - int addActivationSlot, - int addDependencySlot) - { - struct partialMatch *linker; - short int i; - - linker = get_var_struct(theEnv,partialMatch,sizeof(struct genericMatch) * - (list->bcount + addActivationSlot + - addDependencySlot)); - - linker->next = NULL; - linker->betaMemory = TRUE; - linker->busy = FALSE; - linker->activationf = addActivationSlot; - linker->dependentsf = addDependencySlot; - linker->notOriginf = FALSE; - linker->counterf = FALSE; - linker->bcount = list->bcount + 1; - - for (i = 0; i < (int) list->bcount; i++) - { linker->binds[i] = list->binds[i]; } - - set_nth_pm_match(linker,i++,afb); - - if (addActivationSlot) linker->binds[i++].gm.theValue = NULL; - if (addDependencySlot) linker->binds[i].gm.theValue = NULL; - - return(linker); - } - + /*******************************************/ /* CopyMultifieldMarkers: Copies a list of */ /* multifieldMarker data structures. */ @@ -309,46 +778,12 @@ struct multifieldMarker *CopyMultifieldMarkers( } /***************************************************************/ -/* NewPseudoFactPartialMatch: Creates a partial structure that */ -/* indicates the "pseudo" fact to which a not pattern CE has */ -/* been bound. Since a non-existant fact has no fact index, */ -/* the partial match structure is given a pseudo fact index */ -/* (a unique negative integer). Note that a "pseudo" fact */ -/* can also be used as a "pseudo" instance. */ +/* FlushAlphaBetaMemory: Returns all partial matches in a list */ +/* of partial matches either directly to the pool of free */ +/* memory or to the list of GarbagePartialMatches. Partial */ +/* matches stored in alpha memories must be placed on the */ +/* list of GarbagePartialMatches. */ /***************************************************************/ -globle struct partialMatch *NewPseudoFactPartialMatch( - void *theEnv) - { - struct partialMatch *linker; - struct alphaMatch *tempAlpha; - - linker = get_struct(theEnv,partialMatch); - linker->next = NULL; - linker->betaMemory = TRUE; - linker->busy = FALSE; - linker->activationf = FALSE; - linker->dependentsf = FALSE; - linker->notOriginf = TRUE; - linker->counterf = FALSE; - linker->bcount = 0; - tempAlpha = get_struct(theEnv,alphaMatch); - tempAlpha->next = NULL; - tempAlpha->matchingItem = NULL; - tempAlpha->markers = NULL; - - linker->binds[0].gm.theMatch = tempAlpha; - return(linker); - } - -/******************************************************************/ -/* FlushAlphaBetaMemory: Returns all partial matches in a list of */ -/* partial matches either directly to the pool of free memory */ -/* or to the list of GarbagePartialMatches. Partial matches */ -/* stored in alpha memories and partial matches which store the */ -/* information for pseudo facts (for not CEs) may be referred */ -/* to by other data structures and thus must be placed on the */ -/* list of GarbagePartialMatches. */ -/******************************************************************/ globle void FlushAlphaBetaMemory( void *theEnv, struct partialMatch *pfl) @@ -357,16 +792,10 @@ globle void FlushAlphaBetaMemory( while (pfl != NULL) { - pfltemp = pfl->next; + pfltemp = pfl->nextInMemory; - if (((pfl->notOriginf) && (pfl->counterf == FALSE)) || - (pfl->betaMemory == FALSE)) - { - pfl->next = EngineData(theEnv)->GarbagePartialMatches; - EngineData(theEnv)->GarbagePartialMatches = pfl; - } - else - { ReturnPartialMatch(theEnv,pfl); } + UnlinkBetaPartialMatchfromAlphaAndBetaLineage(pfl); + ReturnPartialMatch(theEnv,pfl); pfl = pfltemp; } @@ -384,10 +813,8 @@ globle void DestroyAlphaBetaMemory( while (pfl != NULL) { - pfltemp = pfl->next; - - DestroyPartialMatch(theEnv,pfl); - + pfltemp = pfl->nextInMemory; + DestroyPartialMatch(theEnv,pfl); pfl = pfltemp; } } @@ -400,17 +827,18 @@ globle int FindEntityInPartialMatch( struct patternEntity *theEntity, struct partialMatch *thePartialMatch) { - short int i; + unsigned short i; - for (i = 0 ; i < (int) thePartialMatch->bcount; i++) + for (i = 0 ; i < thePartialMatch->bcount; i++) { + if (thePartialMatch->binds[i].gm.theMatch == NULL) continue; if (thePartialMatch->binds[i].gm.theMatch->matchingItem == theEntity) { return(TRUE); } } return(FALSE); } - + /***********************************************************************/ /* GetPatternNumberFromJoin: Given a pointer to a join associated with */ /* a pattern CE, returns an integer representing the position of the */ @@ -443,10 +871,17 @@ globle int GetPatternNumberFromJoin( globle void TraceErrorToRule( void *theEnv, struct joinNode *joinPtr, - char *indentSpaces) + const char *indentSpaces) { + int patternCount; + + MarkRuleNetwork(theEnv,0); + + patternCount = CountPriorPatterns(joinPtr->lastLevel) + 1; + + TraceErrorToRuleDriver(theEnv,joinPtr,indentSpaces,patternCount,FALSE); + MarkRuleNetwork(theEnv,0); - TraceErrorToRuleDriver(theEnv,joinPtr,indentSpaces); } /**************************************************************/ @@ -456,30 +891,67 @@ globle void TraceErrorToRule( static void TraceErrorToRuleDriver( void *theEnv, struct joinNode *joinPtr, - char *indentSpaces) + const char *indentSpaces, + int priorRightJoinPatterns, + int enteredJoinFromRight) { - char *name; + const char *name; + int priorPatternCount; + struct joinLink *theLinks; - while (joinPtr != NULL) + if ((joinPtr->joinFromTheRight) && enteredJoinFromRight) + { priorPatternCount = CountPriorPatterns(joinPtr->lastLevel); } + else + { priorPatternCount = 0; } + + if (joinPtr->marked) + { /* Do Nothing */ } + else if (joinPtr->ruleToActivate != NULL) { - if (joinPtr->marked) - { /* Do Nothing */ } - else if (joinPtr->ruleToActivate != NULL) - { - joinPtr->marked = 1; - name = EnvGetDefruleName(theEnv,joinPtr->ruleToActivate); - EnvPrintRouter(theEnv,WERROR,indentSpaces); - EnvPrintRouter(theEnv,WERROR,name); - EnvPrintRouter(theEnv,WERROR,"\n"); - } - else + joinPtr->marked = 1; + name = EnvGetDefruleName(theEnv,joinPtr->ruleToActivate); + EnvPrintRouter(theEnv,WERROR,indentSpaces); + + EnvPrintRouter(theEnv,WERROR,"Of pattern #"); + PrintLongInteger(theEnv,WERROR,priorRightJoinPatterns+priorPatternCount); + EnvPrintRouter(theEnv,WERROR," in rule "); + EnvPrintRouter(theEnv,WERROR,name); + EnvPrintRouter(theEnv,WERROR,"\n"); + } + else + { + joinPtr->marked = 1; + + theLinks = joinPtr->nextLinks; + while (theLinks != NULL) { - joinPtr->marked = 1; - TraceErrorToRuleDriver(theEnv,joinPtr->nextLevel,indentSpaces); + TraceErrorToRuleDriver(theEnv,theLinks->join,indentSpaces, + priorRightJoinPatterns+priorPatternCount, + (theLinks->enterDirection == RHS)); + theLinks = theLinks->next; } + } + } - joinPtr = joinPtr->rightDriveNode; +/**************************************************************/ +/* CountPriorPatterns: */ +/**************************************************************/ +static int CountPriorPatterns( + struct joinNode *joinPtr) + { + int count = 0; + + while (joinPtr != NULL) + { + if (joinPtr->joinFromTheRight) + { count += CountPriorPatterns((struct joinNode *) joinPtr->rightSideEntryStructure); } + else + { count++; } + + joinPtr = joinPtr->lastLevel; } + + return(count); } /********************************************************/ @@ -490,7 +962,7 @@ globle void MarkRuleNetwork( void *theEnv, int value) { - struct defrule *rulePtr; + struct defrule *rulePtr, *disjunctPtr; struct joinNode *joinPtr; struct defmodule *modulePtr; @@ -517,20 +989,17 @@ globle void MarkRuleNetwork( /* with the specified value. */ /*=============================*/ - joinPtr = rulePtr->lastJoin; - while (joinPtr != NULL) + for (disjunctPtr = rulePtr; disjunctPtr != NULL; disjunctPtr = disjunctPtr->disjunct) { - joinPtr->marked = value; - joinPtr = GetPreviousJoin(joinPtr); + joinPtr = disjunctPtr->lastJoin; + MarkRuleJoins(joinPtr,value); } - /*=================================*/ - /* Move on to the next rule or the */ - /* next disjunct for this rule. */ - /*=================================*/ + /*===========================*/ + /* Move on to the next rule. */ + /*===========================*/ - if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct; - else rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); + rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); } } @@ -538,6 +1007,592 @@ globle void MarkRuleNetwork( RestoreCurrentModule(theEnv); } +/*****************************************/ +/* MarkRuleJoins: */ +/*****************************************/ +globle void MarkRuleJoins( + struct joinNode *joinPtr, + int value) + { + while (joinPtr != NULL) + { + if (joinPtr->joinFromTheRight) + { MarkRuleJoins((struct joinNode *) joinPtr->rightSideEntryStructure,value); } + + joinPtr->marked = value; + joinPtr = joinPtr->lastLevel; + } + } + +/*****************************************/ +/* GetAlphaMemory: Retrieves the list of */ +/* matches from an alpha memory. */ +/*****************************************/ +globle struct partialMatch *GetAlphaMemory( + void *theEnv, + struct patternNodeHeader *theHeader, + unsigned long hashOffset) + { + struct alphaMemoryHash *theAlphaMemory; + unsigned long hashValue; + + hashValue = AlphaMemoryHashValue(theHeader,hashOffset); + theAlphaMemory = FindAlphaMemory(theEnv,theHeader,hashValue); + + if (theAlphaMemory == NULL) + { return NULL; } + + return theAlphaMemory->alphaMemory; + } + +/*****************************************/ +/* GetLeftBetaMemory: Retrieves the list */ +/* of matches from a beta memory. */ +/*****************************************/ +globle struct partialMatch *GetLeftBetaMemory( + struct joinNode *theJoin, + unsigned long hashValue) + { + unsigned long betaLocation; + + betaLocation = hashValue % theJoin->leftMemory->size; + + return theJoin->leftMemory->beta[betaLocation]; + } + +/******************************************/ +/* GetRightBetaMemory: Retrieves the list */ +/* of matches from a beta memory. */ +/******************************************/ +globle struct partialMatch *GetRightBetaMemory( + struct joinNode *theJoin, + unsigned long hashValue) + { + unsigned long betaLocation; + + betaLocation = hashValue % theJoin->rightMemory->size; + + return theJoin->rightMemory->beta[betaLocation]; + } + +/***************************************/ +/* ReturnLeftMemory: Sets the contents */ +/* of a beta memory to NULL. */ +/***************************************/ +globle void ReturnLeftMemory( + void *theEnv, + struct joinNode *theJoin) + { + if (theJoin->leftMemory == NULL) return; + genfree(theEnv,theJoin->leftMemory->beta,sizeof(struct partialMatch *) * theJoin->leftMemory->size); + rtn_struct(theEnv,betaMemory,theJoin->leftMemory); + theJoin->leftMemory = NULL; + } + +/***************************************/ +/* ReturnRightMemory: Sets the contents */ +/* of a beta memory to NULL. */ +/***************************************/ +globle void ReturnRightMemory( + void *theEnv, + struct joinNode *theJoin) + { + if (theJoin->rightMemory == NULL) return; + genfree(theEnv,theJoin->rightMemory->beta,sizeof(struct partialMatch *) * theJoin->rightMemory->size); + genfree(theEnv,theJoin->rightMemory->last,sizeof(struct partialMatch *) * theJoin->rightMemory->size); + rtn_struct(theEnv,betaMemory,theJoin->rightMemory); + theJoin->rightMemory = NULL; + } + +/****************************************************************/ +/* DestroyBetaMemory: Destroys the contents of a beta memory in */ +/* preperation for the deallocation of a join. Destroying is */ +/* performed when the environment is being deallocated and it */ +/* is not necessary to leave the environment in a consistent */ +/* state (as it would be if just a single rule were being */ +/* deleted). */ +/****************************************************************/ +globle void DestroyBetaMemory( + void *theEnv, + struct joinNode *theJoin, + int side) + { + unsigned long i; + + if (side == LHS) + { + if (theJoin->leftMemory == NULL) return; + + for (i = 0; i < theJoin->leftMemory->size; i++) + { DestroyAlphaBetaMemory(theEnv,theJoin->leftMemory->beta[i]); } + } + else + { + if (theJoin->rightMemory == NULL) return; + + for (i = 0; i < theJoin->rightMemory->size; i++) + { DestroyAlphaBetaMemory(theEnv,theJoin->rightMemory->beta[i]); } + } + } + +/*************************************************************/ +/* FlushBetaMemory: Flushes the contents of a beta memory in */ +/* preperation for the deallocation of a join. Flushing */ +/* is performed when the partial matches in the beta */ +/* memory may still be in use because the environment will */ +/* remain active. */ +/*************************************************************/ +globle void FlushBetaMemory( + void *theEnv, + struct joinNode *theJoin, + int side) + { + unsigned long i; + + if (side == LHS) + { + if (theJoin->leftMemory == NULL) return; + + for (i = 0; i < theJoin->leftMemory->size; i++) + { FlushAlphaBetaMemory(theEnv,theJoin->leftMemory->beta[i]); } + } + else + { + if (theJoin->rightMemory == NULL) return; + + for (i = 0; i < theJoin->rightMemory->size; i++) + { FlushAlphaBetaMemory(theEnv,theJoin->rightMemory->beta[i]); } + } + } + +/*****************************************************************/ +/* BetaMemoryNotEmpty: */ +/*****************************************************************/ +globle intBool BetaMemoryNotEmpty( + struct joinNode *theJoin) + { + if (theJoin->leftMemory != NULL) + { + if (theJoin->leftMemory->count > 0) + { return(TRUE); } + } + + if (theJoin->rightMemory != NULL) + { + if (theJoin->rightMemory->count > 0) + { return(TRUE); } + } + + return(FALSE); + } + +/*********************************************/ +/* RemoveAlphaMemoryMatches: Removes matches */ +/* from an alpha memory. */ +/*********************************************/ +globle void RemoveAlphaMemoryMatches( + void *theEnv, + struct patternNodeHeader *theHeader, + struct partialMatch *theMatch, + struct alphaMatch *theAlphaMatch) + { + struct alphaMemoryHash *theAlphaMemory = NULL; + unsigned long hashValue; + + if ((theMatch->prevInMemory == NULL) || (theMatch->nextInMemory == NULL)) + { + hashValue = theAlphaMatch->bucket; + theAlphaMemory = FindAlphaMemory(theEnv,theHeader,hashValue); + } + + if (theMatch->prevInMemory != NULL) + { theMatch->prevInMemory->nextInMemory = theMatch->nextInMemory; } + else + { theAlphaMemory->alphaMemory = theMatch->nextInMemory; } + + if (theMatch->nextInMemory != NULL) + { theMatch->nextInMemory->prevInMemory = theMatch->prevInMemory; } + else + { theAlphaMemory->endOfQueue = theMatch->prevInMemory; } + + /*====================================*/ + /* Add the match to the garbage list. */ + /*====================================*/ + + theMatch->nextInMemory = EngineData(theEnv)->GarbagePartialMatches; + EngineData(theEnv)->GarbagePartialMatches = theMatch; + + if ((theAlphaMemory != NULL) && (theAlphaMemory->alphaMemory == NULL)) + { UnlinkAlphaMemory(theEnv,theHeader,theAlphaMemory); } + } + +/*****************************************************************/ +/* DestroyAlphaMemory: */ +/*****************************************************************/ +globle void DestroyAlphaMemory( + void *theEnv, + struct patternNodeHeader *theHeader, + int unlink) + { + struct alphaMemoryHash *theAlphaMemory, *tempMemory; + + theAlphaMemory = theHeader->firstHash; + + while (theAlphaMemory != NULL) + { + tempMemory = theAlphaMemory->nextHash; + DestroyAlphaBetaMemory(theEnv,theAlphaMemory->alphaMemory); + if (unlink) + { UnlinkAlphaMemoryBucketSiblings(theEnv,theAlphaMemory); } + rtn_struct(theEnv,alphaMemoryHash,theAlphaMemory); + theAlphaMemory = tempMemory; + } + + theHeader->firstHash = NULL; + theHeader->lastHash = NULL; + } + +/*****************************************************************/ +/* FlushAlphaMemory: */ +/*****************************************************************/ +globle void FlushAlphaMemory( + void *theEnv, + struct patternNodeHeader *theHeader) + { + struct alphaMemoryHash *theAlphaMemory, *tempMemory; + + theAlphaMemory = theHeader->firstHash; + + while (theAlphaMemory != NULL) + { + tempMemory = theAlphaMemory->nextHash; + FlushAlphaBetaMemory(theEnv,theAlphaMemory->alphaMemory); + UnlinkAlphaMemoryBucketSiblings(theEnv,theAlphaMemory); + rtn_struct(theEnv,alphaMemoryHash,theAlphaMemory); + theAlphaMemory = tempMemory; + } + + theHeader->firstHash = NULL; + theHeader->lastHash = NULL; + } + +/*****************************************************************/ +/* FindAlphaMemory: */ +/*****************************************************************/ +static struct alphaMemoryHash *FindAlphaMemory( + void *theEnv, + struct patternNodeHeader *theHeader, + unsigned long hashValue) + { + struct alphaMemoryHash *theAlphaMemory; + + theAlphaMemory = DefruleData(theEnv)->AlphaMemoryTable[hashValue]; + + if (theAlphaMemory != NULL) + { + while ((theAlphaMemory != NULL) && (theAlphaMemory->owner != theHeader)) + { theAlphaMemory = theAlphaMemory->next; } + } + + return theAlphaMemory; + } + +/*****************************************************************/ +/* AlphaMemoryHashValue: */ +/*****************************************************************/ +static unsigned long AlphaMemoryHashValue( + struct patternNodeHeader *theHeader, + unsigned long hashOffset) + { + unsigned long hashValue; + union + { + void *vv; + unsigned uv; + } fis; + + fis.uv = 0; + fis.vv = theHeader; + + hashValue = fis.uv + hashOffset; + hashValue = hashValue % ALPHA_MEMORY_HASH_SIZE; + + return hashValue; + } + +/*****************************************************************/ +/* UnlinkAlphaMemory: */ +/*****************************************************************/ +static void UnlinkAlphaMemory( + void *theEnv, + struct patternNodeHeader *theHeader, + struct alphaMemoryHash *theAlphaMemory) + { + /*======================*/ + /* Unlink the siblings. */ + /*======================*/ + + UnlinkAlphaMemoryBucketSiblings(theEnv,theAlphaMemory); + + /*================================*/ + /* Update firstHash and lastHash. */ + /*================================*/ + + if (theAlphaMemory == theHeader->firstHash) + { theHeader->firstHash = theAlphaMemory->nextHash; } + + if (theAlphaMemory == theHeader->lastHash) + { theHeader->lastHash = theAlphaMemory->prevHash; } + + /*===============================*/ + /* Update nextHash and prevHash. */ + /*===============================*/ + + if (theAlphaMemory->prevHash != NULL) + { theAlphaMemory->prevHash->nextHash = theAlphaMemory->nextHash; } + + if (theAlphaMemory->nextHash != NULL) + { theAlphaMemory->nextHash->prevHash = theAlphaMemory->prevHash; } + + rtn_struct(theEnv,alphaMemoryHash,theAlphaMemory); + } + +/*****************************************************************/ +/* UnlinkAlphaMemoryBucketSiblings: */ +/*****************************************************************/ +static void UnlinkAlphaMemoryBucketSiblings( + void *theEnv, + struct alphaMemoryHash *theAlphaMemory) + { + if (theAlphaMemory->prev == NULL) + { DefruleData(theEnv)->AlphaMemoryTable[theAlphaMemory->bucket] = theAlphaMemory->next; } + else + { theAlphaMemory->prev->next = theAlphaMemory->next; } + + if (theAlphaMemory->next != NULL) + { theAlphaMemory->next->prev = theAlphaMemory->prev; } + } + +/********************************************/ +/* ComputeRightHashValue: */ +/********************************************/ +unsigned long ComputeRightHashValue( + void *theEnv, + struct patternNodeHeader *theHeader) + { + struct expr *tempExpr; + unsigned long hashValue = 0; + unsigned long multiplier = 1; + union + { + void *vv; + unsigned long liv; + } fis; + + if (theHeader->rightHash == NULL) + { return hashValue; } + + for (tempExpr = theHeader->rightHash; + tempExpr != NULL; + tempExpr = tempExpr->nextArg, multiplier = multiplier * 509) + { + DATA_OBJECT theResult; + struct expr *oldArgument; + + oldArgument = EvaluationData(theEnv)->CurrentExpression; + EvaluationData(theEnv)->CurrentExpression = tempExpr; + (*EvaluationData(theEnv)->PrimitivesArray[tempExpr->type]->evaluateFunction)(theEnv,tempExpr->value,&theResult); + EvaluationData(theEnv)->CurrentExpression = oldArgument; + + switch (theResult.type) + { + case STRING: + case SYMBOL: + case INSTANCE_NAME: + hashValue += (((SYMBOL_HN *) theResult.value)->bucket * multiplier); + break; + + case INTEGER: + hashValue += (((INTEGER_HN *) theResult.value)->bucket * multiplier); + break; + + case FLOAT: + hashValue += (((FLOAT_HN *) theResult.value)->bucket * multiplier); + break; + + case FACT_ADDRESS: +#if OBJECT_SYSTEM + case INSTANCE_ADDRESS: +#endif + fis.liv = 0; + fis.vv = theResult.value; + hashValue += (unsigned long) (fis.liv * multiplier); + break; + + case EXTERNAL_ADDRESS: + fis.liv = 0; + fis.vv = ValueToExternalAddress(theResult.value); + hashValue += (unsigned long) (fis.liv * multiplier); + break; + } + } + + return hashValue; + } + +/***********************************************************/ +/* ResizeBetaMemory: */ +/***********************************************************/ +globle void ResizeBetaMemory( + void *theEnv, + struct betaMemory *theMemory) + { + struct partialMatch **oldArray, **lastAdd, *thePM, *nextPM; + unsigned long i, oldSize, betaLocation; + + oldSize = theMemory->size; + oldArray = theMemory->beta; + + theMemory->size = oldSize * 11; + theMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * theMemory->size); + + lastAdd = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * theMemory->size); + memset(theMemory->beta,0,sizeof(struct partialMatch *) * theMemory->size); + memset(lastAdd,0,sizeof(struct partialMatch *) * theMemory->size); + + for (i = 0; i < oldSize; i++) + { + thePM = oldArray[i]; + while (thePM != NULL) + { + nextPM = thePM->nextInMemory; + + thePM->nextInMemory = NULL; + + betaLocation = thePM->hashValue % theMemory->size; + thePM->prevInMemory = lastAdd[betaLocation]; + + if (lastAdd[betaLocation] != NULL) + { lastAdd[betaLocation]->nextInMemory = thePM; } + else + { theMemory->beta[betaLocation] = thePM; } + + lastAdd[betaLocation] = thePM; + + thePM = nextPM; + } + } + + if (theMemory->last != NULL) + { + genfree(theEnv,theMemory->last,sizeof(struct partialMatch *) * oldSize); + theMemory->last = lastAdd; + } + else + { genfree(theEnv,lastAdd,sizeof(struct partialMatch *) * theMemory->size); } + + genfree(theEnv,oldArray,sizeof(struct partialMatch *) * oldSize); + } + +/***********************************************************/ +/* ResetBetaMemory: */ +/***********************************************************/ +static void ResetBetaMemory( + void *theEnv, + struct betaMemory *theMemory) + { + struct partialMatch **oldArray, **lastAdd; + unsigned long oldSize; + + if ((theMemory->size == 1) || + (theMemory->size == INITIAL_BETA_HASH_SIZE)) + { return; } + + oldSize = theMemory->size; + oldArray = theMemory->beta; + + theMemory->size = INITIAL_BETA_HASH_SIZE; + theMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * theMemory->size); + memset(theMemory->beta,0,sizeof(struct partialMatch *) * theMemory->size); + genfree(theEnv,oldArray,sizeof(struct partialMatch *) * oldSize); + + if (theMemory->last != NULL) + { + lastAdd = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * theMemory->size); + memset(lastAdd,0,sizeof(struct partialMatch *) * theMemory->size); + genfree(theEnv,theMemory->last,sizeof(struct partialMatch *) * oldSize); + theMemory->last = lastAdd; + } + } + +/********************/ +/* PrintBetaMemory: */ +/********************/ +globle unsigned long PrintBetaMemory( + void *theEnv, + const char *logName, + struct betaMemory *theMemory, + int indentFirst, + const char *indentString, + int output) + { + struct partialMatch *listOfMatches; + unsigned long b, count = 0; + + if (GetHaltExecution(theEnv) == TRUE) + { return count; } + + for (b = 0; b < theMemory->size; b++) + { + listOfMatches = theMemory->beta[b]; + + while (listOfMatches != NULL) + { + /*=========================================*/ + /* Check to see if the user is attempting */ + /* to stop the display of partial matches. */ + /*=========================================*/ + + if (GetHaltExecution(theEnv) == TRUE) + { return count; } + + /*=========================================================*/ + /* The first partial match may have already been indented. */ + /* Subsequent partial matches will always be indented with */ + /* the indentation string. */ + /*=========================================================*/ + + if (output == VERBOSE) + { + if (indentFirst) + { EnvPrintRouter(theEnv,logName,indentString); } + else + { indentFirst = TRUE; } + } + + /*==========================*/ + /* Print the partial match. */ + /*==========================*/ + + if (output == VERBOSE) + { + PrintPartialMatch(theEnv,logName,listOfMatches); + EnvPrintRouter(theEnv,logName,"\n"); + } + + count++; + + /*============================*/ + /* Move on to the next match. */ + /*============================*/ + + listOfMatches = listOfMatches->nextInMemory; + } + } + + return count; + } + #if (CONSTRUCT_COMPILER || BLOAD_AND_BSAVE) && (! RUN_TIME) /*************************************************************/ @@ -550,18 +1605,36 @@ globle void TagRuleNetwork( void *theEnv, long int *moduleCount, long int *ruleCount, - long int *joinCount) + long int *joinCount, + long int *linkCount) { struct defmodule *modulePtr; - struct defrule *rulePtr; - struct joinNode *joinPtr; + struct defrule *rulePtr, *disjunctPtr; + struct joinLink *theLink; *moduleCount = 0; *ruleCount = 0; *joinCount = 0; + *linkCount = 0; MarkRuleNetwork(theEnv,0); + for (theLink = DefruleData(theEnv)->LeftPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { + theLink->bsaveID = *linkCount; + (*linkCount)++; + } + + for (theLink = DefruleData(theEnv)->RightPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { + theLink->bsaveID = *linkCount; + (*linkCount)++; + } + /*===========================*/ /* Loop through each module. */ /*===========================*/ @@ -581,28 +1654,52 @@ globle void TagRuleNetwork( while (rulePtr != NULL) { - rulePtr->header.bsaveID = *ruleCount; - (*ruleCount)++; - - /*=========================*/ - /* Loop through each join. */ - /*=========================*/ - - for (joinPtr = rulePtr->lastJoin; - joinPtr != NULL; - joinPtr = GetPreviousJoin(joinPtr)) + /*=============================*/ + /* Loop through each disjunct. */ + /*=============================*/ + + for (disjunctPtr = rulePtr; disjunctPtr != NULL; disjunctPtr = disjunctPtr->disjunct) { - if (joinPtr->marked == 0) - { - joinPtr->marked = 1; - joinPtr->bsaveID = *joinCount; - (*joinCount)++; - } + disjunctPtr->header.bsaveID = *ruleCount; + (*ruleCount)++; + TagNetworkTraverseJoins(theEnv,joinCount,linkCount,disjunctPtr->lastJoin); } + + rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); + } + } + } - if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct; - else rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); +/*******************************************************************/ +/* TagNetworkTraverseJoins: Traverses the join network for a rule. */ +/*******************************************************************/ +static void TagNetworkTraverseJoins( + void *theEnv, + long int *joinCount, + long int *linkCount, + struct joinNode *joinPtr) + { + struct joinLink *theLink; + for (; + joinPtr != NULL; + joinPtr = joinPtr->lastLevel) + { + if (joinPtr->marked == 0) + { + joinPtr->marked = 1; + joinPtr->bsaveID = *joinCount; + (*joinCount)++; + for (theLink = joinPtr->nextLinks; + theLink != NULL; + theLink = theLink->next) + { + theLink->bsaveID = *linkCount; + (*linkCount)++; + } } + + if (joinPtr->joinFromTheRight) + { TagNetworkTraverseJoins(theEnv,joinCount,linkCount,(struct joinNode *) joinPtr->rightSideEntryStructure); } } } diff --git a/src/reteutil.h b/src/reteutil.h index 56198aa..866e3d7 100644 --- a/src/reteutil.h +++ b/src/reteutil.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RETE UTILITY HEADER FILE */ /*******************************************************/ @@ -17,9 +17,31 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Rule with exists CE has incorrect activation. */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for join network changes. */ +/* */ +/* Support for using an asterick (*) to indicate */ +/* that existential patterns are matched. */ +/* */ +/* Support for partial match changes. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_reteutil @@ -45,27 +67,48 @@ #define LOCALE extern #endif - LOCALE void PrintPartialMatch(void *,char *,struct partialMatch *); - LOCALE struct partialMatch *CopyPartialMatch(void *,struct partialMatch *,int,int); - LOCALE struct partialMatch *MergePartialMatches(void *,struct partialMatch *,struct partialMatch *,int,int); - LOCALE struct partialMatch *AddSingleMatch(void *,struct partialMatch *,struct alphaMatch *,int,int); - LOCALE struct partialMatch *NewPseudoFactPartialMatch(void *); +#define NETWORK_ASSERT 0 +#define NETWORK_RETRACT 1 + + LOCALE void PrintPartialMatch(void *,const char *,struct partialMatch *); + LOCALE struct partialMatch *CopyPartialMatch(void *,struct partialMatch *); + LOCALE struct partialMatch *MergePartialMatches(void *,struct partialMatch *,struct partialMatch *); LOCALE long int IncrementPseudoFactIndex(void); + LOCALE struct partialMatch *GetAlphaMemory(void *,struct patternNodeHeader *,unsigned long); + LOCALE struct partialMatch *GetLeftBetaMemory(struct joinNode *,unsigned long); + LOCALE struct partialMatch *GetRightBetaMemory(struct joinNode *,unsigned long); + LOCALE void ReturnLeftMemory(void *,struct joinNode *); + LOCALE void ReturnRightMemory(void *,struct joinNode *); + LOCALE void DestroyBetaMemory(void *,struct joinNode *,int); + LOCALE void FlushBetaMemory(void *,struct joinNode *,int); + LOCALE intBool BetaMemoryNotEmpty(struct joinNode *); + LOCALE void RemoveAlphaMemoryMatches(void *,struct patternNodeHeader *,struct partialMatch *, + struct alphaMatch *); + LOCALE void DestroyAlphaMemory(void *,struct patternNodeHeader *,int); + LOCALE void FlushAlphaMemory(void *,struct patternNodeHeader *); LOCALE void FlushAlphaBetaMemory(void *,struct partialMatch *); LOCALE void DestroyAlphaBetaMemory(void *,struct partialMatch *); LOCALE int GetPatternNumberFromJoin(struct joinNode *); - LOCALE void PrimeJoin(struct joinNode *); LOCALE struct multifieldMarker *CopyMultifieldMarkers(void *,struct multifieldMarker *); LOCALE struct partialMatch *CreateAlphaMatch(void *,void *,struct multifieldMarker *, - struct patternNodeHeader *); - LOCALE void TraceErrorToRule(void *,struct joinNode *,char *); + struct patternNodeHeader *,unsigned long); + LOCALE void TraceErrorToRule(void *,struct joinNode *,const char *); LOCALE void InitializePatternHeader(void *,struct patternNodeHeader *); LOCALE void MarkRuleNetwork(void *,int); - LOCALE void TagRuleNetwork(void *,long *,long *,long *); + LOCALE void TagRuleNetwork(void *,long *,long *,long *,long *); LOCALE int FindEntityInPartialMatch(struct patternEntity *,struct partialMatch *); + LOCALE unsigned long ComputeRightHashValue(void *,struct patternNodeHeader *); + LOCALE void UpdateBetaPMLinks(void *,struct partialMatch *,struct partialMatch *,struct partialMatch *, + struct joinNode *,unsigned long,int); + LOCALE void UnlinkBetaPMFromNodeAndLineage(void *,struct joinNode *,struct partialMatch *,int); + LOCALE void UnlinkNonLeftLineage(void *,struct joinNode *,struct partialMatch *,int); + LOCALE struct partialMatch *CreateEmptyPartialMatch(void *); + LOCALE void MarkRuleJoins(struct joinNode *,int); + LOCALE void AddBlockedLink(struct partialMatch *,struct partialMatch *); + LOCALE void RemoveBlockedLink(struct partialMatch *); + LOCALE unsigned long PrintBetaMemory(void *,const char *,struct betaMemory *,int,const char *,int); -#endif - +#endif /* _H_reteutil */ diff --git a/src/retract.c b/src/retract.c index 946cac3..e30e2d9 100644 --- a/src/retract.c +++ b/src/retract.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RETRACT MODULE */ /*******************************************************/ @@ -25,6 +25,13 @@ /* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ /*************************************************************/ #define _RETRACT_SOURCE_ @@ -57,353 +64,277 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct partialMatch *RemovePartialMatches(void *,struct alphaMatch *, - struct partialMatch *, - struct partialMatch **,int, - struct partialMatch **); - static void DeletePartialMatches(void *,struct partialMatch *,int); static void ReturnMarkers(void *,struct multifieldMarker *); - static void DriveRetractions(void *); - static intBool FindNextConflictingAlphaMatch(void *,struct partialMatch *, - struct partialMatch *, - struct joinNode *); + static intBool FindNextConflictingMatch(void *,struct partialMatch *, + struct partialMatch *, + struct joinNode *,struct partialMatch *,int); static intBool PartialMatchDefunct(void *,struct partialMatch *); + static void NegEntryRetractAlpha(void *,struct partialMatch *,int); + static void NegEntryRetractBeta(void *,struct joinNode *,struct partialMatch *, + struct partialMatch *,int); /************************************************************/ /* NetworkRetract: Retracts a data entity (such as a fact */ /* or instance) from the pattern and join networks given */ /* a pointer to the list of patterns which the data */ -/* entity matched. The data entity is first removed from */ -/* the join network through patterns not directly */ -/* enclosed within a not CE and then through patterns */ -/* enclosed by a not CE. Any new partial matches created */ -/* by the removal are then filtered through the join */ -/* network. This ordering prevents partial matches from */ -/* being generated that contain the data entity which was */ -/* removed. */ +/* entity matched. */ /************************************************************/ globle void NetworkRetract( void *theEnv, struct patternMatch *listOfMatchedPatterns) { - struct patternMatch *tempMatch; - struct partialMatch *deletedMatches, *theLast; - struct joinNode *joinPtr; - - /*===============================*/ - /* Remember the beginning of the */ - /* list of matched patterns. */ - /*===============================*/ + struct patternMatch *tempMatch, *nextMatch; tempMatch = listOfMatchedPatterns; - - /*============================================*/ - /* Remove the data entity from all joins that */ - /* aren't directly enclosed by a not CE. */ - /*============================================*/ - - for (; - listOfMatchedPatterns != NULL; - listOfMatchedPatterns = listOfMatchedPatterns->next) + while (tempMatch != NULL) { - /*====================================*/ - /* Loop through the list of all joins */ - /* attached to this pattern. */ - /*====================================*/ + nextMatch = tempMatch->next; - for (joinPtr = listOfMatchedPatterns->matchingPattern->entryJoin; - joinPtr != NULL; - joinPtr = joinPtr->rightMatchNode) - { - if (joinPtr->patternIsNegated == FALSE) - { PosEntryRetract(theEnv,joinPtr, - listOfMatchedPatterns->theMatch->binds[0].gm.theMatch, - listOfMatchedPatterns->theMatch, - (int) joinPtr->depth - 1,listOfMatchedPatterns->theMatch->binds[0].gm.theMatch->matchingItem); } - } - } - - /*============================================*/ - /* Remove the data entity from all joins that */ - /* are directly enclosed by a not CE. */ - /*============================================*/ - - listOfMatchedPatterns = tempMatch; - while (listOfMatchedPatterns != NULL) - { - /*====================================*/ - /* Loop through the list of all joins */ - /* attached to this pattern. */ - /*====================================*/ + if (tempMatch->theMatch->children != NULL) + { PosEntryRetractAlpha(theEnv,tempMatch->theMatch,NETWORK_RETRACT); } - for (joinPtr = listOfMatchedPatterns->matchingPattern->entryJoin; - joinPtr != NULL; - joinPtr = joinPtr->rightMatchNode) - { - if (joinPtr->patternIsNegated == TRUE) - { - if (joinPtr->firstJoin == TRUE) - { - SystemError(theEnv,"RETRACT",3); - EnvExitRouter(theEnv,EXIT_FAILURE); - } - else - { - NegEntryRetract(theEnv,joinPtr,listOfMatchedPatterns->theMatch,listOfMatchedPatterns->theMatch->binds[0].gm.theMatch->matchingItem); - } - } - } + if (tempMatch->theMatch->blockList != NULL) + { NegEntryRetractAlpha(theEnv,tempMatch->theMatch,NETWORK_RETRACT); } /*===================================================*/ /* Remove from the alpha memory of the pattern node. */ /*===================================================*/ - theLast = NULL; - listOfMatchedPatterns->matchingPattern->alphaMemory = - RemovePartialMatches(theEnv,listOfMatchedPatterns->theMatch->binds[0].gm.theMatch, - listOfMatchedPatterns->matchingPattern->alphaMemory, - &deletedMatches,0,&theLast); - listOfMatchedPatterns->matchingPattern->endOfQueue = theLast; + RemoveAlphaMemoryMatches(theEnv,tempMatch->matchingPattern, + tempMatch->theMatch, + tempMatch->theMatch->binds[0].gm.theMatch); - DeletePartialMatches(theEnv,deletedMatches,0); + rtn_struct(theEnv,patternMatch,tempMatch); - tempMatch = listOfMatchedPatterns->next; - rtn_struct(theEnv,patternMatch,listOfMatchedPatterns); - listOfMatchedPatterns = tempMatch; + tempMatch = nextMatch; } - - /*=========================================*/ - /* Filter new partial matches generated by */ - /* retraction through the join network. */ - /*=========================================*/ - - DriveRetractions(theEnv); } /***************************************************************/ -/* PosEntryRetract: Handles retract for a join of a rule with */ -/* a positive pattern when the retraction is starting from */ -/* the RHS of that join (empty or positive LHS entry, */ -/* positive RHS entry), or the LHS of that join (positive */ -/* LHS entry, negative or positive RHS entry). */ +/* PosEntryRetractAlpha: */ /***************************************************************/ -globle void PosEntryRetract( +globle void PosEntryRetractAlpha( void *theEnv, - struct joinNode *join, - struct alphaMatch *theAlphaNode, - struct partialMatch *theMatch, - int position, - void *duringRetract) + struct partialMatch *alphaMatch, + int operation) { - struct partialMatch *deletedMatches; + struct partialMatch *betaMatch, *tempMatch; struct joinNode *joinPtr; - struct partialMatch *theLast; - while (join != NULL) + betaMatch = alphaMatch->children; + while (betaMatch != NULL) { - /*=========================================*/ - /* Remove the bindings from this join that */ - /* contain the fact to be retracted. */ - /*=========================================*/ + joinPtr = (struct joinNode *) betaMatch->owner; - if (join->beta == NULL) return; /* optimize */ + if (betaMatch->children != NULL) + { PosEntryRetractBeta(theEnv,betaMatch,betaMatch->children,operation); } - join->beta = RemovePartialMatches(theEnv,theAlphaNode,join->beta,&deletedMatches, - position,&theLast); + if (betaMatch->rhsMemory) + { NegEntryRetractAlpha(theEnv,betaMatch,operation); } - /*===================================================*/ - /* If no facts were deleted at this join, then there */ - /* is no need to check joins at a lower level. */ - /*===================================================*/ + /* Remove the beta match. */ + + if ((joinPtr->ruleToActivate != NULL) ? + (betaMatch->marker != NULL) : FALSE) + { RemoveActivation(theEnv,(struct activation *) betaMatch->marker,TRUE,TRUE); } + + tempMatch = betaMatch->nextRightChild; - if (deletedMatches == NULL) return; + if (betaMatch->rhsMemory) + { UnlinkBetaPMFromNodeAndLineage(theEnv,joinPtr,betaMatch,RHS); } + else + { UnlinkBetaPMFromNodeAndLineage(theEnv,joinPtr,betaMatch,LHS); } - /*==================================================*/ - /* If there is more than one join below this join, */ - /* then recursively remove fact bindings from all */ - /* but one of the lower joins. Remove the bindings */ - /* from the other join through this loop. */ - /*==================================================*/ + DeletePartialMatches(theEnv,betaMatch); - joinPtr = join->nextLevel; - if (joinPtr == NULL) + betaMatch = tempMatch; + } + } + +/***************************************************************/ +/* NegEntryRetractAlpha: */ +/***************************************************************/ +static void NegEntryRetractAlpha( + void *theEnv, + struct partialMatch *alphaMatch, + int operation) + { + struct partialMatch *betaMatch; + struct joinNode *joinPtr; + + betaMatch = alphaMatch->blockList; + while (betaMatch != NULL) + { + joinPtr = (struct joinNode *) betaMatch->owner; + + if ((! joinPtr->patternIsNegated) && + (! joinPtr->patternIsExists) && + (! joinPtr->joinFromTheRight)) { - DeletePartialMatches(theEnv,deletedMatches,1); - return; + SystemError(theEnv,"RETRACT",117); + betaMatch = betaMatch->nextBlocked; + continue; } - if (((struct joinNode *) (joinPtr->rightSideEntryStructure)) == join) - { - theMatch = deletedMatches; - while (theMatch != NULL) - { - NegEntryRetract(theEnv,joinPtr,theMatch,duringRetract); - theMatch = theMatch->next; - } + NegEntryRetractBeta(theEnv,joinPtr,alphaMatch,betaMatch,operation); + betaMatch = alphaMatch->blockList; + } + } - DeletePartialMatches(theEnv,deletedMatches,1); - return; - } +/***************************************************************/ +/* NegEntryRetractBeta: */ +/***************************************************************/ +static void NegEntryRetractBeta( + void *theEnv, + struct joinNode *joinPtr, + struct partialMatch *alphaMatch, + struct partialMatch *betaMatch, + int operation) + { + /*======================================================*/ + /* Try to find another RHS partial match which prevents */ + /* the LHS partial match from being satisifed. */ + /*======================================================*/ - DeletePartialMatches(theEnv,deletedMatches,1); - while (joinPtr->rightDriveNode != NULL) + RemoveBlockedLink(betaMatch); + + if (FindNextConflictingMatch(theEnv,betaMatch,alphaMatch->nextInMemory,joinPtr,alphaMatch,operation)) + { return; } + else if (joinPtr->patternIsExists) + { + if (betaMatch->children != NULL) + { PosEntryRetractBeta(theEnv,betaMatch,betaMatch->children,operation); } + return; + } + else if (joinPtr->firstJoin && (joinPtr->patternIsNegated || joinPtr->joinFromTheRight) && (! joinPtr->patternIsExists)) + { + if (joinPtr->secondaryNetworkTest != NULL) { - PosEntryRetract(theEnv,joinPtr,theAlphaNode,theMatch,position,duringRetract); - joinPtr = joinPtr->rightDriveNode; + if (EvaluateSecondaryNetworkTest(theEnv,betaMatch,joinPtr) == FALSE) + { return; } } - join = joinPtr; + EPMDrive(theEnv,betaMatch,joinPtr,operation); + + return; + } + + if (joinPtr->secondaryNetworkTest != NULL) + { + if (EvaluateSecondaryNetworkTest(theEnv,betaMatch,joinPtr) == FALSE) + { return; } } + + /*=========================================================*/ + /* If the LHS partial match now has no RHS partial matches */ + /* that conflict with it, then it satisfies the conditions */ + /* of the RHS not CE. Create a partial match and send it */ + /* to the joins below. */ + /*=========================================================*/ + + /*===============================*/ + /* Create the new partial match. */ + /*===============================*/ + + if ((operation == NETWORK_RETRACT) && PartialMatchWillBeDeleted(theEnv,betaMatch)) + { return; } + + PPDrive(theEnv,betaMatch,NULL,joinPtr,operation); } -/*****************************************************************/ -/* NegEntryRetract: Handles retract for a join of a rule with a */ -/* not CE when the retraction is process from the RHS of that */ -/* join. */ -/*****************************************************************/ -void NegEntryRetract( +/***************************************************************/ +/* PosEntryRetractBeta: */ +/***************************************************************/ +globle void PosEntryRetractBeta( void *theEnv, - struct joinNode *theJoin, - struct partialMatch *theMatch, - void *duringRetract) + struct partialMatch *parentMatch, + struct partialMatch *betaMatch, + int operation) { - struct partialMatch *theLHS; - int result; - struct rdriveinfo *tempDR; - struct alphaMatch *tempAlpha; - struct joinNode *listOfJoins; - - /*===============================================*/ - /* Loop through all LHS partial matches checking */ - /* for sets that satisfied the join expression. */ - /*===============================================*/ - - for (theLHS = theJoin->beta; theLHS != NULL; theLHS = theLHS->next) + struct partialMatch *tempMatch; + + while (betaMatch != NULL) { - /*===========================================================*/ - /* Don't bother checking partial matches that are satisfied. */ - /* We're looking for joins from which the removal of a */ - /* partial match would satisfy the join. */ - /*===========================================================*/ - - if (theLHS->counterf == FALSE) continue; - - /*==================================================*/ - /* If the partial match being removed isn't the one */ - /* preventing the LHS partial match from being */ - /* satisifed, then don't bother processing it. */ - /*==================================================*/ - - if (theLHS->binds[theLHS->bcount - 1].gm.theValue != (void *) theMatch) continue; - - /*======================================================*/ - /* Try to find another RHS partial match which prevents */ - /* the LHS partial match from being satisifed. */ - /*======================================================*/ - - theLHS->binds[theLHS->bcount - 1].gm.theValue = NULL; - result = FindNextConflictingAlphaMatch(theEnv,theLHS,theMatch->next,theJoin); - - /*=========================================================*/ - /* If the LHS partial match now has no RHS partial matches */ - /* that conflict with it, then it satisfies the conditions */ - /* of the RHS not CE. Create a partial match and send it */ - /* to the joins below. */ - /*=========================================================*/ - - if (result == FALSE) + if (betaMatch->children != NULL) { - /*===============================*/ - /* Create the new partial match. */ - /*===============================*/ - - theLHS->counterf = FALSE; - tempAlpha = get_struct(theEnv,alphaMatch); - tempAlpha->next = NULL; - tempAlpha->matchingItem = NULL; - tempAlpha->markers = NULL; - theLHS->binds[theLHS->bcount - 1].gm.theMatch = tempAlpha; - - /*==============================================*/ - /* If partial matches from this join correspond */ - /* to a rule activation, then add an activation */ - /* to the agenda. */ - /*==============================================*/ - - if (theJoin->ruleToActivate != NULL) - { AddActivation(theEnv,theJoin->ruleToActivate,theLHS); } - - /*=======================================================*/ - /* Send the partial match to the list of joins following */ - /* this join. If we're in the middle of a retract, add */ - /* the partial match to the list of join activities that */ - /* need to be processed later. If we're doing an assert, */ - /* then the join activity can be processed immediately. */ - /*=======================================================*/ - - listOfJoins = theJoin->nextLevel; - if (listOfJoins != NULL) - { - if (((struct joinNode *) (listOfJoins->rightSideEntryStructure)) == theJoin) - { NetworkAssert(theEnv,theLHS,listOfJoins,RHS); } - else - { - if (duringRetract != NULL) - { - if (FindEntityInPartialMatch((struct patternEntity *) duringRetract,theLHS) == FALSE) - { - tempDR = get_struct(theEnv,rdriveinfo); - tempDR->link = theLHS; - tempDR->jlist = theJoin->nextLevel; - tempDR->next = EngineData(theEnv)->DriveRetractionList; - EngineData(theEnv)->DriveRetractionList = tempDR; - } - } - else while (listOfJoins != NULL) - { - NetworkAssert(theEnv,theLHS,listOfJoins,LHS); - listOfJoins = listOfJoins->rightDriveNode; - } - } - } + betaMatch = betaMatch->children; + continue; } + + if (betaMatch->nextLeftChild != NULL) + { tempMatch = betaMatch->nextLeftChild; } + else + { + tempMatch = betaMatch->leftParent; + betaMatch->leftParent->children = NULL; + } + + if (betaMatch->blockList != NULL) + { NegEntryRetractAlpha(theEnv,betaMatch,operation); } + else if ((((struct joinNode *) betaMatch->owner)->ruleToActivate != NULL) ? + (betaMatch->marker != NULL) : FALSE) + { RemoveActivation(theEnv,(struct activation *) betaMatch->marker,TRUE,TRUE); } + + if (betaMatch->rhsMemory) + { UnlinkNonLeftLineage(theEnv,(struct joinNode *) betaMatch->owner,betaMatch,RHS); } + else + { UnlinkNonLeftLineage(theEnv,(struct joinNode *) betaMatch->owner,betaMatch,LHS); } + + if (betaMatch->dependents != NULL) RemoveLogicalSupport(theEnv,betaMatch); + ReturnPartialMatch(theEnv,betaMatch); + + if (tempMatch == parentMatch) return; + betaMatch = tempMatch; } } -/**************************************************************/ -/* FindNextConflictingAlphaMatch: Finds the next conflicting */ -/* partial match in the alpha memory of a join (or the beta */ -/* memory of a join from the right) that prevents a partial */ -/* match in the beta memory of the join from being */ -/* satisfied. */ -/**************************************************************/ -static intBool FindNextConflictingAlphaMatch( +/******************************************************************/ +/* FindNextConflictingMatch: Finds the next conflicting partial */ +/* match in the right memory of a join that prevents a partial */ +/* match in the beta memory of the join from being satisfied. */ +/******************************************************************/ +static intBool FindNextConflictingMatch( void *theEnv, struct partialMatch *theBind, struct partialMatch *possibleConflicts, - struct joinNode *theJoin) + struct joinNode *theJoin, + struct partialMatch *skipMatch, + int operation) { - int i, result; - - /*=====================================================*/ - /* If we're dealing with a join from the right, then */ - /* we need to check the entire beta memory of the join */ - /* from the right (a join doesn't have an end of queue */ - /* pointer like a pattern data structure has). */ - /*=====================================================*/ - - if (theJoin->joinFromTheRight) - { possibleConflicts = ((struct joinNode *) theJoin->rightSideEntryStructure)->beta; } + int result, restore = FALSE; + struct partialMatch *oldLHSBinds = NULL; + struct partialMatch *oldRHSBinds = NULL; + struct joinNode *oldJoin = NULL; /*====================================*/ /* Check each of the possible partial */ /* matches which could conflict. */ /*====================================*/ +#if DEVELOPER + if (possibleConflicts != NULL) + { EngineData(theEnv)->leftToRightLoops++; } +#endif + /*====================================*/ + /* Set up the evaluation environment. */ + /*====================================*/ + + if (possibleConflicts != NULL) + { + oldLHSBinds = EngineData(theEnv)->GlobalLHSBinds; + oldRHSBinds = EngineData(theEnv)->GlobalRHSBinds; + oldJoin = EngineData(theEnv)->GlobalJoin; + EngineData(theEnv)->GlobalLHSBinds = theBind; + EngineData(theEnv)->GlobalJoin = theJoin; + restore = TRUE; + } + for (; possibleConflicts != NULL; - possibleConflicts = possibleConflicts->next) + possibleConflicts = possibleConflicts->nextInMemory) { + theJoin->memoryCompares++; + /*=====================================*/ /* Initially indicate that the partial */ /* match doesn't conflict. */ @@ -411,20 +342,12 @@ static intBool FindNextConflictingAlphaMatch( result = FALSE; - /*====================================================*/ - /* A partial match with the counterf flag set is not */ - /* yet a "real" partial match, so ignore it. When the */ - /* counterf flag is set that means that the partial */ - /* match is associated with a not CE that has a data */ - /* entity preventing it from being satsified. */ - /*====================================================*/ - - if (possibleConflicts->counterf) + if (skipMatch == possibleConflicts) { /* Do Nothing */ } /*======================================================*/ /* 6.05 Bug Fix. It is possible that a pattern entity */ - /* (e.g., instance) in a partial match is 'out of date' */ + /* (e.g. instance) in a partial match is 'out of date' */ /* with respect to the lazy evaluation scheme use by */ /* negated patterns. In other words, the object may */ /* have changed since it was last pushed through the */ @@ -435,34 +358,16 @@ static intBool FindNextConflictingAlphaMatch( else if (PartialMatchDefunct(theEnv,possibleConflicts)) { /* Do Nothing */ } - /*==================================================*/ - /* If the join doesn't have a network expression to */ - /* be evaluated, then partial match conflicts. If */ - /* the partial match is retrieved from a join from */ - /* the right, the RHS partial match must correspond */ - /* to the partial match in the beta memory of the */ - /* join being examined (in a join associated with a */ - /* not CE, each partial match in the beta memory of */ - /* the join corresponds uniquely to a partial match */ - /* in either the alpha memory from the RHS or in */ - /* the beta memory of a join from the right). */ - /*==================================================*/ + else if ((operation == NETWORK_RETRACT) && PartialMatchWillBeDeleted(theEnv,possibleConflicts)) + { /* Do Nothing */ } + + /*================================================*/ + /* If the join doesn't have a network expression */ + /* to be evaluated, then partial match conflicts. */ + /*================================================*/ else if (theJoin->networkTest == NULL) - { - result = TRUE; - if (theJoin->joinFromTheRight) - { - for (i = 0; i < (int) (theBind->bcount - 1); i++) - { - if (possibleConflicts->binds[i].gm.theMatch != theBind->binds[i].gm.theMatch) - { - result = FALSE; - break; - } - } - } - } + { result = TRUE; } /*=================================================*/ /* Otherwise, if the join has a network expression */ @@ -471,13 +376,26 @@ static intBool FindNextConflictingAlphaMatch( else { - result = EvaluateJoinExpression(theEnv,theJoin->networkTest,theBind, - possibleConflicts,theJoin); +#if DEVELOPER + if (theJoin->networkTest) + { + EngineData(theEnv)->leftToRightComparisons++; + EngineData(theEnv)->findNextConflictingComparisons++; + } +#endif + EngineData(theEnv)->GlobalRHSBinds = possibleConflicts; + + result = EvaluateJoinExpression(theEnv,theJoin->networkTest,theJoin); if (EvaluationData(theEnv)->EvaluationError) { result = TRUE; EvaluationData(theEnv)->EvaluationError = FALSE; } + +#if DEVELOPER + if (result != FALSE) + { EngineData(theEnv)->leftToRightSucceeds++; } +#endif } /*==============================================*/ @@ -490,11 +408,21 @@ static intBool FindNextConflictingAlphaMatch( if (result != FALSE) { - theBind->binds[theBind->bcount - 1].gm.theValue = (void *) possibleConflicts; + AddBlockedLink(theBind,possibleConflicts); + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; return(TRUE); } } + if (restore) + { + EngineData(theEnv)->GlobalLHSBinds = oldLHSBinds; + EngineData(theEnv)->GlobalRHSBinds = oldRHSBinds; + EngineData(theEnv)->GlobalJoin = oldJoin; + } + /*========================*/ /* No conflict was found. */ /*========================*/ @@ -512,11 +440,12 @@ static intBool PartialMatchDefunct( void *theEnv, struct partialMatch *thePM) { - register unsigned i; + register unsigned short i; register struct patternEntity * thePE; for (i = 0 ; i < thePM->bcount ; i++) { + if (thePM->binds[i].gm.theMatch == NULL) continue; thePE = thePM->binds[i].gm.theMatch->matchingItem; if (thePE && thePE->theInfo->synchronized && !(*thePE->theInfo->synchronized)(theEnv,thePE)) @@ -525,171 +454,42 @@ static intBool PartialMatchDefunct( return(FALSE); } -/*************************************************************/ -/* RemovePartialMatches: Searches through a list of partial */ -/* matches and removes any partial match that contains the */ -/* specified data entity. */ -/*************************************************************/ -static struct partialMatch *RemovePartialMatches( +/*****************************************************************/ +/* PartialMatchWillBeDeleted: Determines if any pattern entities */ +/* contained within the partial match were deleted as part of */ +/* a retraction/deletion. When rules have multiple patterns */ +/* that can be matched by the same fact it's possible that a */ +/* partial match encountered in the join network has not yet */ +/* deleted and so should not be considered as valid. */ +/*****************************************************************/ +intBool PartialMatchWillBeDeleted( void *theEnv, - struct alphaMatch *theAlphaNode, - struct partialMatch *listOfPMs, - struct partialMatch **deleteHead, - int position, - struct partialMatch **returnLast) + struct partialMatch *thePM) { - struct partialMatch *head, *lastPM, *nextPM; - struct partialMatch *lastDelete = NULL; - - /*====================================================*/ - /* Initialize pointers used for creating the new list */ - /* of partial matches and the list of partial matches */ - /* to be deleted. */ - /*====================================================*/ - - head = listOfPMs; - lastPM = listOfPMs; - *deleteHead = NULL; - - /*==========================================*/ - /* Loop through each of the partial matches */ - /* and determine if it needs to be deleted. */ - /*==========================================*/ - - while (listOfPMs != NULL) - { - if ((listOfPMs->counterf == TRUE) && (position == ((int) (listOfPMs->bcount - 1)))) - { - lastPM = listOfPMs; - listOfPMs = listOfPMs->next; - } - - /*=====================================================*/ - /* Otherwise, if the specified position in the partial */ - /* match contains the specified data entity, then */ - /* remove the partial match from the list and add it */ - /* to a deletion list. */ - /*=====================================================*/ - - else if (listOfPMs->binds[position].gm.theMatch == theAlphaNode) - { - /*===================================================*/ - /* If the partial match has an activation associated */ - /* with it, then return the activation. */ - /*===================================================*/ - - if ((listOfPMs->activationf) ? - (listOfPMs->binds[listOfPMs->bcount].gm.theValue != NULL) : FALSE) - { RemoveActivation(theEnv,(struct activation *) listOfPMs->binds[listOfPMs->bcount].gm.theValue,TRUE,TRUE); } - - /*==================================================*/ - /* If the partial match is at the head of the list */ - /* of matches, then use the following deletion code */ - /* for the head of the list. */ - /*==================================================*/ - - if (listOfPMs == head) - { - /*===================================*/ - /* Remember the new beginning of the */ - /* new list of partial matches. */ - /*===================================*/ - - nextPM = listOfPMs->next; - - /*=============================================*/ - /* Add the partial match to the deletion list. */ - /*=============================================*/ - - if (*deleteHead == NULL) - { *deleteHead = listOfPMs; } - else - { lastDelete->next = listOfPMs; } - - listOfPMs->next = NULL; - lastDelete = listOfPMs; - - /*================================================*/ - /* Update the head and tail pointers for the new */ - /* list of partial matches as well as the pointer */ - /* to the next partial match to be examined. */ - /*================================================*/ - - listOfPMs = nextPM; - head = listOfPMs; - lastPM = head; - } - - /*======================================*/ - /* Otherwise, use the following code to */ - /* delete the partial match. */ - /*======================================*/ - - else - { - /*========================================*/ - /* Detach the partial match being deleted */ - /* from the new list of partial matches. */ - /*========================================*/ - - lastPM->next = listOfPMs->next; - - /*=============================================*/ - /* Add the partial match to the deletion list. */ - /*=============================================*/ - - if (*deleteHead == NULL) - { *deleteHead = listOfPMs; } - else - { lastDelete->next = listOfPMs; } - - listOfPMs->next = NULL; - lastDelete = listOfPMs; - - /*=============================*/ - /* Move on to the next partial */ - /* match to be examined. */ - /*=============================*/ - - listOfPMs = lastPM->next; - } - } + register unsigned short i; + register struct patternEntity * thePE; - /*==============================================*/ - /* Otherwise, the partial match should be added */ - /* to the new list of partial matches. */ - /*==============================================*/ + if (thePM == NULL) return FALSE; - else - { - lastPM = listOfPMs; - listOfPMs = listOfPMs->next; - } + for (i = 0 ; i < thePM->bcount ; i++) + { + if (thePM->binds[i].gm.theMatch == NULL) continue; + thePE = thePM->binds[i].gm.theMatch->matchingItem; + if (thePE && thePE->theInfo->isDeleted && + (*thePE->theInfo->isDeleted)(theEnv,thePE)) + return(TRUE); } - /*===============================================*/ - /* Return the last partial match in the new list */ - /* of partial matches via one of the function's */ - /* parameters. */ - /*===============================================*/ - - *returnLast = lastPM; - - /*=====================================================*/ - /* Return the head of the new list of partial matches. */ - /*=====================================================*/ - - return(head); + return(FALSE); } /***************************************************/ /* DeletePartialMatches: Returns a list of partial */ /* matches to the pool of free memory. */ /***************************************************/ -static void DeletePartialMatches( +void DeletePartialMatches( void *theEnv, - struct partialMatch *listOfPMs, - int betaDelete) + struct partialMatch *listOfPMs) { struct partialMatch *nextPM; @@ -699,7 +499,7 @@ static void DeletePartialMatches( /* Remember the next partial match to delete. */ /*============================================*/ - nextPM = listOfPMs->next; + nextPM = listOfPMs->nextInMemory; /*================================================*/ /* Remove the links between the partial match and */ @@ -707,7 +507,7 @@ static void DeletePartialMatches( /* result of a logical CE. */ /*================================================*/ - if (listOfPMs->dependentsf) RemoveLogicalSupport(theEnv,listOfPMs); + if (listOfPMs->dependents != NULL) RemoveLogicalSupport(theEnv,listOfPMs); /*==========================================================*/ /* If the partial match is being deleted from a beta memory */ @@ -722,14 +522,7 @@ static void DeletePartialMatches( /* immediately). */ /*==========================================================*/ - if (betaDelete && - ((listOfPMs->notOriginf == FALSE) || (listOfPMs->counterf))) - { ReturnPartialMatch(theEnv,listOfPMs); } - else - { - listOfPMs->next = EngineData(theEnv)->GarbagePartialMatches; - EngineData(theEnv)->GarbagePartialMatches = listOfPMs; - } + ReturnPartialMatch(theEnv,listOfPMs); /*====================================*/ /* Move on to the next partial match. */ @@ -755,7 +548,7 @@ globle void ReturnPartialMatch( if (waste->busy) { - waste->next = EngineData(theEnv)->GarbagePartialMatches; + waste->nextInMemory = EngineData(theEnv)->GarbagePartialMatches; EngineData(theEnv)->GarbagePartialMatches = waste; return; } @@ -780,14 +573,14 @@ globle void ReturnPartialMatch( /* the logical CE. */ /*=================================================*/ - if (waste->dependentsf) RemovePMDependencies(theEnv,waste); + if (waste->dependents != NULL) RemovePMDependencies(theEnv,waste); /*======================================================*/ /* Return the partial match to the pool of free memory. */ /*======================================================*/ rtn_var_struct(theEnv,partialMatch,(int) sizeof(struct genericMatch *) * - (waste->bcount + waste->activationf + waste->dependentsf - 1), + (waste->bcount - 1), waste); } @@ -812,20 +605,6 @@ globle void DestroyPartialMatch( { ReturnMarkers(theEnv,waste->binds[0].gm.theMatch->markers); } rm(theEnv,waste->binds[0].gm.theMatch,(int) sizeof(struct alphaMatch)); } - - /*================================================*/ - /* Remove the alpha match used to represent a not */ - /* CE match in a beta memory partial match. */ - /*================================================*/ - - if ((waste->notOriginf) && (waste->counterf == FALSE)) - { - if (waste->binds[waste->bcount - 1].gm.theMatch != NULL) - { - rtn_struct(theEnv,alphaMatch, - waste->binds[waste->bcount - 1].gm.theMatch); - } - } /*=================================================*/ /* Remove any links between the partial match and */ @@ -833,14 +612,14 @@ globle void DestroyPartialMatch( /* the logical CE. */ /*=================================================*/ - if (waste->dependentsf) DestroyPMDependencies(theEnv,waste); + if (waste->dependents != NULL) DestroyPMDependencies(theEnv,waste); /*======================================================*/ /* Return the partial match to the pool of free memory. */ /*======================================================*/ rtn_var_struct(theEnv,partialMatch,(int) sizeof(struct genericMatch *) * - (waste->bcount + waste->activationf + waste->dependentsf - 1), + (waste->bcount - 1), waste); } @@ -863,62 +642,6 @@ static void ReturnMarkers( } } -/*************************************************/ -/* DriveRetractions: Filters the list of partial */ -/* matches created as a result of removing a */ -/* data entity through the join network. */ -/*************************************************/ -static void DriveRetractions( - void *theEnv) - { - struct rdriveinfo *tempDR; - struct joinNode *joinPtr; - - while (EngineData(theEnv)->DriveRetractionList != NULL) - { - for (joinPtr = EngineData(theEnv)->DriveRetractionList->jlist; - joinPtr != NULL; - joinPtr = joinPtr->rightDriveNode) - { NetworkAssert(theEnv,EngineData(theEnv)->DriveRetractionList->link,joinPtr,LHS); } - - tempDR = EngineData(theEnv)->DriveRetractionList->next; - rtn_struct(theEnv,rdriveinfo,EngineData(theEnv)->DriveRetractionList); - EngineData(theEnv)->DriveRetractionList = tempDR; - } - } - -/*************************************************/ -/* RetractCheckDriveRetractions: */ -/*************************************************/ -globle void RetractCheckDriveRetractions( /* GDR 111599 #834 Begin */ - void *theEnv, - struct alphaMatch *theAlphaNode, - int position) - { - struct rdriveinfo *tempDR, *theDR, *lastDR = NULL; - - theDR = EngineData(theEnv)->DriveRetractionList; - while (theDR != NULL) - { - if ((position < (int) theDR->link->bcount) && - (theDR->link->binds[position].gm.theMatch == theAlphaNode)) - { - tempDR = theDR->next; - rtn_struct(theEnv,rdriveinfo,theDR); - if (lastDR == NULL) - { EngineData(theEnv)->DriveRetractionList = tempDR; } - else - { lastDR->next = tempDR; } - theDR = tempDR; - } - else - { - lastDR = theDR; - theDR = theDR->next; - } - } - } /* GDR 111599 #834 End */ - /*************************************************************/ /* FlushGarbagePartialMatches: Returns partial matches and */ /* associated structures that were removed as part of a */ @@ -956,23 +679,7 @@ globle void FlushGarbagePartialMatches( /* Remember the next garbage partial match to process. */ /*=====================================================*/ - pmPtr = EngineData(theEnv)->GarbagePartialMatches->next; - - /*=======================================================*/ - /* If a "pseudo" data entity was created for the partial */ - /* match (i.e. a not CE was satisfied), then dispose of */ - /* the pseudo data entity. */ - /*=======================================================*/ - - if ((EngineData(theEnv)->GarbagePartialMatches->notOriginf) && - (EngineData(theEnv)->GarbagePartialMatches->counterf == FALSE)) - { - if (EngineData(theEnv)->GarbagePartialMatches->binds[EngineData(theEnv)->GarbagePartialMatches->bcount - 1].gm.theMatch != NULL) - { - rtn_struct(theEnv,alphaMatch, - EngineData(theEnv)->GarbagePartialMatches->binds[EngineData(theEnv)->GarbagePartialMatches->bcount - 1].gm.theMatch); - } - } + pmPtr = EngineData(theEnv)->GarbagePartialMatches->nextInMemory; /*============================================*/ /* Dispose of the garbage partial match being */ diff --git a/src/retract.h b/src/retract.h index 7dcbc0f..6ffa581 100644 --- a/src/retract.h +++ b/src/retract.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RETRACT HEADER FILE */ /*******************************************************/ @@ -18,9 +18,20 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Rule with exists CE has incorrect activation. */ +/* 6.24: Removed LOGICAL_DEPENDENCIES compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Rule with exists CE has incorrect activation. */ /* DR0867 */ /* */ +/* 6.30: Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Removed pseudo-facts used in not CEs. */ +/* */ /*************************************************************/ #ifndef _H_retract @@ -51,14 +62,15 @@ struct rdriveinfo }; LOCALE void NetworkRetract(void *,struct patternMatch *); -LOCALE void PosEntryRetract(void *,struct joinNode *,struct alphaMatch *,struct partialMatch *,int,void *); LOCALE void ReturnPartialMatch(void *,struct partialMatch *); LOCALE void DestroyPartialMatch(void *,struct partialMatch *); LOCALE void FlushGarbagePartialMatches(void *); -LOCALE void NegEntryRetract(void *,struct joinNode *,struct partialMatch *,void *); -LOCALE void RetractCheckDriveRetractions(void *,struct alphaMatch *,int); +LOCALE void DeletePartialMatches(void *,struct partialMatch *); +LOCALE void PosEntryRetractBeta(void *,struct partialMatch *,struct partialMatch *,int); +LOCALE void PosEntryRetractAlpha(void *,struct partialMatch *,int); +LOCALE intBool PartialMatchWillBeDeleted(void *,struct partialMatch *); -#endif +#endif /* _H_retract */ diff --git a/src/router.c b/src/router.c index 4085ae6..565a5a3 100644 --- a/src/router.c +++ b/src/router.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* I/O ROUTER MODULE */ /*******************************************************/ @@ -14,17 +14,27 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.24: Removed conversion of '\r' to '\n' from the */ /* EnvGetcRouter function. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ -/* Added support for passing context information */ +/* Added support for passing context information */ /* to the router functions. */ /* */ +/* 6.30: Fixed issues with passing context to routers. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _ROUTER_SOURCE_ @@ -51,7 +61,7 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int QueryRouter(void *,char *,struct router *); + static int QueryRouter(void *,const char *,struct router *); static void DeallocateRouterData(void *); /*********************************************************/ @@ -62,15 +72,16 @@ globle void InitializeDefaultRouters( { AllocateEnvironmentData(theEnv,ROUTER_DATA,sizeof(struct routerData),DeallocateRouterData); - RouterData(theEnv)->CommandBufferInputCount = -1; - + RouterData(theEnv)->CommandBufferInputCount = 0; + RouterData(theEnv)->AwaitingInput = TRUE; + #if (! RUN_TIME) EnvDefineFunction2(theEnv,"exit", 'v', PTIEF ExitCommand, "ExitCommand", "*1i"); #endif InitializeFileRouter(theEnv); InitializeStringRouter(theEnv); } - + /*************************************************/ /* DeallocateRouterData: Deallocates environment */ /* data for I/O routers. */ @@ -79,11 +90,12 @@ static void DeallocateRouterData( void *theEnv) { struct router *tmpPtr, *nextPtr; - + tmpPtr = RouterData(theEnv)->ListOfRouters; while (tmpPtr != NULL) { nextPtr = tmpPtr->next; + genfree(theEnv,(void *) tmpPtr->name,strlen(tmpPtr->name) + 1); rtn_struct(theEnv,router,tmpPtr); tmpPtr = nextPtr; } @@ -94,8 +106,8 @@ static void DeallocateRouterData( /*******************************************/ globle int EnvPrintRouter( void *theEnv, - char *logicalName, - char *str) + const char *logicalName, + const char *str) { struct router *currentPtr; @@ -120,14 +132,14 @@ globle int EnvPrintRouter( currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { - SetEnvironmentRouterContext(theEnv,currentPtr->context); if ((currentPtr->printer != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE) { + SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { (*currentPtr->printer)(theEnv,logicalName,str); } - else - { ((int (*)(char *,char *)) (*currentPtr->printer))(logicalName,str); } - + else + { ((int (*)(const char *,const char *)) (*currentPtr->printer))(logicalName,str); } + return(1); } currentPtr = currentPtr->next; @@ -146,7 +158,7 @@ globle int EnvPrintRouter( /**************************************************/ globle int EnvGetcRouter( void *theEnv, - char *logicalName) + const char *logicalName) { struct router *currentPtr; int inchar; @@ -194,8 +206,6 @@ globle int EnvGetcRouter( { IncrementLineCount(theEnv); } } - /* if (inchar == '\r') return('\n'); */ - return(inchar); } @@ -209,10 +219,11 @@ globle int EnvGetcRouter( { if ((currentPtr->charget != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE) { + SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { inchar = (*currentPtr->charget)(theEnv,logicalName); } - else - { inchar = ((int (*)(char *)) (*currentPtr->charget))(logicalName); } + else + { inchar = ((int (*)(const char *)) (*currentPtr->charget))(logicalName); } if ((inchar == '\r') || (inchar == '\n')) { @@ -221,11 +232,6 @@ globle int EnvGetcRouter( { IncrementLineCount(theEnv); } } - /* if (inchar == '\r') return('\n'); */ - /* - if (inchar != '\b') - { return(inchar); } - */ return(inchar); } currentPtr = currentPtr->next; @@ -245,7 +251,7 @@ globle int EnvGetcRouter( globle int EnvUngetcRouter( void *theEnv, int ch, - char *logicalName) + const char *logicalName) { struct router *currentPtr; @@ -302,11 +308,12 @@ globle int EnvUngetcRouter( (strcmp(logicalName,RouterData(theEnv)->LineCountRouter) == 0)) { DecrementLineCount(theEnv); } } - + + SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { return((*currentPtr->charunget)(theEnv,ch,logicalName)); } - else - { return(((int (*)(int,char *)) (*currentPtr->charunget))(ch,logicalName)); } + else + { return(((int (*)(int,const char *)) (*currentPtr->charunget))(ch,logicalName)); } } currentPtr = currentPtr->next; @@ -358,12 +365,13 @@ globle void EnvExitRouter( { nextPtr = currentPtr->next; if (currentPtr->active == TRUE) - { - if (currentPtr->exiter != NULL) + { + if (currentPtr->exiter != NULL) { + SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { (*currentPtr->exiter)(theEnv,num); } - else + else { ((int (*)(int))(*currentPtr->exiter))(num); } } } @@ -371,7 +379,7 @@ globle void EnvExitRouter( } if (RouterData(theEnv)->Abort) return; - genexit(num); + genexit(theEnv,num); } /********************************************/ @@ -384,78 +392,17 @@ globle void AbortExit( RouterData(theEnv)->Abort = TRUE; } -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS -/*********************************************************/ -/* AddRouter: Adds an I/O router to the list of routers. */ -/*********************************************************/ -globle intBool AddRouter( - char *routerName, - int priority, - int (*queryFunction)(char *), - int (*printFunction)(char *,char *), - int (*getcFunction)(char *), - int (*ungetcFunction)(int,char *), - int (*exitFunction)(int)) - { - struct router *newPtr, *lastPtr, *currentPtr; - void *theEnv; - - theEnv = GetCurrentEnvironment(); - - newPtr = get_struct(theEnv,router); - - newPtr->name = routerName; - newPtr->active = TRUE; - newPtr->environmentAware = FALSE; - newPtr->priority = priority; - newPtr->context = NULL; - newPtr->query = (int (*)(void *,char *)) queryFunction; - newPtr->printer = (int (*)(void *,char *,char *)) printFunction; - newPtr->exiter = (int (*)(void *,int)) exitFunction; - newPtr->charget = (int (*)(void *,char *)) getcFunction; - newPtr->charunget = (int (*)(void *,int,char *)) ungetcFunction; - newPtr->next = NULL; - - if (RouterData(theEnv)->ListOfRouters == NULL) - { - RouterData(theEnv)->ListOfRouters = newPtr; - return(1); - } - - lastPtr = NULL; - currentPtr = RouterData(theEnv)->ListOfRouters; - while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) - { - lastPtr = currentPtr; - currentPtr = currentPtr->next; - } - - if (lastPtr == NULL) - { - newPtr->next = RouterData(theEnv)->ListOfRouters; - RouterData(theEnv)->ListOfRouters = newPtr; - } - else - { - newPtr->next = currentPtr; - lastPtr->next = newPtr; - } - - return(1); - } -#endif - /************************************************************/ /* EnvAddRouter: Adds an I/O router to the list of routers. */ /************************************************************/ globle intBool EnvAddRouter( void *theEnv, - char *routerName, + const char *routerName, int priority, - int (*queryFunction)(void *,char *), - int (*printFunction)(void *,char *,char *), - int (*getcFunction)(void *,char *), - int (*ungetcFunction)(void *,int,char *), + int (*queryFunction)(void *,const char *), + int (*printFunction)(void *,const char *,const char *), + int (*getcFunction)(void *,const char *), + int (*ungetcFunction)(void *,int,const char *), int (*exitFunction)(void *,int)) { return EnvAddRouterWithContext(theEnv,routerName,priority, @@ -468,20 +415,24 @@ globle intBool EnvAddRouter( /***********************************************************************/ globle intBool EnvAddRouterWithContext( void *theEnv, - char *routerName, + const char *routerName, int priority, - int (*queryFunction)(void *,char *), - int (*printFunction)(void *,char *,char *), - int (*getcFunction)(void *,char *), - int (*ungetcFunction)(void *,int,char *), + int (*queryFunction)(void *,const char *), + int (*printFunction)(void *,const char *,const char *), + int (*getcFunction)(void *,const char *), + int (*ungetcFunction)(void *,int,const char *), int (*exitFunction)(void *,int), void *context) { struct router *newPtr, *lastPtr, *currentPtr; + char *nameCopy; newPtr = get_struct(theEnv,router); - newPtr->name = routerName; + nameCopy = (char *) genalloc(theEnv,strlen(routerName) + 1); + genstrcpy(nameCopy,routerName); + newPtr->name = nameCopy; + newPtr->active = TRUE; newPtr->environmentAware = TRUE; newPtr->context = context; @@ -521,12 +472,12 @@ globle intBool EnvAddRouterWithContext( return(1); } -/*****************************************************************/ +/********************************************************************/ /* EnvDeleteRouter: Removes an I/O router from the list of routers. */ -/*****************************************************************/ +/********************************************************************/ globle int EnvDeleteRouter( void *theEnv, - char *routerName) + const char *routerName) { struct router *currentPtr, *lastPtr; @@ -537,6 +488,7 @@ globle int EnvDeleteRouter( { if (strcmp(currentPtr->name,routerName) == 0) { + genfree(theEnv,(void *) currentPtr->name,strlen(currentPtr->name) + 1); if (lastPtr == NULL) { RouterData(theEnv)->ListOfRouters = currentPtr->next; @@ -559,7 +511,7 @@ globle int EnvDeleteRouter( /*********************************************************************/ globle int QueryRouters( void *theEnv, - char *logicalName) + const char *logicalName) { struct router *currentPtr; @@ -579,7 +531,7 @@ globle int QueryRouters( /************************************************/ static int QueryRouter( void *theEnv, - char *logicalName, + const char *logicalName, struct router *currentPtr) { /*===================================================*/ @@ -600,14 +552,15 @@ static int QueryRouter( /* if it recognizes the logical name. */ /*=========================================*/ + SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) - { + { if ((*currentPtr->query)(theEnv,logicalName) == TRUE) { return(TRUE); } } - else - { - if (((int (*)(char *)) (*currentPtr->query))(logicalName) == TRUE) + else + { + if (((int (*)(const char *)) (*currentPtr->query))(logicalName) == TRUE) { return(TRUE); } } @@ -619,7 +572,7 @@ static int QueryRouter( /*******************************************************/ globle int EnvDeactivateRouter( void *theEnv, - char *routerName) + const char *routerName) { struct router *currentPtr; @@ -643,7 +596,7 @@ globle int EnvDeactivateRouter( /***************************************************/ globle int EnvActivateRouter( void *theEnv, - char *routerName) + const char *routerName) { struct router *currentPtr; @@ -668,21 +621,8 @@ globle int EnvActivateRouter( globle void SetFastLoad( void *theEnv, FILE *filePtr) - { - RouterData(theEnv)->FastLoadFilePtr = filePtr; - } - -/*****************************************************************************/ -/* SetFastCharLoad: Used to bypass router system for character string loads. */ -/*****************************************************************************/ -globle void SetFastCharLoad( - void *theEnv, - char *theString) { - RouterData(theEnv)->FastLoadFilePtr = NULL; - RouterData(theEnv)->FastCharGetRouter = theString; - RouterData(theEnv)->FastCharGetString = theString; - RouterData(theEnv)->FastCharGetIndex = 0; + RouterData(theEnv)->FastLoadFilePtr = filePtr; } /********************************************************/ @@ -691,8 +631,8 @@ globle void SetFastCharLoad( globle void SetFastSave( void *theEnv, FILE *filePtr) - { - RouterData(theEnv)->FastSaveFilePtr = filePtr; + { + RouterData(theEnv)->FastSaveFilePtr = filePtr; } /******************************************************/ @@ -701,7 +641,7 @@ globle void SetFastSave( globle FILE *GetFastLoad( void *theEnv) { - return(RouterData(theEnv)->FastLoadFilePtr); + return(RouterData(theEnv)->FastLoadFilePtr); } /******************************************************/ @@ -710,7 +650,7 @@ globle FILE *GetFastLoad( globle FILE *GetFastSave( void *theEnv) { - return(RouterData(theEnv)->FastSaveFilePtr); + return(RouterData(theEnv)->FastSaveFilePtr); } /*****************************************************/ @@ -719,7 +659,7 @@ globle FILE *GetFastSave( /*****************************************************/ globle void UnrecognizedRouterMessage( void *theEnv, - char *logicalName) + const char *logicalName) { PrintErrorID(theEnv,"ROUTER",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Logical name "); @@ -732,17 +672,130 @@ globle void UnrecognizedRouterMessage( /*****************************************/ globle int PrintNRouter( void *theEnv, - char *logicalName, - char *str, + const char *logicalName, + const char *str, unsigned long length) { char *tempStr; int rv; - tempStr = (char *) genlongalloc(theEnv,length+1); - strncpy(tempStr,str,length); + tempStr = (char *) genalloc(theEnv,length+1); + genstrncpy(tempStr,str,length); tempStr[length] = 0; rv = EnvPrintRouter(theEnv,logicalName,tempStr); - genlongfree(theEnv,tempStr,length+1); + genfree(theEnv,tempStr,length+1); return(rv); } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle int ActivateRouter( + const char *routerName) + { + return EnvActivateRouter(GetCurrentEnvironment(),routerName); + } + +globle intBool AddRouter( + const char *routerName, + int priority, + int (*queryFunction)(const char *), + int (*printFunction)(const char *,const char *), + int (*getcFunction)(const char *), + int (*ungetcFunction)(int,const char *), + int (*exitFunction)(int)) + { + struct router *newPtr, *lastPtr, *currentPtr; + void *theEnv; + char *nameCopy; + + theEnv = GetCurrentEnvironment(); + + newPtr = get_struct(theEnv,router); + + nameCopy = (char *) genalloc(theEnv,strlen(routerName) + 1); + genstrcpy(nameCopy,routerName); + newPtr->name = nameCopy; + + newPtr->active = TRUE; + newPtr->environmentAware = FALSE; + newPtr->priority = priority; + newPtr->context = NULL; + newPtr->query = (int (*)(void *,const char *)) queryFunction; + newPtr->printer = (int (*)(void *,const char *,const char *)) printFunction; + newPtr->exiter = (int (*)(void *,int)) exitFunction; + newPtr->charget = (int (*)(void *,const char *)) getcFunction; + newPtr->charunget = (int (*)(void *,int,const char *)) ungetcFunction; + newPtr->next = NULL; + + if (RouterData(theEnv)->ListOfRouters == NULL) + { + RouterData(theEnv)->ListOfRouters = newPtr; + return(1); + } + + lastPtr = NULL; + currentPtr = RouterData(theEnv)->ListOfRouters; + while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) + { + lastPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if (lastPtr == NULL) + { + newPtr->next = RouterData(theEnv)->ListOfRouters; + RouterData(theEnv)->ListOfRouters = newPtr; + } + else + { + newPtr->next = currentPtr; + lastPtr->next = newPtr; + } + + return(1); + } + +globle int DeactivateRouter( + const char *routerName) + { + return EnvDeactivateRouter(GetCurrentEnvironment(),routerName); + } + +globle int DeleteRouter( + const char *routerName) + { + return EnvDeleteRouter(GetCurrentEnvironment(),routerName); + } + +globle void ExitRouter( + int num) + { + EnvExitRouter(GetCurrentEnvironment(),num); + } + +globle int GetcRouter( + const char *logicalName) + { + return EnvGetcRouter(GetCurrentEnvironment(),logicalName); + } + +globle int PrintRouter( + const char *logicalName, + const char *str) + { + return EnvPrintRouter(GetCurrentEnvironment(),logicalName,str); + } + +globle int UngetcRouter( + int ch, + const char *logicalName) + { + return EnvUngetcRouter(GetCurrentEnvironment(),ch,logicalName); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + diff --git a/src/router.h b/src/router.h index fb3edd4..3d76eb1 100644 --- a/src/router.h +++ b/src/router.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* ROUTER HEADER FILE */ /*******************************************************/ @@ -17,41 +17,28 @@ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed conversion of '\r' to '\n' from the */ +/* EnvGetcRouter function. */ /* */ -/* Added support for passing context information */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* Added support for passing context information */ /* to the router functions. */ /* */ +/* 6.30: Fixed issues with passing context to routers. */ +/* */ +/* Added AwaitingInput flag. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ -// -//Copyright(c) 2012 Samsung Electronics Co., Ltd. All rights reserved -//on modified portion of CLIPS. -//Except as noted, this software is licensed under Apache License, Version 2. -//Please, see the LICENSE file for Apache License terms and conditions. -// -//This original version of this software is under public domain. Please, see -//the readme.txt file for original software license information. - - -// -// Open Service Platform -// Copyright (c) 2012 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - - #ifndef _H_router #define _H_router @@ -70,29 +57,32 @@ #define WDIALOG "wdialog" #define WPROMPT WPROMPT_STRING #define WDISPLAY "wdisplay" +#define STDOUT "stdout" +#define STDIN "stdin" #define ROUTER_DATA 46 struct router { - char *name; + const char *name; int active; int priority; short int environmentAware; void *context; - int (*query)(void *,char *); - int (*printer)(void *,char *,char *); + int (*query)(void *,const char *); + int (*printer)(void *,const char *,const char *); int (*exiter)(void *,int); - int (*charget)(void *,char *); - int (*charunget)(void *,int,char *); + int (*charget)(void *,const char *); + int (*charunget)(void *,int,const char *); struct router *next; }; struct routerData - { - int CommandBufferInputCount; - char *LineCountRouter; - char *FastCharGetRouter; + { + size_t CommandBufferInputCount; + int AwaitingInput; + const char *LineCountRouter; + const char *FastCharGetRouter; char *FastCharGetString; long FastCharGetIndex; struct router *ListOfRouters; @@ -113,64 +103,57 @@ struct routerData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define ExitRouter(theEnv,a) EnvExitRouter(theEnv,a) -#define GetcRouter(theEnv,a) EnvGetcRouter(theEnv,a) -#define PrintRouter(theEnv,a,b) EnvPrintRouter(theEnv,a,b) -#define UngetcRouter(theEnv,a,b) EnvUngetcRouter(theEnv,a,b) -#define ActivateRouter(theEnv,a) EnvActivateRouter(theEnv,a) -#define DeactivateRouter(theEnv,a) EnvDeactivateRouter(theEnv,a) -#define DeleteRouter(theEnv,a) EnvDeleteRouter(theEnv,a) -#else -#define ExitRouter(a) EnvExitRouter(GetCurrentEnvironment(),a) -#define GetcRouter(a) EnvGetcRouter(GetCurrentEnvironment(),a) -#define PrintRouter(a,b) EnvPrintRouter(GetCurrentEnvironment(),a,b) -#define UngetcRouter(a,b) EnvUngetcRouter(GetCurrentEnvironment(),a,b) -#define ActivateRouter(a) EnvActivateRouter(GetCurrentEnvironment(),a) -#define DeactivateRouter(a) EnvDeactivateRouter(GetCurrentEnvironment(),a) -#define DeleteRouter(a) EnvDeleteRouter(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeDefaultRouters(void *); - LOCALE int EnvPrintRouter(void *,char *,char *); - LOCALE int EnvGetcRouter(void *,char *); - LOCALE int EnvUngetcRouter(void *,int,char *); + LOCALE int EnvPrintRouter(void *,const char *,const char *); + LOCALE int EnvGetcRouter(void *,const char *); + LOCALE int EnvUngetcRouter(void *,int,const char *); LOCALE void EnvExitRouter(void *,int); LOCALE void AbortExit(void *); LOCALE intBool EnvAddRouterWithContext(void *, - char *,int, - int (*)(void *,char *), - int (*)(void *,char *,char *), - int (*)(void *,char *), - int (*)(void *,int,char *), + const char *,int, + int (*)(void *,const char *), + int (*)(void *,const char *,const char *), + int (*)(void *,const char *), + int (*)(void *,int,const char *), int (*)(void *,int), void *); LOCALE intBool EnvAddRouter(void *, - char *,int, - int (*)(void *,char *), - int (*)(void *,char *,char *), - int (*)(void *,char *), - int (*)(void *,int,char *), + const char *,int, + int (*)(void *,const char *), + int (*)(void *,const char *,const char *), + int (*)(void *,const char *), + int (*)(void *,int,const char *), int (*)(void *,int)); - LOCALE intBool AddRouter(char *,int, - int (*)(char *), - int (*)(char *,char *), - int (*)(char *), - int (*)(int,char *), - int (*)(int)); - LOCALE int EnvDeleteRouter(void *,char *); - LOCALE int QueryRouters(void *,char *); - LOCALE int EnvDeactivateRouter(void *,char *); - LOCALE int EnvActivateRouter(void *,char *); + LOCALE int EnvDeleteRouter(void *,const char *); + LOCALE int QueryRouters(void *,const char *); + LOCALE int EnvDeactivateRouter(void *,const char *); + LOCALE int EnvActivateRouter(void *,const char *); LOCALE void SetFastLoad(void *,FILE *); - LOCALE void SetFastCharLoad(void *,char *); LOCALE void SetFastSave(void *,FILE *); LOCALE FILE *GetFastLoad(void *); LOCALE FILE *GetFastSave(void *); - LOCALE void UnrecognizedRouterMessage(void *,char *); + LOCALE void UnrecognizedRouterMessage(void *,const char *); LOCALE void ExitCommand(void *); - LOCALE int PrintNRouter(void *,char *,char *,unsigned long); + LOCALE int PrintNRouter(void *,const char *,const char *,unsigned long); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE int ActivateRouter(const char *); + LOCALE intBool AddRouter(const char *,int, + int (*)(const char *), + int (*)(const char *,const char *), + int (*)(const char *), + int (*)(int,const char *), + int (*)(int)); + LOCALE int DeactivateRouter(const char *); + LOCALE int DeleteRouter(const char *); + LOCALE void ExitRouter(int); + LOCALE int GetcRouter(const char *); + LOCALE int PrintRouter(const char *,const char *); + LOCALE int UngetcRouter(int,const char *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_router */ diff --git a/src/rulebin.c b/src/rulebin.c index 677d910..3d30343 100644 --- a/src/rulebin.c +++ b/src/rulebin.c @@ -1,8 +1,7 @@ - /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFRULE BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -15,7 +14,7 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* Barry Cameron */ /* */ /* Revision History: */ @@ -24,6 +23,14 @@ /* DYNAMIC_SALIENCE, and LOGICAL_DEPENDENCIES */ /* compilation flags. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added support for alpha memories. */ +/* */ +/* Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ /*************************************************************/ #define _RULEBIN_SOURCE_ @@ -62,12 +69,17 @@ static void BsaveJoins(void *,FILE *); static void BsaveJoin(void *,FILE *,struct joinNode *); static void BsaveDisjuncts(void *,FILE *,struct defrule *); + static void BsaveTraverseJoins(void *,FILE *,struct joinNode *); + static void BsaveLinks(void *,FILE *); + static void BsaveTraverseLinks(void *,FILE *,struct joinNode *); + static void BsaveLink(FILE *,struct joinLink *); #endif static void BloadStorage(void *); static void BloadBinaryItem(void *); static void UpdateDefruleModule(void *,void *,long); static void UpdateDefrule(void *,void *,long); static void UpdateJoin(void *,void *,long); + static void UpdateLink(void *,void *,long); static void ClearBload(void *); static void DeallocateDefruleBloadData(void *); @@ -101,40 +113,59 @@ static void DeallocateDefruleBloadData( void *theEnv) { #if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME) - unsigned long space; + size_t space; long i; struct defruleModule *theModuleItem; struct activation *theActivation, *tmpActivation; + struct salienceGroup *theGroup, *tmpGroup; for (i = 0; i < DefruleBinaryData(theEnv)->NumberOfJoins; i++) - { DestroyAlphaBetaMemory(theEnv,DefruleBinaryData(theEnv)->JoinArray[i].beta); } + { + DestroyBetaMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i],LHS); + DestroyBetaMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i],RHS); + ReturnLeftMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i]); + ReturnRightMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i]); + } for (i = 0; i < DefruleBinaryData(theEnv)->NumberOfDefruleModules; i++) { theModuleItem = &DefruleBinaryData(theEnv)->ModuleArray[i]; - + theActivation = theModuleItem->agenda; while (theActivation != NULL) { tmpActivation = theActivation->next; - - if (theActivation->sortedBasis != NULL) - { DestroyPartialMatch(theEnv,theActivation->sortedBasis); } rtn_struct(theEnv,activation,theActivation); - + theActivation = tmpActivation; } + + theGroup = theModuleItem->groupings; + while (theGroup != NULL) + { + tmpGroup = theGroup->next; + + rtn_struct(theEnv,salienceGroup,theGroup); + + theGroup = tmpGroup; + } } - + space = DefruleBinaryData(theEnv)->NumberOfDefruleModules * sizeof(struct defruleModule); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->ModuleArray,space); - + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->ModuleArray,space); + space = DefruleBinaryData(theEnv)->NumberOfDefrules * sizeof(struct defrule); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->DefruleArray,space); - + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->DefruleArray,space); + space = DefruleBinaryData(theEnv)->NumberOfJoins * sizeof(struct joinNode); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->JoinArray,space); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->JoinArray,space); + + space = DefruleBinaryData(theEnv)->NumberOfLinks * sizeof(struct joinLink); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->LinkArray,space); + + if (Bloaded(theEnv)) + { rm3(theEnv,DefruleData(theEnv)->AlphaMemoryTable,sizeof(ALPHA_MEMORY_HASH *) * ALPHA_MEMORY_HASH_SIZE); } #endif } @@ -160,6 +191,7 @@ static void BsaveFind( SaveBloadCount(theEnv,DefruleBinaryData(theEnv)->NumberOfDefruleModules); SaveBloadCount(theEnv,DefruleBinaryData(theEnv)->NumberOfDefrules); SaveBloadCount(theEnv,DefruleBinaryData(theEnv)->NumberOfJoins); + SaveBloadCount(theEnv,DefruleBinaryData(theEnv)->NumberOfLinks); /*====================================================*/ /* Set the binary save ID for defrule data structures */ @@ -168,7 +200,8 @@ static void BsaveFind( TagRuleNetwork(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefruleModules, &DefruleBinaryData(theEnv)->NumberOfDefrules, - &DefruleBinaryData(theEnv)->NumberOfJoins); + &DefruleBinaryData(theEnv)->NumberOfJoins, + &DefruleBinaryData(theEnv)->NumberOfLinks); /*===========================*/ /* Loop through each module. */ @@ -299,13 +332,29 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; + long int value; + + space = sizeof(long) * 5; + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&DefruleBinaryData(theEnv)->NumberOfDefruleModules,sizeof(long int),fp); + GenWrite(&DefruleBinaryData(theEnv)->NumberOfDefrules,sizeof(long int),fp); + GenWrite(&DefruleBinaryData(theEnv)->NumberOfJoins,sizeof(long int),fp); + GenWrite(&DefruleBinaryData(theEnv)->NumberOfLinks,sizeof(long int),fp); + + if (DefruleData(theEnv)->RightPrimeJoins == NULL) + { value = -1; } + else + { value = DefruleData(theEnv)->RightPrimeJoins->bsaveID; } + + GenWrite(&value,sizeof(long int),fp); + + if (DefruleData(theEnv)->LeftPrimeJoins == NULL) + { value = -1; } + else + { value = DefruleData(theEnv)->LeftPrimeJoins->bsaveID; } - space = sizeof(long) * 3; - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); - GenWrite(&DefruleBinaryData(theEnv)->NumberOfDefruleModules,(unsigned long) sizeof(long int),fp); - GenWrite(&DefruleBinaryData(theEnv)->NumberOfDefrules,(unsigned long) sizeof(long int),fp); - GenWrite(&DefruleBinaryData(theEnv)->NumberOfJoins,(unsigned long) sizeof(long int),fp); + GenWrite(&value,sizeof(long int),fp); } /*******************************************/ @@ -316,7 +365,7 @@ static void BsaveBinaryItem( void *theEnv, FILE *fp) { - unsigned long int space; + size_t space; struct defrule *theDefrule; struct defmodule *theModule; struct defruleModule *theModuleItem; @@ -328,8 +377,9 @@ static void BsaveBinaryItem( space = (DefruleBinaryData(theEnv)->NumberOfDefrules * sizeof(struct bsaveDefrule)) + (DefruleBinaryData(theEnv)->NumberOfJoins * sizeof(struct bsaveJoinNode)) + + (DefruleBinaryData(theEnv)->NumberOfLinks * sizeof(struct bsaveJoinLink)) + (DefruleBinaryData(theEnv)->NumberOfDefruleModules * sizeof(struct bsaveDefruleModule)); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*===============================================*/ /* Write out each defrule module data structure. */ @@ -346,7 +396,7 @@ static void BsaveBinaryItem( GetModuleItem(theEnv,NULL,FindModuleItem(theEnv,"defrule")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&tempDefruleModule.header, &theModuleItem->header); - GenWrite(&tempDefruleModule,(unsigned long) sizeof(struct bsaveDefruleModule),fp); + GenWrite(&tempDefruleModule,sizeof(struct bsaveDefruleModule),fp); } /*========================================*/ @@ -372,6 +422,13 @@ static void BsaveBinaryItem( MarkRuleNetwork(theEnv,1); BsaveJoins(theEnv,fp); + /*===========================*/ + /* Write out the join links. */ + /*===========================*/ + + MarkRuleNetwork(theEnv,1); + BsaveLinks(theEnv,fp); + /*=============================================================*/ /* If a binary image was already loaded when the bsave command */ /* was issued, then restore the counts indicating the number */ @@ -382,6 +439,7 @@ static void BsaveBinaryItem( RestoreBloadCount(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefruleModules); RestoreBloadCount(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefrules); RestoreBloadCount(theEnv,&DefruleBinaryData(theEnv)->NumberOfJoins); + RestoreBloadCount(theEnv,&DefruleBinaryData(theEnv)->NumberOfLinks); } /************************************************************/ @@ -470,7 +528,7 @@ static void BsaveDisjuncts( /* Write the disjunct to the file. */ /*=================================*/ - GenWrite(&tempDefrule,(unsigned long) sizeof(struct bsaveDefrule),fp); + GenWrite(&tempDefrule,sizeof(struct bsaveDefrule),fp); } } @@ -482,8 +540,7 @@ static void BsaveJoins( void *theEnv, FILE *fp) { - struct defrule *rulePtr; - struct joinNode *joinPtr; + struct defrule *rulePtr, *disjunctPtr; struct defmodule *theModule; /*===========================*/ @@ -507,21 +564,37 @@ static void BsaveJoins( /* Loop through each join of the disjunct. */ /*=========================================*/ - for (joinPtr = rulePtr->lastJoin; - joinPtr != NULL; - joinPtr = GetPreviousJoin(joinPtr)) - { if (joinPtr->marked) BsaveJoin(theEnv,fp,joinPtr); } + for (disjunctPtr = rulePtr; disjunctPtr != NULL; disjunctPtr = disjunctPtr->disjunct) + { BsaveTraverseJoins(theEnv,fp,disjunctPtr->lastJoin); } - /*=======================================*/ - /* Move on to the next rule or disjunct. */ - /*=======================================*/ + /*===========================*/ + /* Move on to the next rule. */ + /*===========================*/ - if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct; - else rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); + rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); } } } +/**************************************************************/ +/* BsaveTraverseJoins: Traverses the join network for a rule. */ +/**************************************************************/ +static void BsaveTraverseJoins( + void *theEnv, + FILE *fp, + struct joinNode *joinPtr) + { + for (; + joinPtr != NULL; + joinPtr = joinPtr->lastLevel) + { + if (joinPtr->marked) BsaveJoin(theEnv,fp,joinPtr); + + if (joinPtr->joinFromTheRight) + { BsaveTraverseJoins(theEnv,fp,(struct joinNode *) joinPtr->rightSideEntryStructure); } + } + } + /********************************************/ /* BsaveJoin: Writes out a single join node */ /* data structure to the binary file. */ @@ -540,6 +613,7 @@ static void BsaveJoin( tempJoin.logicalJoin = joinPtr->logicalJoin; tempJoin.joinFromTheRight = joinPtr->joinFromTheRight; tempJoin.patternIsNegated = joinPtr->patternIsNegated; + tempJoin.patternIsExists = joinPtr->patternIsExists; if (joinPtr->joinFromTheRight) { tempJoin.rightSideEntryStructure = BsaveJoinIndex(joinPtr->rightSideEntryStructure); } @@ -547,10 +621,12 @@ static void BsaveJoin( { tempJoin.rightSideEntryStructure = -1L; } tempJoin.lastLevel = BsaveJoinIndex(joinPtr->lastLevel); - tempJoin.nextLevel = BsaveJoinIndex(joinPtr->nextLevel); + tempJoin.nextLinks = BsaveJoinLinkIndex(joinPtr->nextLinks); tempJoin.rightMatchNode = BsaveJoinIndex(joinPtr->rightMatchNode); - tempJoin.rightDriveNode = BsaveJoinIndex(joinPtr->rightDriveNode); tempJoin.networkTest = HashedExpressionIndex(theEnv,joinPtr->networkTest); + tempJoin.secondaryNetworkTest = HashedExpressionIndex(theEnv,joinPtr->secondaryNetworkTest); + tempJoin.leftHash = HashedExpressionIndex(theEnv,joinPtr->leftHash); + tempJoin.rightHash = HashedExpressionIndex(theEnv,joinPtr->rightHash); if (joinPtr->ruleToActivate != NULL) { @@ -563,20 +639,125 @@ static void BsaveJoin( GenWrite(&tempJoin,(unsigned long) sizeof(struct bsaveJoinNode),fp); } +/********************************************/ +/* BsaveLinks: Writes out all the join link */ +/* data structures to the binary file. */ +/********************************************/ +static void BsaveLinks( + void *theEnv, + FILE *fp) + { + struct defrule *rulePtr, *disjunctPtr; + struct defmodule *theModule; + struct joinLink *theLink; + + for (theLink = DefruleData(theEnv)->LeftPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { BsaveLink(fp,theLink); } + + for (theLink = DefruleData(theEnv)->RightPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { BsaveLink(fp,theLink); } + + /*===========================*/ + /* Loop through each module. */ + /*===========================*/ + + for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL); + theModule != NULL; + theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule)) + { + EnvSetCurrentModule(theEnv,(void *) theModule); + + /*===========================================*/ + /* Loop through each rule and its disjuncts. */ + /*===========================================*/ + + rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,NULL); + while (rulePtr != NULL) + { + /*=========================================*/ + /* Loop through each join of the disjunct. */ + /*=========================================*/ + + for (disjunctPtr = rulePtr; disjunctPtr != NULL; disjunctPtr = disjunctPtr->disjunct) + { BsaveTraverseLinks(theEnv,fp,disjunctPtr->lastJoin); } + + /*=======================================*/ + /* Move on to the next rule or disjunct. */ + /*=======================================*/ + + rulePtr = (struct defrule *) EnvGetNextDefrule(theEnv,rulePtr); + } + } + } + +/***************************************************/ +/* BsaveTraverseLinks: Traverses the join network */ +/* for a rule saving the join links. */ +/**************************************************/ +static void BsaveTraverseLinks( + void *theEnv, + FILE *fp, + struct joinNode *joinPtr) + { + struct joinLink *theLink; + + for (; + joinPtr != NULL; + joinPtr = joinPtr->lastLevel) + { + if (joinPtr->marked) + { + for (theLink = joinPtr->nextLinks; + theLink != NULL; + theLink = theLink->next) + { BsaveLink(fp,theLink); } + + joinPtr->marked = 0; + } + + if (joinPtr->joinFromTheRight) + { BsaveTraverseLinks(theEnv,fp,(struct joinNode *) joinPtr->rightSideEntryStructure); } + } + } + +/********************************************/ +/* BsaveLink: Writes out a single join link */ +/* data structure to the binary file. */ +/********************************************/ +static void BsaveLink( + FILE *fp, + struct joinLink *linkPtr) + { + struct bsaveJoinLink tempLink; + + tempLink.enterDirection = linkPtr->enterDirection; + tempLink.join = BsaveJoinIndex(linkPtr->join); + tempLink.next = BsaveJoinLinkIndex(linkPtr->next); + + GenWrite(&tempLink,(unsigned long) sizeof(struct bsaveJoinLink),fp); + } + /***********************************************************/ /* AssignBsavePatternHeaderValues: Assigns the appropriate */ /* values to a bsave pattern header record. */ /***********************************************************/ globle void AssignBsavePatternHeaderValues( + void *theEnv, struct bsavePatternNodeHeader *theBsaveHeader, struct patternNodeHeader *theHeader) { theBsaveHeader->multifieldNode = theHeader->multifieldNode; theBsaveHeader->entryJoin = BsaveJoinIndex(theHeader->entryJoin); + theBsaveHeader->rightHash = HashedExpressionIndex(theEnv,theHeader->rightHash); theBsaveHeader->singlefieldNode = theHeader->singlefieldNode; theBsaveHeader->stopNode = theHeader->stopNode; theBsaveHeader->beginSlot = theHeader->beginSlot; theBsaveHeader->endSlot = theHeader->endSlot; + theBsaveHeader->selector = theHeader->selector; } #endif /* BLOAD_AND_BSAVE */ @@ -588,17 +769,20 @@ globle void AssignBsavePatternHeaderValues( static void BloadStorage( void *theEnv) { - unsigned long space; + size_t space; /*=================================================*/ /* Determine the number of defrule, defruleModule, */ /* and joinNode data structures to be read. */ /*=================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefruleModules,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefrules,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfJoins,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefruleModules,sizeof(long int)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfDefrules,sizeof(long int)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfJoins,sizeof(long int)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->NumberOfLinks,sizeof(long int)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->RightPrimeIndex,sizeof(long int)); + GenReadBinary(theEnv,&DefruleBinaryData(theEnv)->LeftPrimeIndex,sizeof(long int)); /*===================================*/ /* Allocate the space needed for the */ @@ -613,7 +797,7 @@ static void BloadStorage( } space = DefruleBinaryData(theEnv)->NumberOfDefruleModules * sizeof(struct defruleModule); - DefruleBinaryData(theEnv)->ModuleArray = (struct defruleModule *) genlongalloc(theEnv,space); + DefruleBinaryData(theEnv)->ModuleArray = (struct defruleModule *) genalloc(theEnv,space); /*===============================*/ /* Allocate the space needed for */ @@ -628,7 +812,7 @@ static void BloadStorage( } space = DefruleBinaryData(theEnv)->NumberOfDefrules * sizeof(struct defrule); - DefruleBinaryData(theEnv)->DefruleArray = (struct defrule *) genlongalloc(theEnv,space); + DefruleBinaryData(theEnv)->DefruleArray = (struct defrule *) genalloc(theEnv,space); /*===============================*/ /* Allocate the space needed for */ @@ -636,7 +820,15 @@ static void BloadStorage( /*===============================*/ space = DefruleBinaryData(theEnv)->NumberOfJoins * sizeof(struct joinNode); - DefruleBinaryData(theEnv)->JoinArray = (struct joinNode *) genlongalloc(theEnv,space); + DefruleBinaryData(theEnv)->JoinArray = (struct joinNode *) genalloc(theEnv,space); + + /*===============================*/ + /* Allocate the space needed for */ + /* the joinNode data structures. */ + /*===============================*/ + + space = DefruleBinaryData(theEnv)->NumberOfLinks * sizeof(struct joinLink); + DefruleBinaryData(theEnv)->LinkArray = (struct joinLink *) genalloc(theEnv,space); } /****************************************************/ @@ -646,7 +838,7 @@ static void BloadStorage( static void BloadBinaryItem( void *theEnv) { - unsigned long space; + size_t space; /*======================================================*/ /* Read in the amount of space used by the binary image */ @@ -654,31 +846,42 @@ static void BloadBinaryItem( /* is not available in the version being run). */ /*======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); /*===========================================*/ /* Read in the defruleModule data structures */ /* and refresh the pointers. */ /*===========================================*/ - BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfDefruleModules,(unsigned) sizeof(struct bsaveDefruleModule), - UpdateDefruleModule); + BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfDefruleModules, + sizeof(struct bsaveDefruleModule),UpdateDefruleModule); /*=====================================*/ /* Read in the defrule data structures */ /* and refresh the pointers. */ /*=====================================*/ - BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfDefrules,(unsigned) sizeof(struct bsaveDefrule), - UpdateDefrule); + BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfDefrules, + sizeof(struct bsaveDefrule),UpdateDefrule); /*======================================*/ /* Read in the joinNode data structures */ /* and refresh the pointers. */ /*======================================*/ - BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfJoins,(unsigned) sizeof(struct bsaveJoinNode), - UpdateJoin); + BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfJoins, + sizeof(struct bsaveJoinNode),UpdateJoin); + + /*======================================*/ + /* Read in the joinLink data structures */ + /* and refresh the pointers. */ + /*======================================*/ + + BloadandRefresh(theEnv,DefruleBinaryData(theEnv)->NumberOfLinks, + sizeof(struct bsaveJoinLink),UpdateLink); + + DefruleData(theEnv)->RightPrimeJoins = BloadJoinLinkPointer(DefruleBinaryData(theEnv)->RightPrimeIndex); + DefruleData(theEnv)->LeftPrimeJoins = BloadJoinLinkPointer(DefruleBinaryData(theEnv)->LeftPrimeIndex); } /**********************************************/ @@ -697,6 +900,8 @@ static void UpdateDefruleModule( (int) sizeof(struct defrule), (void *) DefruleBinaryData(theEnv)->DefruleArray); DefruleBinaryData(theEnv)->ModuleArray[obji].agenda = NULL; + DefruleBinaryData(theEnv)->ModuleArray[obji].groupings = NULL; + } /****************************************/ @@ -749,22 +954,47 @@ static void UpdateJoin( DefruleBinaryData(theEnv)->JoinArray[obji].logicalJoin = bj->logicalJoin; DefruleBinaryData(theEnv)->JoinArray[obji].joinFromTheRight = bj->joinFromTheRight; DefruleBinaryData(theEnv)->JoinArray[obji].patternIsNegated = bj->patternIsNegated; + DefruleBinaryData(theEnv)->JoinArray[obji].patternIsExists = bj->patternIsExists; DefruleBinaryData(theEnv)->JoinArray[obji].depth = bj->depth; DefruleBinaryData(theEnv)->JoinArray[obji].rhsType = bj->rhsType; DefruleBinaryData(theEnv)->JoinArray[obji].networkTest = HashedExpressionPointer(bj->networkTest); - DefruleBinaryData(theEnv)->JoinArray[obji].nextLevel = BloadJoinPointer(bj->nextLevel); + DefruleBinaryData(theEnv)->JoinArray[obji].secondaryNetworkTest = HashedExpressionPointer(bj->secondaryNetworkTest); + DefruleBinaryData(theEnv)->JoinArray[obji].leftHash = HashedExpressionPointer(bj->leftHash); + DefruleBinaryData(theEnv)->JoinArray[obji].rightHash = HashedExpressionPointer(bj->rightHash); + DefruleBinaryData(theEnv)->JoinArray[obji].nextLinks = BloadJoinLinkPointer(bj->nextLinks); DefruleBinaryData(theEnv)->JoinArray[obji].lastLevel = BloadJoinPointer(bj->lastLevel); if (bj->joinFromTheRight == TRUE) { DefruleBinaryData(theEnv)->JoinArray[obji].rightSideEntryStructure = (void *) BloadJoinPointer(bj->rightSideEntryStructure); } + else + { DefruleBinaryData(theEnv)->JoinArray[obji].rightSideEntryStructure = NULL; } DefruleBinaryData(theEnv)->JoinArray[obji].rightMatchNode = BloadJoinPointer(bj->rightMatchNode); - DefruleBinaryData(theEnv)->JoinArray[obji].rightDriveNode = BloadJoinPointer(bj->rightDriveNode); DefruleBinaryData(theEnv)->JoinArray[obji].ruleToActivate = BloadDefrulePointer(DefruleBinaryData(theEnv)->DefruleArray,bj->ruleToActivate); DefruleBinaryData(theEnv)->JoinArray[obji].initialize = 0; DefruleBinaryData(theEnv)->JoinArray[obji].marked = 0; DefruleBinaryData(theEnv)->JoinArray[obji].bsaveID = 0L; - DefruleBinaryData(theEnv)->JoinArray[obji].beta = NULL; + DefruleBinaryData(theEnv)->JoinArray[obji].leftMemory = NULL; + DefruleBinaryData(theEnv)->JoinArray[obji].rightMemory = NULL; + + AddBetaMemoriesToJoin(theEnv,&DefruleBinaryData(theEnv)->JoinArray[obji]); + } + +/*************************************/ +/* UpdateLink: Bload refresh routine */ +/* for joinLink data structures. */ +/*************************************/ +static void UpdateLink( + void *theEnv, + void *buf, + long obji) + { + struct bsaveJoinLink *bj; + + bj = (struct bsaveJoinLink *) buf; + DefruleBinaryData(theEnv)->LinkArray[obji].enterDirection = bj->enterDirection; + DefruleBinaryData(theEnv)->LinkArray[obji].next = BloadJoinLinkPointer(bj->next); + DefruleBinaryData(theEnv)->LinkArray[obji].join = BloadJoinPointer(bj->join); } /************************************************************/ @@ -783,10 +1013,12 @@ globle void UpdatePatternNodeHeader( theHeader->stopNode = theBsaveHeader->stopNode; theHeader->beginSlot = theBsaveHeader->beginSlot; theHeader->endSlot = theBsaveHeader->endSlot; + theHeader->selector = theBsaveHeader->selector; theHeader->initialize = 0; theHeader->marked = 0; - theHeader->alphaMemory = NULL; - theHeader->endOfQueue = NULL; + theHeader->firstHash = NULL; + theHeader->lastHash = NULL; + theHeader->rightHash = HashedExpressionPointer(theBsaveHeader->rightHash); theJoin = BloadJoinPointer(theBsaveHeader->entryJoin); theHeader->entryJoin = theJoin; @@ -805,7 +1037,7 @@ globle void UpdatePatternNodeHeader( static void ClearBload( void *theEnv) { - unsigned long int space; + size_t space; long i; struct patternParser *theParser = NULL; struct patternEntity *theEntity = NULL; @@ -846,7 +1078,12 @@ static void ClearBload( /*==========================================================*/ for (i = 0; i < DefruleBinaryData(theEnv)->NumberOfJoins; i++) - { FlushAlphaBetaMemory(theEnv,DefruleBinaryData(theEnv)->JoinArray[i].beta); } + { + FlushBetaMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i],LHS); + ReturnLeftMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i]); + FlushBetaMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i],RHS); + ReturnRightMemory(theEnv,&DefruleBinaryData(theEnv)->JoinArray[i]); + } /*================================================*/ /* Decrement the symbol count for each rule name. */ @@ -860,16 +1097,23 @@ static void ClearBload( /*==================================================*/ space = DefruleBinaryData(theEnv)->NumberOfDefruleModules * sizeof(struct defruleModule); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->ModuleArray,space); DefruleBinaryData(theEnv)->NumberOfDefruleModules = 0; - + space = DefruleBinaryData(theEnv)->NumberOfDefrules * sizeof(struct defrule); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->DefruleArray,space); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->DefruleArray,space); DefruleBinaryData(theEnv)->NumberOfDefrules = 0; - + space = DefruleBinaryData(theEnv)->NumberOfJoins * sizeof(struct joinNode); - if (space != 0) genlongfree(theEnv,(void *) DefruleBinaryData(theEnv)->JoinArray,space); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->JoinArray,space); DefruleBinaryData(theEnv)->NumberOfJoins = 0; + + space = DefruleBinaryData(theEnv)->NumberOfLinks * sizeof(struct joinLink); + if (space != 0) genfree(theEnv,(void *) DefruleBinaryData(theEnv)->LinkArray,space); + DefruleBinaryData(theEnv)->NumberOfLinks = 0; + + DefruleData(theEnv)->RightPrimeJoins = NULL; + DefruleData(theEnv)->LeftPrimeJoins = NULL; } /*******************************************************/ diff --git a/src/rulebin.h b/src/rulebin.h index 0a3ea2d..0de5db4 100644 --- a/src/rulebin.h +++ b/src/rulebin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFRULE BSAVE/BLOAD HEADER FILE */ /*******************************************************/ @@ -14,10 +14,22 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES, */ +/* DYNAMIC_SALIENCE, and LOGICAL_DEPENDENCIES */ +/* compilation flags. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Added support for alpha memories. */ +/* */ +/* Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ /*************************************************************/ #if (! RUN_TIME) @@ -48,6 +60,7 @@ struct bsaveDefrule struct bsavePatternNodeHeader { long entryJoin; + long rightHash; unsigned int singlefieldNode : 1; unsigned int multifieldNode : 1; unsigned int stopNode : 1; @@ -56,6 +69,7 @@ struct bsavePatternNodeHeader unsigned int marked : 1; unsigned int beginSlot : 1; unsigned int endSlot : 1; + unsigned int selector : 1; }; struct bsaveDefruleModule @@ -63,40 +77,56 @@ struct bsaveDefruleModule struct bsaveDefmoduleItemHeader header; }; +struct bsaveJoinLink + { + char enterDirection; + long join; + long next; + }; + struct bsaveJoinNode { unsigned int firstJoin : 1; unsigned int logicalJoin : 1; unsigned int joinFromTheRight : 1; unsigned int patternIsNegated : 1; + unsigned int patternIsExists : 1; unsigned int rhsType : 3; unsigned int depth : 7; long networkTest; + long secondaryNetworkTest; + long leftHash; + long rightHash; long rightSideEntryStructure; - long nextLevel; + long nextLinks; long lastLevel; - long rightDriveNode; long rightMatchNode; long ruleToActivate; }; - + #define RULEBIN_DATA 20 struct defruleBinaryData - { + { long NumberOfDefruleModules; long NumberOfDefrules; long NumberOfJoins; + long NumberOfLinks; + long RightPrimeIndex; + long LeftPrimeIndex; struct defruleModule *ModuleArray; struct defrule *DefruleArray; struct joinNode *JoinArray; + struct joinLink *LinkArray; }; #define DefruleBinaryData(theEnv) ((struct defruleBinaryData *) GetEnvironmentData(theEnv,RULEBIN_DATA)) -#define BloadDefrulePointer(x,i) ((struct defrule *) (( i == -1L) ? NULL : &x[i])) +#define BloadDefrulePointer(x,i) ((struct defrule *) ((i == -1L) ? NULL : &x[i])) #define BsaveJoinIndex(joinPtr) ((joinPtr == NULL) ? -1L : ((struct joinNode *) joinPtr)->bsaveID) #define BloadJoinPointer(i) ((struct joinNode *) ((i == -1L) ? NULL : &DefruleBinaryData(theEnv)->JoinArray[i])) +#define BsaveJoinLinkIndex(linkPtr) ((linkPtr == NULL) ? -1L : ((struct joinLink *) linkPtr)->bsaveID) +#define BloadJoinLinkPointer(i) ((struct joinLink *) ((i == -1L) ? NULL : &DefruleBinaryData(theEnv)->LinkArray[i])) #ifdef LOCALE #undef LOCALE @@ -111,12 +141,13 @@ struct defruleBinaryData LOCALE void DefruleBinarySetup(void *); LOCALE void UpdatePatternNodeHeader(void *,struct patternNodeHeader *, struct bsavePatternNodeHeader *); - LOCALE void AssignBsavePatternHeaderValues(struct bsavePatternNodeHeader *, - struct patternNodeHeader *); + LOCALE void AssignBsavePatternHeaderValues(void *,struct bsavePatternNodeHeader *, + struct patternNodeHeader *); LOCALE void *BloadDefruleModuleReference(void *,int); -#endif -#endif +#endif /* _H_rulebin */ + +#endif /* (! RUN_TIME) */ diff --git a/src/rulebld.c b/src/rulebld.c index 68b105f..439f879 100644 --- a/src/rulebld.c +++ b/src/rulebld.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE BUILD MODULE */ /*******************************************************/ @@ -26,6 +26,10 @@ /* */ /* Corrected code to remove compiler warnings. */ /* */ +/* 6.30: Changes to constructing join network. */ +/* */ +/* Added support for hashed memories. */ +/* */ /*************************************************************/ #define _RULEBLD_SOURCE_ @@ -48,20 +52,21 @@ #include "reteutil.h" #include "router.h" #include "rulebld.h" +#include "rulepsr.h" #include "watch.h" /***************************************/ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct joinNode *FindShareableJoin(struct joinNode *,void *,unsigned,unsigned,int, - struct expr *, - int,int,int,struct joinNode **); - static int TestJoinForReuse(struct joinNode *,unsigned,unsigned,int, - struct expr *, - int,int,int,struct joinNode **); - static struct joinNode *CreateNewJoin(void *,struct expr *, - struct joinNode *,void *,int,int); + static struct joinNode *FindShareableJoin(struct joinLink *,struct joinNode *,intBool,void *,unsigned,unsigned, + unsigned,unsigned,struct expr *,struct expr *, + struct expr *,struct expr *); + static int TestJoinForReuse(struct joinNode *,unsigned,unsigned, + unsigned,unsigned,struct expr *,struct expr *, + struct expr *,struct expr *); + static struct joinNode *CreateNewJoin(void *,struct expr *,struct expr *,struct joinNode *,void *, + int,int,int,struct expr *,struct expr *); static void AttachTestCEsToPatternCEs(void *,struct lhsParseNode *); /****************************************************************/ @@ -71,21 +76,27 @@ globle struct joinNode *ConstructJoins( void *theEnv, int logicalJoin, - struct lhsParseNode *theLHS) + struct lhsParseNode *theLHS, + int startDepth, + struct joinNode *lastJoin, + int tryToReuse, + int firstJoin) { - struct joinNode *lastJoin = NULL; struct patternNodeHeader *lastPattern; - unsigned firstJoin = TRUE; - int tryToReuse = TRUE; - struct joinNode *listOfJoins; + struct joinNode *listOfJoins = NULL; struct joinNode *oldJoin; int joinNumber = 1; - int isLogical; - struct joinNode *nandReconnect[32]; - int currentDepth = 1; + int isLogical, isExists; + struct joinNode *lastRightJoin; int lastIteration = FALSE; int rhsType; - int endDepth; + struct expr *leftHash, *rightHash; + void *rhsStruct; + struct lhsParseNode *nextLHS; + struct expr *networkTest, *secondaryNetworkTest, *secondaryExternalTest; + int joinFromTheRight; + struct joinLink *theLinks; + intBool useLinks; /*===================================================*/ /* Remove any test CEs from the LHS and attach their */ @@ -93,41 +104,139 @@ globle struct joinNode *ConstructJoins( /* join at the same not/and depth. */ /*===================================================*/ - AttachTestCEsToPatternCEs(theEnv,theLHS); + if (startDepth == 1) + { AttachTestCEsToPatternCEs(theEnv,theLHS); } + + if (theLHS == NULL) + { + lastJoin = FindShareableJoin(DefruleData(theEnv)->RightPrimeJoins,NULL,TRUE,NULL,TRUE, + FALSE,FALSE,FALSE,NULL,NULL,NULL,NULL); + + if (lastJoin == NULL) + { lastJoin = CreateNewJoin(theEnv,NULL,NULL,NULL,NULL,FALSE,FALSE,FALSE,NULL,NULL); } + } /*=====================================================*/ /* Process each pattern CE in the rule. At this point, */ - /* there should be no and/or/not/test CEs in the LHS. */ + /* there should be no and/or/not CEs in the LHS. */ /*=====================================================*/ while (theLHS != NULL) { - if (theLHS->bottom == NULL) lastIteration = TRUE; + /*======================================================*/ + /* Find the beginning of the next group of patterns. If */ + /* the current pattern is not the beginning of a "join */ + /* from the right" group of patterns, then the next */ + /* pattern is the next pattern. Otherwise skip over all */ + /* the patterns that belong to the group of subjoins. */ + /*======================================================*/ - /*==================================================*/ - /* If the pattern is the start of a new not/and CE, */ - /* then remember the join to reconnect to after the */ - /* join from the right is completed. */ - /*==================================================*/ + nextLHS = theLHS->bottom; + secondaryExternalTest = NULL; - while (theLHS->beginNandDepth > currentDepth) + if (theLHS->endNandDepth > startDepth) { - nandReconnect[currentDepth-1] = lastJoin; - currentDepth++; + while ((nextLHS != NULL) && + (nextLHS->endNandDepth > startDepth)) + { nextLHS = nextLHS->bottom; } + + /*====================================================*/ + /* Variable nextLHS is now pointing to the end of the */ + /* not/and group beginning with variable theLHS. If */ + /* the end depth of the group is less than the depth */ + /* of the current enclosing not/and group, then this */ + /* is the last iteration for the enclosing group. */ + /*====================================================*/ + + if (nextLHS != NULL) + { + if (nextLHS->endNandDepth < startDepth) + { lastIteration = TRUE; } + } + + if (nextLHS != NULL) + { nextLHS = nextLHS->bottom; } + + if ((nextLHS != NULL) && (nextLHS->type == TEST_CE) && (nextLHS->beginNandDepth >= startDepth)) + { + secondaryExternalTest = nextLHS->networkTest; + nextLHS = nextLHS->bottom; + } } - /*============================================================*/ - /* Add the next pattern for this rule to the pattern network. */ - /*============================================================*/ + /*=======================================*/ + /* Is this the last pattern to be added? */ + /*=======================================*/ + + if (nextLHS == NULL) + { lastIteration = TRUE; } + else if (theLHS->endNandDepth < startDepth) + { lastIteration = TRUE; } + else if ((nextLHS->type == TEST_CE) && + (theLHS->beginNandDepth > startDepth) && + (nextLHS->endNandDepth < startDepth)) + { lastIteration = TRUE; } + + /*===============================================*/ + /* If the pattern is a join from the right, then */ + /* construct the subgroup of patterns and use */ + /* that as the RHS of the join to be added. */ + /*===============================================*/ + + if (theLHS->beginNandDepth > startDepth) + { + joinFromTheRight = TRUE; + isExists = theLHS->existsNand; + + lastRightJoin = ConstructJoins(theEnv,logicalJoin,theLHS,startDepth+1,lastJoin,tryToReuse,firstJoin); + + rhsStruct = lastRightJoin; + rhsType = 0; + lastPattern = NULL; + networkTest = theLHS->externalNetworkTest; + secondaryNetworkTest = secondaryExternalTest; + leftHash = theLHS->externalLeftHash; + rightHash = theLHS->externalRightHash; + } - rhsType = theLHS->patternType->positionInArray; - lastPattern = (*theLHS->patternType->addPatternFunction)(theEnv,theLHS); + /*=======================================================*/ + /* Otherwise, add the pattern to the appropriate pattern */ + /* network and use the pattern node containing the alpha */ + /* memory as the RHS of the join to be added. */ + /*=======================================================*/ + + else if (theLHS->right == NULL) + { + joinFromTheRight = FALSE; + rhsType = 0; + lastPattern = NULL; + rhsStruct = NULL; + lastRightJoin = NULL; + isExists = theLHS->exists; + networkTest = theLHS->networkTest; + secondaryNetworkTest = theLHS->secondaryNetworkTest; + leftHash = NULL; + rightHash = NULL; + } + else + { + joinFromTheRight = FALSE; + rhsType = theLHS->patternType->positionInArray; + lastPattern = (*theLHS->patternType->addPatternFunction)(theEnv,theLHS); + rhsStruct = lastPattern; + lastRightJoin = NULL; + isExists = theLHS->exists; + networkTest = theLHS->networkTest; + secondaryNetworkTest = theLHS->secondaryNetworkTest; + leftHash = theLHS->leftHash; + rightHash = theLHS->rightHash; + } /*======================================================*/ /* Determine if the join being added is a logical join. */ /*======================================================*/ - if (joinNumber == logicalJoin) isLogical = TRUE; + if ((startDepth == 1) && (joinNumber == logicalJoin)) isLogical = TRUE; else isLogical = FALSE; /*===============================================*/ @@ -135,22 +244,29 @@ globle struct joinNode *ConstructJoins( /* be reused in place of the join being added. */ /*===============================================*/ - if (firstJoin == TRUE) - { listOfJoins = lastPattern->entryJoin; } + useLinks = TRUE; + if (lastJoin != NULL) + { theLinks = lastJoin->nextLinks; } + else if (theLHS->right == NULL) + { theLinks = DefruleData(theEnv)->RightPrimeJoins; } + else if (lastPattern != NULL) + { + listOfJoins = lastPattern->entryJoin; + theLinks = NULL; + useLinks = FALSE; + } else - { listOfJoins = lastJoin->nextLevel; } + { theLinks = lastRightJoin->nextLinks; } /*=======================================================*/ /* Determine if the next join to be added can be shared. */ /*=======================================================*/ - endDepth = theLHS->endNandDepth; if ((tryToReuse == TRUE) && - ((oldJoin = FindShareableJoin(listOfJoins,(void *) lastPattern,firstJoin, - theLHS->negated,isLogical, - theLHS->networkTest, - endDepth,currentDepth, - lastIteration,nandReconnect)) != NULL) ) + ((oldJoin = FindShareableJoin(theLinks,listOfJoins,useLinks,rhsStruct,firstJoin, + theLHS->negated,isExists,isLogical, + networkTest,secondaryNetworkTest, + leftHash,rightHash)) != NULL) ) { #if DEBUGGING_FUNCTIONS if ((EnvGetWatchItem(theEnv,"compilations") == TRUE) && GetPrintWhileLoading(theEnv)) @@ -161,54 +277,59 @@ globle struct joinNode *ConstructJoins( else { tryToReuse = FALSE; - lastJoin = CreateNewJoin(theEnv,theLHS->networkTest, - lastJoin,lastPattern, - FALSE,(int) theLHS->negated); - lastJoin->rhsType = rhsType; - } - - /*==========================================================*/ - /* Create any joins from the right needed to handle not/and */ - /* CE combinations and connect them to the join network. */ - /*==========================================================*/ - - while (endDepth < currentDepth) - { - currentDepth--; - - if (lastJoin->nextLevel == NULL) tryToReuse = FALSE; - - if (tryToReuse) + if (! joinFromTheRight) { -#if DEBUGGING_FUNCTIONS - if ((EnvGetWatchItem(theEnv,"compilations") == TRUE) && GetPrintWhileLoading(theEnv)) - { EnvPrintRouter(theEnv,WDIALOG,"=j"); } -#endif - lastJoin = lastJoin->nextLevel; + lastJoin = CreateNewJoin(theEnv,networkTest,secondaryNetworkTest,lastJoin, + lastPattern,FALSE,(int) theLHS->negated, isExists, + leftHash,rightHash); + lastJoin->rhsType = rhsType; } else { - lastJoin = CreateNewJoin(theEnv,NULL,nandReconnect[currentDepth-1], - lastJoin,TRUE,FALSE); + lastJoin = CreateNewJoin(theEnv,networkTest,secondaryNetworkTest,lastJoin, + lastRightJoin,TRUE,(int) theLHS->negated, isExists, + leftHash,rightHash); + lastJoin->rhsType = rhsType; } } + /*============================================*/ + /* If we've reached the end of the subgroup, */ + /* then return the last join of the subgroup. */ + /*============================================*/ + + if (lastIteration) + { break; } + /*=======================================*/ /* Move on to the next join to be added. */ /*=======================================*/ - theLHS = theLHS->bottom; + theLHS = nextLHS; joinNumber++; firstJoin = FALSE; } + /*=================================================*/ + /* Add the final join which stores the activations */ + /* of the rule. This join is never shared. */ + /*=================================================*/ + + if (startDepth == 1) + { + lastJoin = CreateNewJoin(theEnv,NULL,NULL,lastJoin,NULL, + FALSE,FALSE,FALSE,NULL,NULL); + } + /*===================================================*/ /* If compilations are being watched, put a carriage */ /* return after all of the =j's and +j's */ /*===================================================*/ #if DEBUGGING_FUNCTIONS - if ((EnvGetWatchItem(theEnv,"compilations") == TRUE) && GetPrintWhileLoading(theEnv)) + if ((startDepth == 1) && + (EnvGetWatchItem(theEnv,"compilations") == TRUE) && + GetPrintWhileLoading(theEnv)) { EnvPrintRouter(theEnv,WDIALOG,"\n"); } #endif @@ -228,96 +349,546 @@ static void AttachTestCEsToPatternCEs( void *theEnv, struct lhsParseNode *theLHS) { - struct lhsParseNode *lastNode = NULL, *trackNode, *tempNode; + struct lhsParseNode *lastNode, *tempNode, *lastLastNode; - /*===============================================*/ - /* Look at each pattern on the rule's LHS to see */ - /* if any test CEs should be attached to it. */ - /*===============================================*/ + if (theLHS == NULL) return; + + /*=============================================================*/ + /* Attach test CEs that can be attached directly to a pattern. */ + /*=============================================================*/ + + lastLastNode = NULL; + lastNode = theLHS; + theLHS = lastNode->bottom; while (theLHS != NULL) { - /*==============================================*/ - /* If the pattern is negated, then don't bother */ - /* looking for any test CEs to attach to it. */ - /*==============================================*/ + /*================================================================*/ + /* Skip over any CE that's not a TEST CE as we're only interested */ + /* in attaching a TEST CE to a preceding pattern CE. Update the */ + /* variables that track the preceding pattern. */ + /*================================================================*/ - if (theLHS->negated) - { trackNode = NULL; } - else + if (theLHS->type != TEST_CE) { + lastLastNode = lastNode; lastNode = theLHS; - trackNode = theLHS->bottom; + theLHS = theLHS->bottom; + continue; } - /*=================================================*/ - /* Check all of the patterns following the current */ - /* pattern to check for test CEs which can be */ - /* attached to the current pattern. */ - /*=================================================*/ + /*=====================================================*/ + /* If this is the beginning of a new NOT/AND CE group, */ + /* then we can't attach this TEST CE to a preceding */ + /* pattern CE and should skip over it. */ + /*=====================================================*/ + + /*================================================*/ + /* Case #2 */ + /* Pattern CE */ + /* Depth Begin: N */ + /* Depth End: N */ + /* Test CE */ + /* Depth Begin: M where M > N */ + /* Depth End: - */ + /* */ + /* (defrule example */ + /* (a) */ + /* (not (and (test (> 1 0)) */ + /* (b))) */ + /* =>) */ + /* */ + /* Case #8 */ + /* Pattern CE */ + /* Depth Begin: N */ + /* Depth End: M where M < N */ + /* Test CE */ + /* Depth Begin: R where R > M */ + /* Depth End: - */ + /* */ + /* (defrule example */ + /* (not (and (a) */ + /* (c))) */ + /* (not (and (test (> 1 0)) */ + /* (b))) */ + /* =>) */ + /* */ + /* This situation will not occur with the current */ + /* implementation. The initial pattern will be */ + /* added before the test CE so that there is a */ + /* pattern CE beginning the not/and or exists/and */ + /* pattern group. */ + /*================================================*/ + + if (theLHS->beginNandDepth > lastNode->endNandDepth) + { + lastLastNode = lastNode; + lastNode = theLHS; + theLHS = theLHS->bottom; + continue; + } - while (trackNode != NULL) + /*==============================================================*/ + /* If the preceding pattern was the end of a NOT/AND CE group, */ + /* then we can't attach this TEST CE to a preceding pattern and */ + /* should skip over it. The logic for handling the test CE will */ + /* be triggered when the joins are constructed. Note that the */ + /* endNandDepth will never be greater than the beginNandDepth. */ + /*==============================================================*/ + + if (lastNode->beginNandDepth > lastNode->endNandDepth) { - /*=======================================================*/ - /* Skip over any CEs that have a higher not/and depth or */ - /* are negated since any test CEs found within these CEs */ - /* would be attached to another pattern with the same */ - /* depth, rather than the current pattern. */ - /*=======================================================*/ - - if ((trackNode->beginNandDepth != theLHS->beginNandDepth) || - (trackNode->negated)) + lastLastNode = lastNode; + lastNode = theLHS; + theLHS = theLHS->bottom; + continue; + } + + /*===================================================*/ + /* If the TEST CE does not close the preceding CE... */ + /*===================================================*/ + + /*===================================================*/ + /* Case #1 */ + /* Pattern CE */ + /* Depth Begin: N */ + /* Depth End: N */ + /* Test CE */ + /* Depth Begin: N */ + /* Depth End: N */ + /* */ + /* (defrule example */ + /* (a ?x) */ + /* (test (> ?x 0)) */ + /* =>) */ + /* */ + /* The test expression can be directly attached to */ + /* the network expression for the preceding pattern. */ + /*===================================================*/ + + if (theLHS->beginNandDepth == theLHS->endNandDepth) + { + /*==============================================================*/ + /* If the preceding pattern was a NOT or EXISTS CE containing */ + /* a single pattern, then attached the TEST CE to the secondary */ + /* test, otherwise combine it with the primary network test. */ + /*==============================================================*/ + + if (lastNode->negated) { - lastNode = trackNode; - trackNode = trackNode->bottom; + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); } + else + { + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + } + } + + /*=================================================================*/ + /* Otherwise the TEST CE closes a prior NOT/AND or EXISTS/AND CE. */ + /*=================================================================*/ + + /*==================================================*/ + /* If these are the first two patterns in the rule. */ + /*==================================================*/ - /*======================================================*/ - /* Once a non-negated pattern has been encounted at the */ - /* same not/and depth as the current pattern, then stop */ - /* because any test CEs following this pattern would be */ - /* attached to it rather than the current pattern. */ - /*======================================================*/ + /*=========*/ + /* Case #3 */ + /*=========*/ - else if (trackNode->type == PATTERN_CE) - { trackNode = NULL; } + else if (lastLastNode == NULL) + { + /*=========================================================*/ + /* The prior pattern is a single pattern within a not/and. */ + /* */ + /* (defrule example */ + /* (not (and (b) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /* Collapse the nand pattern. */ + /*=========================================================*/ + + if ((lastNode->negated == FALSE) && + (lastNode->existsNand == FALSE)) + { + lastNode->beginNandDepth = theLHS->endNandDepth; - /*==================================================*/ - /* A test CE encountered at the same not/and depth */ - /* can be added to the network test expressions for */ - /* the currentpattern. */ - /*==================================================*/ + lastNode->negated = TRUE; + + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,lastNode->externalNetworkTest); + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + lastNode->externalNetworkTest = NULL; + } - else if (trackNode->type == TEST_CE) + /*=================================================================*/ + /* The prior pattern is a single negated pattern within a not/and. */ + /* */ + /* (defrule example */ + /* (not (and (not (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /*=================================================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == FALSE)) { - theLHS->networkTest = CombineExpressions(theEnv,theLHS->networkTest, - trackNode->networkTest); - trackNode->networkTest = NULL; - tempNode = trackNode->bottom; - trackNode->bottom = NULL; - lastNode->bottom = tempNode; - lastNode->endNandDepth = trackNode->endNandDepth; - ReturnLHSParseNodes(theEnv,trackNode); - trackNode = tempNode; + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); } - /*================================================*/ - /* If none of the previous conditions have been */ - /* met, then there is an internal error. */ - /*================================================*/ + /*================================================================*/ + /* The prior pattern is a single exists pattern within a not/and. */ + /* */ + /* (defrule example */ + /* (not (and (exists (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /*================================================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == TRUE) && + (lastNode->existsNand == FALSE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*=============================================================*/ + /* The prior pattern is a single pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (exists (and (b) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /* Collapse the exists pattern. */ + /*=============================================================*/ + + else if ((lastNode->negated == FALSE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == TRUE)) + { + lastNode->beginNandDepth = theLHS->endNandDepth; + + lastNode->existsNand = FALSE; + lastNode->exists = TRUE; + lastNode->negated = TRUE; + + /*===================================================*/ + /* For the first two patterns, there shouldn't be an */ + /* externalNetwork test, but this code is included */ + /* to match the other cases where patterns are */ + /* collapsed. */ + /*===================================================*/ + + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,lastNode->externalNetworkTest); + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + lastNode->externalNetworkTest = NULL; + } + + /*=======================================*/ + /* The prior pattern is a single negated */ + /* pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (exists (and (not (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /*=======================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == TRUE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*======================================*/ + /* The prior pattern is a single exists */ + /* pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (exists (and (exists (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /* Collapse the exists pattern. */ + /*======================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == TRUE) && + (lastNode->existsNand == TRUE)) + { + lastNode->beginNandDepth = theLHS->endNandDepth; + + lastNode->existsNand = FALSE; + + /*===================================================*/ + /* For the first two patterns, there shouldn't be an */ + /* externalNetwork test, but this code is included */ + /* to match the other cases where patterns are */ + /* collapsed. */ + /*===================================================*/ + + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,lastNode->externalNetworkTest); + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + lastNode->externalNetworkTest = NULL; + } + + /*==============================================*/ + /* Unhandled case which should not be possible. */ + /*==============================================*/ else { - SystemError(theEnv,"BUILD",1); + SystemError(theEnv,"RULEBLD",1); EnvExitRouter(theEnv,EXIT_FAILURE); } } + /*==============================================*/ + /* Otherwise, there are two preceding patterns. */ + /*==============================================*/ + + /*====================================*/ + /* Case #4 */ + /* Pattern CE */ + /* Depth Begin: - */ + /* Depth End: N */ + /* Pattern CE */ + /* Depth Begin: N */ + /* Depth End: N */ + /* Test CE */ + /* Depth Begin: N */ + /* Depth End: M where M < N */ + /*====================================*/ + + else if (lastLastNode->endNandDepth == theLHS->beginNandDepth) + { + /*==============================================================*/ + /* If the preceding pattern was a NOT or EXISTS CE containing */ + /* a single pattern, then attached the TEST CE to the secondary */ + /* test, otherwise combine it with the primary network test. */ + /*==============================================================*/ + + if (lastNode->negated) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + else + { + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + } + } + /*====================================*/ - /* Check the next pattern in the LHS. */ + /* Case #5 */ + /* Pattern CE */ + /* Depth Begin: - */ + /* Depth End: R where R < N */ + /* Pattern CE */ + /* Depth Begin: N */ + /* Depth End: N */ + /* Test CE */ + /* Depth Begin: N */ + /* Depth End: M where M < N */ /*====================================*/ - theLHS = theLHS->bottom; + else if (lastLastNode->endNandDepth < theLHS->beginNandDepth) + { + /*=========================================================*/ + /* The prior pattern is a single pattern within a not/and: */ + /* */ + /* (defrule example */ + /* (a) */ + /* (not (and (b) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /* The test expression can be directly attached to the */ + /* network expression for the pattern and the pattern */ + /* group can be collapsed into a single negated pattern. */ + /*=========================================================*/ + + if ((lastNode->negated == FALSE) && + (lastNode->existsNand == FALSE)) + { + /*====================*/ + /* Use max of R and M */ + /*====================*/ + + if (lastLastNode->endNandDepth > theLHS->endNandDepth) + { lastNode->beginNandDepth = lastLastNode->endNandDepth; } + else + { lastNode->beginNandDepth = theLHS->endNandDepth; } + + lastNode->negated = TRUE; + + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,lastNode->externalNetworkTest); + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + lastNode->externalNetworkTest = NULL; + } + + /*=================================================================*/ + /* The prior pattern is a single negated pattern within a not/and. */ + /* */ + /* (defrule example */ + /* (a) */ + /* (not (and (not (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /*=================================================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == FALSE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*================================================================*/ + /* The prior pattern is a single exists pattern within a not/and. */ + /* */ + /* (defrule example */ + /* (a) */ + /* (not (and (exists (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /*================================================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == TRUE) && + (lastNode->existsNand == FALSE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*=============================================================*/ + /* The prior pattern is a single pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (a) */ + /* (exists (and (b) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /* The test expression can be directly attached to the */ + /* network expression for the pattern and the pattern */ + /* group can be collapsed into a single exists pattern. */ + /*=============================================================*/ + + else if ((lastNode->negated == FALSE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == TRUE)) + { + if (lastLastNode->endNandDepth > theLHS->endNandDepth) + { lastNode->beginNandDepth = lastLastNode->endNandDepth; } + else + { lastNode->beginNandDepth = theLHS->endNandDepth; } + + lastNode->existsNand = FALSE; + lastNode->exists = TRUE; + lastNode->negated = TRUE; + + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,lastNode->externalNetworkTest); + lastNode->networkTest = + CombineExpressions(theEnv,lastNode->networkTest,theLHS->networkTest); + lastNode->externalNetworkTest = NULL; + } + + /*=======================================*/ + /* The prior pattern is a single negated */ + /* pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (a) */ + /* (exists (and (not (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /*=======================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == FALSE) && + (lastNode->existsNand == TRUE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*======================================*/ + /* The prior pattern is a single exists */ + /* pattern within an exists/and. */ + /* */ + /* (defrule example */ + /* (a) */ + /* (exists (and (exists (b)) */ + /* (test (= 1 1)))) */ + /* =>) */ + /* */ + /*======================================*/ + + else if ((lastNode->negated == TRUE) && + (lastNode->exists == TRUE) && + (lastNode->existsNand == TRUE)) + { + lastNode->secondaryNetworkTest = + CombineExpressions(theEnv,lastNode->secondaryNetworkTest,theLHS->networkTest); + } + + /*==============================================*/ + /* Unhandled case which should not be possible. */ + /*==============================================*/ + + else + { + SystemError(theEnv,"RULEBLD",2); + EnvExitRouter(theEnv,EXIT_FAILURE); + } + } + + /*==============================================*/ + /* Unhandled case which should not be possible. */ + /*==============================================*/ + + else + { + SystemError(theEnv,"RULEBLD",3); + EnvExitRouter(theEnv,EXIT_FAILURE); + } + + /*=================================================*/ + /* Remove the TEST CE and continue to the next CE. */ + /*=================================================*/ + + theLHS->networkTest = NULL; + tempNode = theLHS->bottom; + theLHS->bottom = NULL; + lastNode->bottom = tempNode; + lastNode->endNandDepth = theLHS->endNandDepth; + ReturnLHSParseNodes(theEnv,theLHS); + theLHS = tempNode; } } @@ -328,22 +899,32 @@ static void AttachTestCEsToPatternCEs( /* otherwise returns a NULL pointer. */ /********************************************************************/ static struct joinNode *FindShareableJoin( + struct joinLink *theLinks, struct joinNode *listOfJoins, + intBool useLinks, void *rhsStruct, unsigned int firstJoin, unsigned int negatedRHS, - int isLogical, + unsigned int existsRHS, + unsigned int isLogical, struct expr *joinTest, - int endDepth, - int currentDepth, - int lastIteration, - struct joinNode **nandReconnect) + struct expr *secondaryJoinTest, + struct expr *leftHash, + struct expr *rightHash) { /*========================================*/ /* Loop through all of the joins in the */ /* list of potential candiates for reuse. */ /*========================================*/ + if (useLinks) + { + if (theLinks != NULL) + { listOfJoins = theLinks->join; } + else + { listOfJoins = NULL; } + } + while (listOfJoins != NULL) { /*=========================================================*/ @@ -355,9 +936,9 @@ static struct joinNode *FindShareableJoin( if (listOfJoins->rightSideEntryStructure == rhsStruct) { - if (TestJoinForReuse(listOfJoins,firstJoin,negatedRHS,isLogical, - joinTest,endDepth,currentDepth, - lastIteration,nandReconnect)) + if (TestJoinForReuse(listOfJoins,firstJoin,negatedRHS,existsRHS, + isLogical,joinTest,secondaryJoinTest, + leftHash,rightHash)) { return(listOfJoins); } } @@ -370,10 +951,16 @@ static struct joinNode *FindShareableJoin( /* joins of a rule. */ /*====================================================*/ - if (firstJoin) - { listOfJoins = listOfJoins->rightMatchNode; } + if (useLinks) + { + theLinks = theLinks->next; + if (theLinks != NULL) + { listOfJoins = theLinks->join; } + else + { listOfJoins = NULL; } + } else - { listOfJoins = listOfJoins->rightDriveNode; } + { listOfJoins = listOfJoins->rightMatchNode; } } /*================================*/ @@ -393,12 +980,12 @@ static int TestJoinForReuse( struct joinNode *testJoin, unsigned firstJoin, unsigned negatedRHS, - int isLogical, + unsigned existsRHS, + unsigned int isLogical, struct expr *joinTest, - int endDepth, - int currentDepth, - int lastIteration, - struct joinNode **nandReconnect) + struct expr *secondaryJoinTest, + struct expr *leftHash, + struct expr *rightHash) { /*==================================================*/ /* The first join of a rule may only be shared with */ @@ -412,7 +999,14 @@ static int TestJoinForReuse( /* join that has its patternIsNegated field set to TRUE. */ /*========================================================*/ - if (testJoin->patternIsNegated != negatedRHS) return(FALSE); + if ((testJoin->patternIsNegated != negatedRHS) && (! existsRHS)) return(FALSE); + + /*==========================================================*/ + /* A join connected to an exists CE may only be shared with */ + /* a join that has its patternIsExists field set to TRUE. */ + /*==========================================================*/ + + if (testJoin->patternIsExists != existsRHS) return(FALSE); /*==========================================================*/ /* If the join added is associated with a logical CE, then */ @@ -423,7 +1017,7 @@ static int TestJoinForReuse( if ((isLogical == TRUE) && (testJoin->logicalJoin == FALSE) && - (testJoin->beta != NULL)) + BetaMemoryNotEmpty(testJoin)) { return(FALSE); } /*===============================================================*/ @@ -434,57 +1028,19 @@ static int TestJoinForReuse( if (IdenticalExpression(testJoin->networkTest,joinTest) != TRUE) { return(FALSE); } - /*==============================================================*/ - /* If the join being added enters another join from the right, */ - /* then the series of "joins from the right" for the join being */ - /* added must match the series of "joins from the right" for */ - /* the join being tested for reuse (i.e. the LHS connections */ - /* from other joins must be identical for each of the joins in */ - /* the series of "joins from the right." */ - /*==============================================================*/ - - for (; endDepth < currentDepth; currentDepth--) - { - testJoin = testJoin->nextLevel; - if (testJoin == NULL) return(FALSE); - - if (testJoin->joinFromTheRight == FALSE) - { return(FALSE); } - else if (nandReconnect[currentDepth-2] != testJoin->lastLevel) - { return(FALSE); } - } - - /*=============================================================*/ - /* The last join of a rule cannot be shared with the last join */ - /* of another rule. A join cannot be used as the last join of */ - /* a rule if it already has partial matches in its beta memory */ - /* (because of the extra slot used to point at activations). */ - /*=============================================================*/ - - if (lastIteration) - { - if (testJoin->ruleToActivate != NULL) return(FALSE); + if (IdenticalExpression(testJoin->secondaryNetworkTest,secondaryJoinTest) != TRUE) + { return(FALSE); } - if (testJoin->beta != NULL) return(FALSE); - } + /*====================================================================*/ + /* The alpha memory hashing values associated with the join must be */ + /* identical to the hashing values stored with the join to be shared. */ + /*====================================================================*/ - /*===========================================================================*/ - /* A join cannot be shared if it is not the last join for a rule and shares */ - /* part, but not all, of a series of joins connected to other joins from the */ - /* right. This is because the data structure for joins can only point to */ - /* either a single join that is entered from the right or a series of joins */ - /* that are entered from the left, but not both. (The last join of a rule */ - /* does not require any links to other joins so it can be shared). */ - /*===========================================================================*/ + if (IdenticalExpression(testJoin->leftHash,leftHash) != TRUE) + { return(FALSE); } - if ((! lastIteration) && (testJoin->nextLevel != NULL)) - { - if (testJoin->nextLevel->joinFromTheRight == TRUE) - { - if (((struct joinNode *) testJoin->nextLevel->rightSideEntryStructure) == testJoin) - { return(FALSE); } - } - } + if (IdenticalExpression(testJoin->rightHash,rightHash) != TRUE) + { return(FALSE); } /*=============================================*/ /* The join can be shared since all conditions */ @@ -500,12 +1056,17 @@ static int TestJoinForReuse( static struct joinNode *CreateNewJoin( void *theEnv, struct expr *joinTest, + struct expr *secondaryJoinTest, struct joinNode *lhsEntryStruct, void *rhsEntryStruct, int joinFromTheRight, - int negatedRHSPattern) + int negatedRHSPattern, + int existsRHSPattern, + struct expr *leftHash, + struct expr *rightHash) { struct joinNode *newJoin; + struct joinLink *theLink; /*===============================================*/ /* If compilations are being watch, print +j to */ @@ -519,18 +1080,111 @@ static struct joinNode *CreateNewJoin( { EnvPrintRouter(theEnv,WDIALOG,"+j"); } #endif - /*========================================================*/ - /* Create the new join and initialize some of its values. */ - /*========================================================*/ + /*======================*/ + /* Create the new join. */ + /*======================*/ newJoin = get_struct(theEnv,joinNode); - newJoin->beta = NULL; - newJoin->nextLevel = NULL; + + /*======================================================*/ + /* The first join of a rule does not have a beta memory */ + /* unless the RHS pattern is an exists or not CE. */ + /*======================================================*/ + + if ((lhsEntryStruct != NULL) || existsRHSPattern || negatedRHSPattern || joinFromTheRight) + { + if (leftHash == NULL) + { + newJoin->leftMemory = get_struct(theEnv,betaMemory); + newJoin->leftMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + newJoin->leftMemory->beta[0] = NULL; + newJoin->leftMemory->last = NULL; + newJoin->leftMemory->size = 1; + newJoin->leftMemory->count = 0; + } + else + { + newJoin->leftMemory = get_struct(theEnv,betaMemory); + newJoin->leftMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + memset(newJoin->leftMemory->beta,0,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + newJoin->leftMemory->last = NULL; + newJoin->leftMemory->size = INITIAL_BETA_HASH_SIZE; + newJoin->leftMemory->count = 0; + } + + /*===========================================================*/ + /* If the first join of a rule connects to an exists or not */ + /* CE, then we create an empty partial match for the usually */ + /* empty left beta memory so that we can track the current */ + /* current right memory partial match satisfying the CE. */ + /*===========================================================*/ + + if ((lhsEntryStruct == NULL) && (existsRHSPattern || negatedRHSPattern || joinFromTheRight)) + { + newJoin->leftMemory->beta[0] = CreateEmptyPartialMatch(theEnv); + newJoin->leftMemory->beta[0]->owner = newJoin; + newJoin->leftMemory->count = 1; + } + } + else + { newJoin->leftMemory = NULL; } + + if (joinFromTheRight) + { + if (leftHash == NULL) + { + newJoin->rightMemory = get_struct(theEnv,betaMemory); + newJoin->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + newJoin->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + newJoin->rightMemory->beta[0] = NULL; + newJoin->rightMemory->last[0] = NULL; + newJoin->rightMemory->size = 1; + newJoin->rightMemory->count = 0; + } + else + { + newJoin->rightMemory = get_struct(theEnv,betaMemory); + newJoin->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + newJoin->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + memset(newJoin->rightMemory->beta,0,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + memset(newJoin->rightMemory->last,0,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + newJoin->rightMemory->size = INITIAL_BETA_HASH_SIZE; + newJoin->rightMemory->count = 0; + } + } + else if (rhsEntryStruct == NULL) + { + newJoin->rightMemory = get_struct(theEnv,betaMemory); + newJoin->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + newJoin->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + newJoin->rightMemory->beta[0] = CreateEmptyPartialMatch(theEnv); + newJoin->rightMemory->beta[0]->owner = newJoin; + newJoin->rightMemory->beta[0]->rhsMemory = TRUE; + newJoin->rightMemory->last[0] = newJoin->rightMemory->beta[0]; + newJoin->rightMemory->size = 1; + newJoin->rightMemory->count = 1; + } + else + { newJoin->rightMemory = NULL; } + + newJoin->nextLinks = NULL; newJoin->joinFromTheRight = joinFromTheRight; - newJoin->patternIsNegated = negatedRHSPattern; + + if (existsRHSPattern) + { newJoin->patternIsNegated = FALSE; } + else + { newJoin->patternIsNegated = negatedRHSPattern; } + newJoin->patternIsExists = existsRHSPattern; + + newJoin->marked = FALSE; newJoin->initialize = EnvGetIncrementalReset(theEnv); newJoin->logicalJoin = FALSE; newJoin->ruleToActivate = NULL; + newJoin->memoryLeftAdds = 0; + newJoin->memoryRightAdds = 0; + newJoin->memoryLeftDeletes = 0; + newJoin->memoryRightDeletes = 0; + newJoin->memoryCompares = 0; /*==============================================*/ /* Install the expressions used to determine */ @@ -539,6 +1193,16 @@ static struct joinNode *CreateNewJoin( /*==============================================*/ newJoin->networkTest = AddHashedExpression(theEnv,joinTest); + newJoin->secondaryNetworkTest = AddHashedExpression(theEnv,secondaryJoinTest); + + /*=====================================================*/ + /* Install the expression used to hash the beta memory */ + /* partial match to determine the location to search */ + /* in the alpha memory. */ + /*=====================================================*/ + + newJoin->leftHash = AddHashedExpression(theEnv,leftHash); + newJoin->rightHash = AddHashedExpression(theEnv,rightHash); /*============================================================*/ /* Initialize the values associated with the LHS of the join. */ @@ -550,15 +1214,40 @@ static struct joinNode *CreateNewJoin( { newJoin->firstJoin = TRUE; newJoin->depth = 1; - newJoin->rightDriveNode = NULL; } else { newJoin->firstJoin = FALSE; newJoin->depth = lhsEntryStruct->depth; newJoin->depth++; /* To work around Sparcworks C compiler bug */ - newJoin->rightDriveNode = lhsEntryStruct->nextLevel; - lhsEntryStruct->nextLevel = newJoin; + + theLink = get_struct(theEnv,joinLink); + theLink->join = newJoin; + theLink->enterDirection = LHS; + + /*==============================================================*/ + /* If this is a join from the right, then there should already */ + /* be a link from the previous join to the other join in the */ + /* the bifurcated path through the join network. If so, we want */ + /* add the next link to the join from the right so that it is */ + /* visited after the other path. Doing this will reduce the */ + /* number of activations added and then removed if the other */ + /* path were followed first. The other path generates the */ + /* partial matches which are negated by this path, so if that */ + /* path is processed first, the partial matches from that path */ + /* will prevent partial matches on this path. */ + /*==============================================================*/ + + if ((joinFromTheRight) && (lhsEntryStruct->nextLinks != NULL)) + { + theLink->next = lhsEntryStruct->nextLinks->next; + lhsEntryStruct->nextLinks->next = theLink; + } + else + { + theLink->next = lhsEntryStruct->nextLinks; + lhsEntryStruct->nextLinks = theLink; + } } /*=======================================================*/ @@ -569,10 +1258,47 @@ static struct joinNode *CreateNewJoin( newJoin->rightSideEntryStructure = rhsEntryStruct; + if (rhsEntryStruct == NULL) + { + if (newJoin->firstJoin) + { + theLink = get_struct(theEnv,joinLink); + theLink->join = newJoin; + theLink->enterDirection = RHS; + theLink->next = DefruleData(theEnv)->RightPrimeJoins; + DefruleData(theEnv)->RightPrimeJoins = theLink; + } + + newJoin->rightMatchNode = NULL; + + return(newJoin); + } + + /*===========================================================*/ + /* If the first join of a rule is a not CE, then it needs to */ + /* be "primed" under certain circumstances. This used to be */ + /* handled by adding the (initial-fact) pattern to a rule */ + /* with the not CE as its first pattern, but this alternate */ + /* mechanism is now used so patterns don't have to be added. */ + /*===========================================================*/ + + if (newJoin->firstJoin && (newJoin->patternIsNegated || newJoin->joinFromTheRight) && (! newJoin->patternIsExists)) + { + theLink = get_struct(theEnv,joinLink); + theLink->join = newJoin; + theLink->enterDirection = LHS; + theLink->next = DefruleData(theEnv)->LeftPrimeJoins; + DefruleData(theEnv)->LeftPrimeJoins = theLink; + } + if (joinFromTheRight) { + theLink = get_struct(theEnv,joinLink); + theLink->join = newJoin; + theLink->enterDirection = RHS; + theLink->next = ((struct joinNode *) rhsEntryStruct)->nextLinks; + ((struct joinNode *) rhsEntryStruct)->nextLinks = theLink; newJoin->rightMatchNode = NULL; - ((struct joinNode *) rhsEntryStruct)->nextLevel = newJoin; } else { diff --git a/src/rulebld.h b/src/rulebld.h index 7df40ea..0917617 100644 --- a/src/rulebld.h +++ b/src/rulebld.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE BUILD HEADER FILE */ /*******************************************************/ @@ -22,6 +22,14 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Removed INCREMENTAL_RESET compilation flag. */ +/* */ +/* Corrected code to remove compiler warnings. */ +/* */ +/* 6.30: Changes to constructing join network. */ +/* */ +/* Added support for hashed memories. */ +/* */ /*************************************************************/ #ifndef _H_rulebld @@ -45,9 +53,9 @@ #define LOCALE extern #endif - LOCALE struct joinNode *ConstructJoins(void *,int,struct lhsParseNode *); + LOCALE struct joinNode *ConstructJoins(void *,int,struct lhsParseNode *,int,struct joinNode *,int,int); -#endif +#endif /* _H_rulebld */ diff --git a/src/rulebsc.c b/src/rulebsc.c index c62b235..7904ab6 100644 --- a/src/rulebsc.c +++ b/src/rulebsc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* DEFRULE BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -16,9 +16,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ @@ -28,6 +29,21 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for join network changes. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* JoinOperationInProgress mechanism. */ +/* */ /*************************************************************/ #define _RULEBSC_SOURCE_ @@ -47,6 +63,8 @@ #include "extnfunc.h" #include "ruledef.h" #include "engine.h" +#include "drive.h" +#include "reteutil.h" #if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE #include "rulebin.h" #endif @@ -61,7 +79,8 @@ /***************************************/ static void ResetDefrules(void *); - static void SaveDefrules(void *,void *,char *); + static void ResetDefrulesPrime(void *); + static void SaveDefrules(void *,void *,const char *); #if (! RUN_TIME) static int ClearDefrulesReady(void *); static void ClearDefrules(void *); @@ -74,12 +93,13 @@ globle void DefruleBasicCommands( void *theEnv) { EnvAddResetFunction(theEnv,"defrule",ResetDefrules,70); + EnvAddResetFunction(theEnv,"defrule",ResetDefrulesPrime,10); AddSaveFunction(theEnv,"defrule",SaveDefrules,0); #if (! RUN_TIME) AddClearReadyFunction(theEnv,"defrule",ClearDefrulesReady,0); EnvAddClearFunction(theEnv,"defrule",ClearDefrules,0); #endif - + #if DEBUGGING_FUNCTIONS AddWatchItem(theEnv,"rules",0,&DefruleData(theEnv)->WatchRules,70,DefruleWatchAccess,DefruleWatchPrint); #endif @@ -117,11 +137,81 @@ static void ResetDefrules( void *theEnv) { struct defmodule *theModule; - - DefruleData(theEnv)->CurrentEntityTimeTag = 0L; + struct joinLink *theLink; + struct partialMatch *notParent; + + DefruleData(theEnv)->CurrentEntityTimeTag = 1L; EnvClearFocusStack(theEnv); theModule = (struct defmodule *) EnvFindDefmodule(theEnv,"MAIN"); EnvFocus(theEnv,(void *) theModule); + + for (theLink = DefruleData(theEnv)->RightPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { PosEntryRetractAlpha(theEnv,theLink->join->rightMemory->beta[0],NETWORK_ASSERT); } + + for (theLink = DefruleData(theEnv)->LeftPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { + if ((theLink->join->patternIsNegated || theLink->join->joinFromTheRight) && + (! theLink->join->patternIsExists)) + { + notParent = theLink->join->leftMemory->beta[0]; + + if (notParent->marker) + { RemoveBlockedLink(notParent); } + + /*==========================================================*/ + /* Prevent any retractions from generating partial matches. */ + /*==========================================================*/ + + notParent->marker = notParent; + + if (notParent->children != NULL) + { PosEntryRetractBeta(theEnv,notParent,notParent->children,NETWORK_ASSERT); } + /* + if (notParent->dependents != NULL) + { RemoveLogicalSupport(theEnv,notParent); } */ + } + } + } + +/*****************************************************/ +/* ResetDefrulesPrime: */ +/*****************************************************/ +static void ResetDefrulesPrime( + void *theEnv) + { + struct joinLink *theLink; + struct partialMatch *notParent; + + for (theLink = DefruleData(theEnv)->RightPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { NetworkAssert(theEnv,theLink->join->rightMemory->beta[0],theLink->join); } + + for (theLink = DefruleData(theEnv)->LeftPrimeJoins; + theLink != NULL; + theLink = theLink->next) + { + if ((theLink->join->patternIsNegated || theLink->join->joinFromTheRight) && + (! theLink->join->patternIsExists)) + { + notParent = theLink->join->leftMemory->beta[0]; + + if (theLink->join->secondaryNetworkTest != NULL) + { + if (EvaluateSecondaryNetworkTest(theEnv,notParent,theLink->join) == FALSE) + { continue; } + } + + notParent->marker = NULL; + + EPMDrive(theEnv,notParent,theLink->join,NETWORK_ASSERT); + } + } + } #if (! RUN_TIME) @@ -133,11 +223,13 @@ static int ClearDefrulesReady( void *theEnv) { if (EngineData(theEnv)->ExecutingRule != NULL) return(FALSE); - + + if (EngineData(theEnv)->JoinOperationInProgress) return(FALSE); + EnvClearFocusStack(theEnv); if (EnvGetCurrentModule(theEnv) == NULL) return(FALSE); - DefruleData(theEnv)->CurrentEntityTimeTag = 0L; + DefruleData(theEnv)->CurrentEntityTimeTag = 1L; return(TRUE); } @@ -153,6 +245,7 @@ static void ClearDefrules( theModule = (struct defmodule *) EnvFindDefmodule(theEnv,"MAIN"); EnvFocus(theEnv,(void *) theModule); } + #endif /**************************************/ @@ -162,9 +255,9 @@ static void ClearDefrules( static void SaveDefrules( void *theEnv, void *theModule, - char *logicalName) + const char *logicalName) { - SaveConstruct(theEnv,theModule,logicalName,DefruleData(theEnv)->DefruleConstruct); + SaveConstruct(theEnv,theModule,logicalName,DefruleData(theEnv)->DefruleConstruct); } /******************************************/ @@ -173,8 +266,8 @@ static void SaveDefrules( /******************************************/ globle void UndefruleCommand( void *theEnv) - { - UndefconstructCommand(theEnv,"undefrule",DefruleData(theEnv)->DefruleConstruct); + { + UndefconstructCommand(theEnv,"undefrule",DefruleData(theEnv)->DefruleConstruct); } /**********************************/ @@ -185,7 +278,7 @@ globle intBool EnvUndefrule( void *theEnv, void *theDefrule) { - return(Undefconstruct(theEnv,theDefrule,DefruleData(theEnv)->DefruleConstruct)); + return(Undefconstruct(theEnv,theDefrule,DefruleData(theEnv)->DefruleConstruct)); } /************************************************/ @@ -196,7 +289,7 @@ globle void GetDefruleListFunction( void *theEnv, DATA_OBJECT_PTR returnValue) { - GetConstructListFunction(theEnv,"get-defrule-list",returnValue,DefruleData(theEnv)->DefruleConstruct); + GetConstructListFunction(theEnv,"get-defrule-list",returnValue,DefruleData(theEnv)->DefruleConstruct); } /****************************************/ @@ -218,7 +311,7 @@ globle void EnvGetDefruleList( globle void *DefruleModuleFunction( void *theEnv) { - return(GetConstructModuleCommand(theEnv,"defrule-module",DefruleData(theEnv)->DefruleConstruct)); + return(GetConstructModuleCommand(theEnv,"defrule-module",DefruleData(theEnv)->DefruleConstruct)); } #if DEBUGGING_FUNCTIONS @@ -239,8 +332,8 @@ globle void PPDefruleCommand( /***********************************/ globle int PPDefrule( void *theEnv, - char *defruleName, - char *logicalName) + const char *defruleName, + const char *logicalName) { return(PPConstruct(theEnv,defruleName,logicalName,DefruleData(theEnv)->DefruleConstruct)); } @@ -252,7 +345,7 @@ globle int PPDefrule( globle void ListDefrulesCommand( void *theEnv) { - ListConstructCommand(theEnv,"list-defrules",DefruleData(theEnv)->DefruleConstruct); + ListConstructCommand(theEnv,"list-defrules",DefruleData(theEnv)->DefruleConstruct); } /*************************************/ @@ -261,10 +354,10 @@ globle void ListDefrulesCommand( /*************************************/ globle void EnvListDefrules( void *theEnv, - char *logicalName, + const char *logicalName, void *theModule) { - ListConstruct(theEnv,DefruleData(theEnv)->DefruleConstruct,logicalName,(struct defmodule *) theModule); + ListConstruct(theEnv,DefruleData(theEnv)->DefruleConstruct,logicalName,(struct defmodule *) theModule); } /*******************************************************/ @@ -272,15 +365,12 @@ globle void EnvListDefrules( /* retrieving the current watch value of a defrule's */ /* activations. */ /*******************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefruleWatchActivations( void *theEnv, void *rulePtr) { struct defrule *thePtr; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -297,15 +387,12 @@ globle unsigned EnvGetDefruleWatchActivations( /* for retrieving the current watch value of */ /* a defrule's firings. */ /***********************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDefruleWatchFirings( void *theEnv, void *rulePtr) { struct defrule *thePtr; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -322,16 +409,13 @@ globle unsigned EnvGetDefruleWatchFirings( /* for setting the current watch value of a */ /* defrule's activations. */ /***************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefruleWatchActivations( void *theEnv, unsigned newState, void *rulePtr) { struct defrule *thePtr; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -343,19 +427,16 @@ globle void EnvSetDefruleWatchActivations( /****************************************************/ /* EnvSetDefruleWatchFirings: C access routine for */ -/* setting the current watch value of a defrule's */ +/* setting the current watch value of a defrule's */ /* firings. */ /****************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDefruleWatchFirings( void *theEnv, unsigned newState, void *rulePtr) { struct defrule *thePtr; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -389,10 +470,10 @@ globle unsigned DefruleWatchAccess( /*****************************************************************/ globle unsigned DefruleWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, struct expr *argExprs) - { + { if (code) return(ConstructPrintWatchAccess(theEnv,DefruleData(theEnv)->DefruleConstruct,logName,argExprs, EnvGetDefruleWatchActivations,EnvSetDefruleWatchActivations)); @@ -403,6 +484,64 @@ globle unsigned DefruleWatchPrint( #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void GetDefruleList( + DATA_OBJECT_PTR returnValue, + void *theModule) + { + EnvGetDefruleList(GetCurrentEnvironment(),returnValue,theModule); + } + +#if DEBUGGING_FUNCTIONS + +globle unsigned GetDefruleWatchActivations( + void *rulePtr) + { + return EnvGetDefruleWatchActivations(GetCurrentEnvironment(),rulePtr); + } + +globle unsigned GetDefruleWatchFirings( + void *rulePtr) + { + return EnvGetDefruleWatchFirings(GetCurrentEnvironment(),rulePtr); + } + +globle void ListDefrules( + const char *logicalName, + void *theModule) + { + EnvListDefrules(GetCurrentEnvironment(),logicalName,theModule); + } + +globle void SetDefruleWatchActivations( + unsigned newState, + void *rulePtr) + { + EnvSetDefruleWatchActivations(GetCurrentEnvironment(),newState,rulePtr); + } + +globle void SetDefruleWatchFirings( + unsigned newState, + void *rulePtr) + { + EnvSetDefruleWatchFirings(GetCurrentEnvironment(),newState,rulePtr); + } + +#endif + +globle intBool Undefrule( + void *theDefrule) + { + return EnvUndefrule(GetCurrentEnvironment(),theDefrule); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/rulebsc.h b/src/rulebsc.h index 32566b3..6250670 100644 --- a/src/rulebsc.h +++ b/src/rulebsc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* DEFRULE BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -16,14 +16,34 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ +/* Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for join network changes. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* JoinOperationInProgress mechanism. */ +/* */ /*************************************************************/ #ifndef _H_rulebsc @@ -43,24 +63,6 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetDefruleList(theEnv,a,b) EnvGetDefruleList(theEnv,a,b) -#define GetDefruleWatchActivations(theEnv,a) EnvGetDefruleWatchActivations(theEnv,a) -#define GetDefruleWatchFirings(theEnv,a) EnvGetDefruleWatchFirings(theEnv,a) -#define ListDefrules(theEnv,a,b) EnvListDefrules(theEnv,a,b) -#define SetDefruleWatchActivations(theEnv,a,b) EnvSetDefruleWatchActivations(theEnv,a,b) -#define SetDefruleWatchFirings(theEnv,a,b) EnvSetDefruleWatchFirings(theEnv,a,b) -#define Undefrule(theEnv,a) EnvUndefrule(theEnv,a) -#else -#define GetDefruleList(a,b) EnvGetDefruleList(GetCurrentEnvironment(),a,b) -#define GetDefruleWatchActivations(a) EnvGetDefruleWatchActivations(GetCurrentEnvironment(),a) -#define GetDefruleWatchFirings(a) EnvGetDefruleWatchFirings(GetCurrentEnvironment(),a) -#define ListDefrules(a,b) EnvListDefrules(GetCurrentEnvironment(),a,b) -#define SetDefruleWatchActivations(a,b) EnvSetDefruleWatchActivations(GetCurrentEnvironment(),a,b) -#define SetDefruleWatchFirings(a,b) EnvSetDefruleWatchFirings(GetCurrentEnvironment(),a,b) -#define Undefrule(a) EnvUndefrule(GetCurrentEnvironment(),a) -#endif - LOCALE void DefruleBasicCommands(void *); LOCALE void UndefruleCommand(void *); LOCALE intBool EnvUndefrule(void *,void *); @@ -69,17 +71,31 @@ LOCALE void *DefruleModuleFunction(void *); #if DEBUGGING_FUNCTIONS LOCALE void PPDefruleCommand(void *); - LOCALE int PPDefrule(void *,char *,char *); + LOCALE int PPDefrule(void *,const char *,const char *); LOCALE void ListDefrulesCommand(void *); - LOCALE void EnvListDefrules(void *,char *,void *); + LOCALE void EnvListDefrules(void *,const char *,void *); LOCALE unsigned EnvGetDefruleWatchFirings(void *,void *); LOCALE unsigned EnvGetDefruleWatchActivations(void *,void *); LOCALE void EnvSetDefruleWatchFirings(void *,unsigned,void *); LOCALE void EnvSetDefruleWatchActivations(void *,unsigned,void *); LOCALE unsigned DefruleWatchAccess(void *,int,unsigned,struct expr *); - LOCALE unsigned DefruleWatchPrint(void *,char *,int,struct expr *); + LOCALE unsigned DefruleWatchPrint(void *,const char *,int,struct expr *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void GetDefruleList(DATA_OBJECT_PTR,void *); +#if DEBUGGING_FUNCTIONS + LOCALE unsigned GetDefruleWatchActivations(void *); + LOCALE unsigned GetDefruleWatchFirings(void *); + LOCALE void ListDefrules(const char *,void *); + LOCALE void SetDefruleWatchActivations(unsigned,void *); + LOCALE void SetDefruleWatchFirings(unsigned,void *); #endif + LOCALE intBool Undefrule(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_rulebsc */ diff --git a/src/rulecmp.c b/src/rulecmp.c index bcd4072..c5fe797 100644 --- a/src/rulecmp.c +++ b/src/rulecmp.c @@ -2,7 +2,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* DEFRULE CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -15,13 +15,25 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Removed DYNAMIC_SALIENCE and */ /* LOGICAL_DEPENDENCIES compilation flags. */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for join network changes. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _RULECMP_SOURCE_ @@ -44,12 +56,19 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int ConstructToCode(void *,char *,int,FILE *,int,int); + static int ConstructToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void JoinToCode(void *,FILE *,struct joinNode *,int,int); + static void LinkToCode(void *,FILE *,struct joinLink *,int,int); static void DefruleModuleToCode(void *,FILE *,struct defmodule *,int,int,int); static void DefruleToCode(void *,FILE *,struct defrule *,int,int,int); - static void CloseDefruleFiles(void *,FILE *,FILE *,FILE *,int); + static void CloseDefruleFiles(void *,FILE *,FILE *,FILE *,FILE*,int); static void BeforeDefrulesCode(void *); + static void InitDefruleCode(void *,FILE *,int,int); + static int RuleCompilerTraverseJoins(void *,struct joinNode *,const char *,const char *,char *,int, + FILE *,int,int,FILE **,FILE **, + int *,int *,int *,int *,int *); + static int TraverseJoinLinks(void *,struct joinLink *,const char *,const char *,char *,int,FILE *, + int,int,FILE **,int *,int *, int *); /***********************************************************/ /* DefruleCompilerSetup: Initializes the defrule construct */ @@ -59,7 +78,7 @@ globle void DefruleCompilerSetup( void *theEnv) { DefruleData(theEnv)->DefruleCodeItem = AddCodeGeneratorItem(theEnv,"defrules",0,BeforeDefrulesCode, - NULL,ConstructToCode,3); + InitDefruleCode,ConstructToCode,4); } /**************************************************************/ @@ -70,9 +89,9 @@ globle void DefruleCompilerSetup( static void BeforeDefrulesCode( void *theEnv) { - long int moduleCount, ruleCount, joinCount; + long int moduleCount, ruleCount, joinCount, linkCount; - TagRuleNetwork(theEnv,&moduleCount,&ruleCount,&joinCount); + TagRuleNetwork(theEnv,&moduleCount,&ruleCount,&joinCount,&linkCount); } /*********************************************************/ @@ -81,7 +100,9 @@ static void BeforeDefrulesCode( /*********************************************************/ static int ConstructToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -90,11 +111,11 @@ static int ConstructToCode( int fileCount = 1; struct defmodule *theModule; struct defrule *theDefrule; - struct joinNode *theJoin; int joinArrayCount = 0, joinArrayVersion = 1; + int linkArrayCount = 0, linkArrayVersion = 1; int moduleCount = 0, moduleArrayCount = 0, moduleArrayVersion = 1; int defruleArrayCount = 0, defruleArrayVersion = 1; - FILE *joinFile = NULL, *moduleFile = NULL, *defruleFile = NULL; + FILE *joinFile = NULL, *moduleFile = NULL, *defruleFile = NULL, *linkFile = NULL; /*==============================================*/ /* Include the appropriate defrule header file. */ @@ -102,6 +123,24 @@ static int ConstructToCode( fprintf(headerFP,"#include \"ruledef.h\"\n"); + /*======================================*/ + /* Save the left and right prime links. */ + /*======================================*/ + + if (! TraverseJoinLinks(theEnv,DefruleData(theEnv)->LeftPrimeJoins,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID, + maxIndices,&linkFile,&fileCount,&linkArrayVersion,&linkArrayCount)) + { + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); + return(0); + } + + if (! TraverseJoinLinks(theEnv,DefruleData(theEnv)->RightPrimeJoins,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID, + maxIndices,&linkFile,&fileCount,&linkArrayVersion,&linkArrayCount)) + { + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); + return(0); + } + /*=========================================================*/ /* Loop through all the modules, all the defrules, and all */ /* the join nodes writing their C code representation to */ @@ -122,14 +161,14 @@ static int ConstructToCode( /* Save the defrule module. */ /*==========================*/ - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "struct defruleModule",ModulePrefix(DefruleData(theEnv)->DefruleCodeItem), FALSE,NULL); if (moduleFile == NULL) { - CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,maxIndices); + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); return(0); } @@ -150,13 +189,13 @@ static int ConstructToCode( /* Save the defrule data structures. */ /*===================================*/ - defruleFile = OpenFileIfNeeded(theEnv,defruleFile,fileName,fileID,imageID,&fileCount, + defruleFile = OpenFileIfNeeded(theEnv,defruleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, defruleArrayVersion,headerFP, "struct defrule",ConstructPrefix(DefruleData(theEnv)->DefruleCodeItem), FALSE,NULL); if (defruleFile == NULL) { - CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,maxIndices); + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); return(0); } @@ -170,26 +209,12 @@ static int ConstructToCode( /* Save the join data structures. */ /*================================*/ - for (theJoin = theDefrule->lastJoin; - theJoin != NULL; - theJoin = GetPreviousJoin(theJoin)) + if (! RuleCompilerTraverseJoins(theEnv,theDefrule->lastJoin,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID, + maxIndices,&joinFile,&linkFile,&fileCount,&joinArrayVersion,&joinArrayCount, + &linkArrayVersion,&linkArrayCount)) { - if (theJoin->marked) - { - joinFile = OpenFileIfNeeded(theEnv,joinFile,fileName,fileID,imageID,&fileCount, - joinArrayVersion,headerFP, - "struct joinNode",JoinPrefix(),FALSE,NULL); - if (joinFile == NULL) - { - CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,maxIndices); - return(0); - } - - JoinToCode(theEnv,joinFile,theJoin,imageID,maxIndices); - joinArrayCount++; - joinFile = CloseFileIfNeeded(theEnv,joinFile,&joinArrayCount,&joinArrayVersion, - maxIndices,NULL,NULL); - } + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); + return(0); } /*==========================================*/ @@ -204,11 +229,106 @@ static int ConstructToCode( moduleArrayCount++; } - CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,maxIndices); + CloseDefruleFiles(theEnv,moduleFile,defruleFile,joinFile,linkFile,maxIndices); return(1); } +/*********************************************************************/ +/* RuleCompilerTraverseJoins: Traverses the join network for a rule. */ +/*********************************************************************/ +static int RuleCompilerTraverseJoins( + void *theEnv, + struct joinNode *joinPtr, + const char *fileName, + const char *pathName, + char *fileNameBuffer, + int fileID, + FILE *headerFP, + int imageID, + int maxIndices, + FILE **joinFile, + FILE **linkFile, + int *fileCount, + int *joinArrayVersion, + int *joinArrayCount, + int *linkArrayVersion, + int *linkArrayCount) + { + for (; + joinPtr != NULL; + joinPtr = joinPtr->lastLevel) + { + if (joinPtr->marked) + { + *joinFile = OpenFileIfNeeded(theEnv,*joinFile,fileName,pathName,fileNameBuffer,fileID,imageID,fileCount, + *joinArrayVersion,headerFP, + "struct joinNode",JoinPrefix(),FALSE,NULL); + if (*joinFile == NULL) + { return(FALSE); } + + JoinToCode(theEnv,*joinFile,joinPtr,imageID,maxIndices); + (*joinArrayCount)++; + *joinFile = CloseFileIfNeeded(theEnv,*joinFile,joinArrayCount,joinArrayVersion, + maxIndices,NULL,NULL); + + + if (! TraverseJoinLinks(theEnv,joinPtr->nextLinks,fileName,pathName,fileNameBuffer,fileID,headerFP,imageID, + maxIndices,linkFile,fileCount,linkArrayVersion,linkArrayCount)) + { return(FALSE); } + } + + if (joinPtr->joinFromTheRight) + { + if (RuleCompilerTraverseJoins(theEnv,(struct joinNode *) joinPtr->rightSideEntryStructure,fileName,pathName, + fileNameBuffer,fileID,headerFP,imageID,maxIndices,joinFile,linkFile,fileCount, + joinArrayVersion,joinArrayCount, + linkArrayVersion,linkArrayCount) == FALSE) + { return(FALSE); } + } + } + + return(TRUE); + } + +/*******************************************************/ +/* TraverseJoinLinks: Writes out a list of join links. */ +/*******************************************************/ +static int TraverseJoinLinks( + void *theEnv, + struct joinLink *linkPtr, + const char *fileName, + const char *pathName, + char *fileNameBuffer, + int fileID, + FILE *headerFP, + int imageID, + int maxIndices, + FILE **linkFile, + int *fileCount, + int *linkArrayVersion, + int *linkArrayCount) + { + for (; + linkPtr != NULL; + linkPtr = linkPtr->next) + { + *linkFile = OpenFileIfNeeded(theEnv,*linkFile,fileName,pathName,fileNameBuffer,fileID,imageID,fileCount, + *linkArrayVersion,headerFP, + "struct joinLink",LinkPrefix(),FALSE,NULL); + + if (*linkFile == NULL) + { return(FALSE); } + + LinkToCode(theEnv,*linkFile,linkPtr,imageID,maxIndices); + (*linkArrayCount)++; + *linkFile = CloseFileIfNeeded(theEnv,*linkFile,linkArrayCount,linkArrayVersion, + maxIndices,NULL,NULL); + } + + return(TRUE); + } + /********************************************************/ /* CloseDefruleFiles: Closes all of the C files created */ /* for defrule. Called when an error occurs or when */ @@ -219,11 +339,18 @@ static void CloseDefruleFiles( FILE *moduleFile, FILE *defruleFile, FILE *joinFile, + FILE *linkFile, int maxIndices) { int count = maxIndices; int arrayVersion = 0; + if (linkFile != NULL) + { + count = maxIndices; + CloseFileIfNeeded(theEnv,linkFile,&count,&arrayVersion,maxIndices,NULL,NULL); + } + if (joinFile != NULL) { count = maxIndices; @@ -247,9 +374,6 @@ static void CloseDefruleFiles( /* DefruleModuleToCode: Writes the C code representation */ /* of a single defrule module to the specified file. */ /*********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DefruleModuleToCode( void *theEnv, FILE *theFile, @@ -258,7 +382,7 @@ static void DefruleModuleToCode( int maxIndices, int moduleCount) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(moduleCount) #endif @@ -306,8 +430,8 @@ static void DefruleToCode( /* Dynamic Salience */ /*==================*/ - ExpressionToCode(theEnv,theFile,theDefrule->dynamicSalience); - fprintf(theFile,","); + ExpressionToCode(theEnv,theFile,theDefrule->dynamicSalience); + fprintf(theFile,","); /*=============*/ /* RHS Actions */ @@ -362,7 +486,7 @@ static void DefruleToCode( /***************************************************/ static void JoinToCode( void *theEnv, - FILE *theFile, + FILE *joinFile, struct joinNode *theJoin, int imageID, int maxIndices) @@ -379,45 +503,63 @@ static void JoinToCode( /* Flags and Integer Values. */ /*===========================*/ - fprintf(theFile,"{%d,%d,%d,%d,0,0,%d,%d,0,", + fprintf(joinFile,"{%d,%d,%d,%d,%d,0,0,%d,%d,0,0,0,0,0,0,", theJoin->firstJoin,theJoin->logicalJoin, theJoin->joinFromTheRight,theJoin->patternIsNegated, + theJoin->patternIsExists, + // initialize, + // marked theJoin->rhsType,theJoin->depth); + // bsaveID + // memoryLeftAdds + // memoryRightAdds + // memoryLeftDeletes + // memoryRightDeletes + // memoryCompares - /*==============*/ - /* Beta Memory. */ - /*==============*/ + /*==========================*/ + /* Left and right Memories. */ + /*==========================*/ - fprintf(theFile,"NULL,"); + fprintf(joinFile,"NULL,NULL,"); /*====================*/ /* Network Expression */ /*====================*/ - PrintHashedExpressionReference(theEnv,theFile,theJoin->networkTest,imageID,maxIndices); - fprintf(theFile,","); + PrintHashedExpressionReference(theEnv,joinFile,theJoin->networkTest,imageID,maxIndices); + fprintf(joinFile,","); + + PrintHashedExpressionReference(theEnv,joinFile,theJoin->secondaryNetworkTest,imageID,maxIndices); + fprintf(joinFile,","); + + PrintHashedExpressionReference(theEnv,joinFile,theJoin->leftHash,imageID,maxIndices); + fprintf(joinFile,","); + + PrintHashedExpressionReference(theEnv,joinFile,theJoin->rightHash,imageID,maxIndices); + fprintf(joinFile,","); /*============================*/ /* Right Side Entry Structure */ /*============================*/ if (theJoin->rightSideEntryStructure == NULL) - { fprintf(theFile,"NULL,"); } + { fprintf(joinFile,"NULL,"); } else if (theJoin->joinFromTheRight == FALSE) { theParser = GetPatternParser(theEnv,(int) theJoin->rhsType); - if (theParser->codeReferenceFunction == NULL) fprintf(theFile,"NULL,"); + if (theParser->codeReferenceFunction == NULL) fprintf(joinFile,"NULL,"); else { - fprintf(theFile,"VS "); + fprintf(joinFile,"VS "); (*theParser->codeReferenceFunction)(theEnv,theJoin->rightSideEntryStructure, - theFile,imageID,maxIndices); - fprintf(theFile,","); + joinFile,imageID,maxIndices); + fprintf(joinFile,","); } } else { - fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), + fprintf(joinFile,"&%s%d_%ld[%ld],",JoinPrefix(), imageID,(((struct joinNode *) theJoin->rightSideEntryStructure)->bsaveID / maxIndices) + 1, ((struct joinNode *) theJoin->rightSideEntryStructure)->bsaveID % maxIndices); } @@ -426,13 +568,13 @@ static void JoinToCode( /* Next Join Level */ /*=================*/ - if (theJoin->nextLevel == NULL) - { fprintf(theFile,"NULL,"); } + if (theJoin->nextLinks == NULL) + { fprintf(joinFile,"NULL,"); } else { - fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), - imageID,(theJoin->nextLevel->bsaveID / maxIndices) + 1, - theJoin->nextLevel->bsaveID % maxIndices); + fprintf(joinFile,"&%s%d_%ld[%ld],",LinkPrefix(), + imageID,(theJoin->nextLinks->bsaveID / maxIndices) + 1, + theJoin->nextLinks->bsaveID % maxIndices); } /*=================*/ @@ -440,36 +582,23 @@ static void JoinToCode( /*=================*/ if (theJoin->lastLevel == NULL) - { fprintf(theFile,"NULL,"); } + { fprintf(joinFile,"NULL,"); } else { - fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), + fprintf(joinFile,"&%s%d_%ld[%ld],",JoinPrefix(), imageID,(theJoin->lastLevel->bsaveID / maxIndices) + 1, theJoin->lastLevel->bsaveID % maxIndices); } /*==================*/ - /* Right Drive Node */ - /*==================*/ - - if (theJoin->rightDriveNode == NULL) - { fprintf(theFile,"NULL,"); } - else - { - fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), - imageID,(theJoin->rightDriveNode->bsaveID / maxIndices) + 1, - theJoin->rightDriveNode->bsaveID % maxIndices); - } - - /*==================*/ /* Right Match Node */ /*==================*/ if (theJoin->rightMatchNode == NULL) - { fprintf(theFile,"NULL,"); } + { fprintf(joinFile,"NULL,"); } else { - fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), + fprintf(joinFile,"&%s%d_%ld[%ld],",JoinPrefix(), imageID,(theJoin->rightMatchNode->bsaveID / maxIndices) + 1, theJoin->rightMatchNode->bsaveID % maxIndices); } @@ -479,15 +608,65 @@ static void JoinToCode( /*==================*/ if (theJoin->ruleToActivate == NULL) - { fprintf(theFile,"NULL}"); } + { fprintf(joinFile,"NULL}"); } else { - fprintf(theFile,"&%s%d_%ld[%ld]}",ConstructPrefix(DefruleData(theEnv)->DefruleCodeItem),imageID, + fprintf(joinFile,"&%s%d_%ld[%ld]}",ConstructPrefix(DefruleData(theEnv)->DefruleCodeItem),imageID, (theJoin->ruleToActivate->header.bsaveID / maxIndices) + 1, theJoin->ruleToActivate->header.bsaveID % maxIndices); } } +/***************************************************/ +/* LinkToCode: Writes the C code representation of */ +/* a single join node to the specified file. */ +/***************************************************/ +static void LinkToCode( + void *theEnv, + FILE *theFile, + struct joinLink *theLink, + int imageID, + int maxIndices) + { + /*==================*/ + /* Enter Direction. */ + /*==================*/ + + fprintf(theFile,"{%d,",theLink->enterDirection); + + /*======*/ + /* Join */ + /*======*/ + + if (theLink->join == NULL) + { fprintf(theFile,"NULL,"); } + else + { + fprintf(theFile,"&%s%d_%ld[%ld],",JoinPrefix(), + imageID,(theLink->join->bsaveID / maxIndices) + 1, + theLink->join->bsaveID % maxIndices); + } + + /*======*/ + /* Next */ + /*======*/ + + if (theLink->next == NULL) + { fprintf(theFile,"NULL,"); } + else + { + fprintf(theFile,"&%s%d_%ld[%ld],",LinkPrefix(), + imageID,(theLink->next->bsaveID / maxIndices) + 1, + theLink->next->bsaveID % maxIndices); + } + + /*===========*/ + /* Bsave ID. */ + /*===========*/ + + fprintf(theFile,"0}"); + } + /*************************************************************/ /* DefruleCModuleReference: Writes the C code representation */ /* of a reference to a defrule module data structure. */ @@ -505,6 +684,43 @@ globle void DefruleCModuleReference( (count % maxIndices)); } + +/*****************************************************************/ +/* InitDefruleCode: Writes out initialization code for defrules. */ +/*****************************************************************/ +static void InitDefruleCode( + void *theEnv, + FILE *initFP, + int imageID, + int maxIndices) + { +#if MAC_XCD +#pragma unused(maxIndices) +#pragma unused(theEnv) +#pragma unused(imageID) +#endif + + fprintf(initFP," DefruleRunTimeInitialize(theEnv,"); + + if (DefruleData(theEnv)->RightPrimeJoins == NULL) + { fprintf(initFP,"NULL,"); } + else + { + fprintf(initFP,"&%s%d_%ld[%ld],",LinkPrefix(), + imageID,(DefruleData(theEnv)->RightPrimeJoins->bsaveID / maxIndices) + 1, + DefruleData(theEnv)->RightPrimeJoins->bsaveID % maxIndices); + } + + if (DefruleData(theEnv)->LeftPrimeJoins == NULL) + { fprintf(initFP,"NULL);\n"); } + else + { + fprintf(initFP,"&%s%d_%ld[%ld]);\n",LinkPrefix(), + imageID,(DefruleData(theEnv)->LeftPrimeJoins->bsaveID / maxIndices) + 1, + DefruleData(theEnv)->LeftPrimeJoins->bsaveID % maxIndices); + } + } + #endif /* DEFRULE_CONSTRUCT && (! RUN_TIME) && CONSTRUCT_COMPILER */ diff --git a/src/rulecmp.h b/src/rulecmp.h index 47f123e..02ec7fe 100644 --- a/src/rulecmp.h +++ b/src/rulecmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFRULE CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -17,6 +17,21 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Removed DYNAMIC_SALIENCE and */ +/* LOGICAL_DEPENDENCIES compilation flags. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for join network changes. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_rulecmp @@ -28,6 +43,7 @@ #endif #define JoinPrefix() ArbitraryPrefix(DefruleData(theEnv)->DefruleCodeItem,2) +#define LinkPrefix() ArbitraryPrefix(DefruleData(theEnv)->DefruleCodeItem,3) #ifdef LOCALE #undef LOCALE @@ -42,11 +58,7 @@ LOCALE void DefruleCompilerSetup(void *); LOCALE void DefruleCModuleReference(void *,FILE *,int,int,int); -#ifndef _RULECMP_SOURCE_ -extern struct CodeGeneratorItem *DefruleCodeItem; -#endif - -#endif +#endif /* _H_rulecmp */ diff --git a/src/rulecom.c b/src/rulecom.c index 2854326..f630483 100644 --- a/src/rulecom.c +++ b/src/rulecom.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* RULE COMMANDS MODULE */ /*******************************************************/ @@ -25,6 +25,27 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Improvements to matches command. */ +/* */ +/* Add join-activity and join-activity-reset */ +/* commands. */ +/* */ +/* Added get-beta-memory-resizing and */ +/* set-beta-memory-resizing functions. */ +/* */ +/* Added timetag function. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _RULECOM_SOURCE_ @@ -48,10 +69,12 @@ #include "incrrset.h" #include "lgcldpnd.h" #include "memalloc.h" +#include "multifld.h" #include "pattern.h" #include "reteutil.h" #include "router.h" #include "ruledlt.h" +#include "sysdep.h" #include "watch.h" #if BLOAD || BLOAD_AND_BSAVE || BLOAD_ONLY @@ -67,6 +90,19 @@ #if DEVELOPER static void ShowJoins(void *,void *); #endif +#if DEBUGGING_FUNCTIONS + static long long ListAlphaMatches(void *,struct joinInformation *,int); + static long long ListBetaMatches(void *,struct joinInformation *,long,long,int); + static void ListBetaJoinActivity(void *,struct joinInformation *,long,long,int,DATA_OBJECT *); + static long AlphaJoinCountDriver(void *,struct joinNode *); + static long BetaJoinCountDriver(void *,struct joinNode *); + static void AlphaJoinsDriver(void *,struct joinNode *,long,struct joinInformation *); + static void BetaJoinsDriver(void *,struct joinNode *,long,struct joinInformation *,struct betaMemory *,struct joinNode *); + static int CountPatterns(void *,struct joinNode *,int); + static const char *BetaHeaderString(void *,struct joinInformation *,long,long); + static const char *ActivityHeaderString(void *,struct joinInformation *,long,long); + static void JoinActivityReset(void *,struct constructHeader *,void *); +#endif /****************************************************************/ /* DefruleCommands: Initializes defrule commands and functions. */ @@ -93,13 +129,18 @@ globle void DefruleCommands( "RemoveBreakCommand", "*1w"); EnvDefineFunction2(theEnv,"show-breaks",'v', PTIEF ShowBreaksCommand, "ShowBreaksCommand", "01w"); - EnvDefineFunction2(theEnv,"matches",'v',PTIEF MatchesCommand,"MatchesCommand","11w"); + EnvDefineFunction2(theEnv,"matches",'u',PTIEF MatchesCommand,"MatchesCommand","12w"); + EnvDefineFunction2(theEnv,"join-activity",'u',PTIEF JoinActivityCommand,"JoinActivityCommand","12w"); + EnvDefineFunction2(theEnv,"join-activity-reset",'v', PTIEF JoinActivityResetCommand, + "JoinActivityResetCommand", "00"); EnvDefineFunction2(theEnv,"list-focus-stack",'v', PTIEF ListFocusStackCommand, "ListFocusStackCommand", "00"); EnvDefineFunction2(theEnv,"dependencies", 'v', PTIEF DependenciesCommand, "DependenciesCommand", "11h"); EnvDefineFunction2(theEnv,"dependents", 'v', PTIEF DependentsCommand, "DependentsCommand", "11h"); + EnvDefineFunction2(theEnv,"timetag", 'g', PTIEF TimetagFunction, + "TimetagFunction", "11h"); #endif /* DEBUGGING_FUNCTIONS */ EnvDefineFunction2(theEnv,"get-incremental-reset",'b', @@ -107,24 +148,112 @@ globle void DefruleCommands( EnvDefineFunction2(theEnv,"set-incremental-reset",'b', SetIncrementalResetCommand,"SetIncrementalResetCommand","11"); + EnvDefineFunction2(theEnv,"get-beta-memory-resizing",'b', + GetBetaMemoryResizingCommand,"GetBetaMemoryResizingCommand","00"); + EnvDefineFunction2(theEnv,"set-beta-memory-resizing",'b', + SetBetaMemoryResizingCommand,"SetBetaMemoryResizingCommand","11"); + EnvDefineFunction2(theEnv,"get-strategy", 'w', PTIEF GetStrategyCommand, "GetStrategyCommand", "00"); EnvDefineFunction2(theEnv,"set-strategy", 'w', PTIEF SetStrategyCommand, "SetStrategyCommand", "11w"); #if DEVELOPER && (! BLOAD_ONLY) EnvDefineFunction2(theEnv,"rule-complexity",'l', PTIEF RuleComplexityCommand,"RuleComplexityCommand", "11w"); EnvDefineFunction2(theEnv,"show-joins", 'v', PTIEF ShowJoinsCommand, "ShowJoinsCommand", "11w"); + EnvDefineFunction2(theEnv,"show-aht", 'v', PTIEF ShowAlphaHashTable, "ShowAlphaHashTable", "00"); #if DEBUGGING_FUNCTIONS - //AddWatchItem(theEnv,"rule-analysis",0,&DefruleData(theEnv)->WatchRuleAnalysis,0,NULL,NULL); + AddWatchItem(theEnv,"rule-analysis",0,&DefruleData(theEnv)->WatchRuleAnalysis,0,NULL,NULL); #endif #endif /* DEVELOPER && (! BLOAD_ONLY) */ #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif /* ! RUN_TIME */ } +/***********************************************/ +/* EnvGetBetaMemoryResizing: C access routine */ +/* for the get-beta-memory-resizing command. */ +/***********************************************/ +globle intBool EnvGetBetaMemoryResizing( + void *theEnv) + { + return(DefruleData(theEnv)->BetaMemoryResizingFlag); + } + +/***********************************************/ +/* EnvSetBetaMemoryResizing: C access routine */ +/* for the set-beta-memory-resizing command. */ +/***********************************************/ +globle intBool EnvSetBetaMemoryResizing( + void *theEnv, + int value) + { + int ov; + + ov = DefruleData(theEnv)->BetaMemoryResizingFlag; + + DefruleData(theEnv)->BetaMemoryResizingFlag = value; + + return(ov); + } + +/****************************************************/ +/* SetBetaMemoryResizingCommand: H/L access routine */ +/* for the set-beta-memory-resizing command. */ +/****************************************************/ +globle int SetBetaMemoryResizingCommand( + void *theEnv) + { + int oldValue; + DATA_OBJECT argPtr; + + oldValue = EnvGetBetaMemoryResizing(theEnv); + + /*============================================*/ + /* Check for the correct number of arguments. */ + /*============================================*/ + + if (EnvArgCountCheck(theEnv,"set-beta-memory-resizing",EXACTLY,1) == -1) + { return(oldValue); } + + /*=================================================*/ + /* The symbol FALSE disables beta memory resizing. */ + /* Any other value enables beta memory resizing. */ + /*=================================================*/ + + EnvRtnUnknown(theEnv,1,&argPtr); + + if ((argPtr.value == EnvFalseSymbol(theEnv)) && (argPtr.type == SYMBOL)) + { EnvSetBetaMemoryResizing(theEnv,FALSE); } + else + { EnvSetBetaMemoryResizing(theEnv,TRUE); } + + /*=======================*/ + /* Return the old value. */ + /*=======================*/ + + return(oldValue); + } + +/****************************************************/ +/* GetBetaMemoryResizingCommand: H/L access routine */ +/* for the get-beta-memory-resizing command. */ +/****************************************************/ +globle int GetBetaMemoryResizingCommand( + void *theEnv) + { + int oldValue; + + oldValue = EnvGetBetaMemoryResizing(theEnv); + + if (EnvArgCountCheck(theEnv,"get-beta-memory-resizing",EXACTLY,0) == -1) + { return(oldValue); } + + return(oldValue); + } + #if DEBUGGING_FUNCTIONS /****************************************/ @@ -132,13 +261,29 @@ globle void DefruleCommands( /* for the matches command. */ /****************************************/ globle void MatchesCommand( - void *theEnv) + void *theEnv, + DATA_OBJECT *result) { - char *ruleName; + const char *ruleName, *argument; void *rulePtr; + int numberOfArguments; + DATA_OBJECT argPtr; + int output; - ruleName = GetConstructName(theEnv,"matches","rule name"); - if (ruleName == NULL) return; + result->type = SYMBOL; + result->value = EnvFalseSymbol(theEnv); + + if ((numberOfArguments = EnvArgRangeCheck(theEnv,"matches",1,2)) == -1) return; + + if (EnvArgTypeCheck(theEnv,"matches",1,SYMBOL,&argPtr) == FALSE) return; + + if (GetType(argPtr) != SYMBOL) + { + ExpectedTypeError1(theEnv,"matches",1,"rule name"); + return; + } + + ruleName = DOToString(argPtr); rulePtr = EnvFindDefrule(theEnv,ruleName); if (rulePtr == NULL) @@ -147,179 +292,1038 @@ globle void MatchesCommand( return; } - EnvMatches(theEnv,rulePtr); + if (numberOfArguments == 2) + { + if (EnvArgTypeCheck(theEnv,"matches",2,SYMBOL,&argPtr) == FALSE) + { return; } + + argument = DOToString(argPtr); + if (strcmp(argument,"verbose") == 0) + { output = VERBOSE; } + else if (strcmp(argument,"succinct") == 0) + { output = SUCCINCT; } + else if (strcmp(argument,"terse") == 0) + { output = TERSE; } + else + { + ExpectedTypeError1(theEnv,"matches",2,"symbol with value verbose, succinct, or terse"); + return; + } + } + else + { output = VERBOSE; } + + EnvMatches(theEnv,rulePtr,output,result); } /********************************/ /* EnvMatches: C access routine */ /* for the matches command. */ /********************************/ -globle intBool EnvMatches( +globle void EnvMatches( void *theEnv, - void *theRule) + void *theRule, + int output, + DATA_OBJECT *result) { - struct defrule *rulePtr, *tmpPtr; - struct partialMatch *listOfMatches, **theStorage; - struct joinNode *theJoin, *lastJoin; - int i, depth; + struct defrule *rulePtr; + long disjunctCount, disjunctIndex, joinIndex; + long arraySize; + struct joinInformation *theInfo; + long long alphaMatchCount = 0; + long long betaMatchCount = 0; + long long activations = 0; ACTIVATION *agendaPtr; - int flag; - int matchesDisplayed; + + /*==========================*/ + /* Set up the return value. */ + /*==========================*/ + + result->type = MULTIFIELD; + result->begin = 0; + result->end = 2; + result->value = EnvCreateMultifield(theEnv,3L); + + SetMFType(result->value,1,INTEGER); + SetMFValue(result->value,1,SymbolData(theEnv)->Zero); + SetMFType(result->value,2,INTEGER); + SetMFValue(result->value,2,SymbolData(theEnv)->Zero); + SetMFType(result->value,3,INTEGER); + SetMFValue(result->value,3,SymbolData(theEnv)->Zero); /*=================================================*/ /* Loop through each of the disjuncts for the rule */ /*=================================================*/ - for (rulePtr = (struct defrule *) theRule, tmpPtr = rulePtr; - rulePtr != NULL; - rulePtr = rulePtr->disjunct) + disjunctCount = EnvGetDisjunctCount(theEnv,theRule); + + for (disjunctIndex = 1; disjunctIndex <= disjunctCount; disjunctIndex++) { + rulePtr = (struct defrule *) EnvGetNthDisjunct(theEnv,theRule,disjunctIndex); + + /*===============================================*/ + /* Create the array containing the list of alpha */ + /* join nodes (those connected to a pattern CE). */ + /*===============================================*/ + + arraySize = EnvAlphaJoinCount(theEnv,rulePtr); + + theInfo = EnvCreateJoinArray(theEnv,arraySize); + + EnvAlphaJoins(theEnv,rulePtr,arraySize,theInfo); + + /*=========================*/ + /* List the alpha matches. */ + /*=========================*/ + + for (joinIndex = 0; joinIndex < arraySize; joinIndex++) + { + alphaMatchCount += ListAlphaMatches(theEnv,&theInfo[joinIndex],output); + + SetMFType(result->value,1,INTEGER); + SetMFValue(result->value,1,EnvAddLong(theEnv,alphaMatchCount)); + } + + /*================================*/ + /* Free the array of alpha joins. */ + /*================================*/ + + EnvFreeJoinArray(theEnv,theInfo,arraySize); + + /*==============================================*/ + /* Create the array containing the list of beta */ + /* join nodes (joins from the right plus joins */ + /* connected to a pattern CE). */ + /*==============================================*/ + + arraySize = EnvBetaJoinCount(theEnv,rulePtr); + + theInfo = EnvCreateJoinArray(theEnv,arraySize); + + EnvBetaJoins(theEnv,rulePtr,arraySize,theInfo); + /*======================================*/ - /* Determine the last join in the rule. */ + /* List the beta matches (for all joins */ + /* except the first pattern CE). */ /*======================================*/ - lastJoin = rulePtr->lastJoin; + for (joinIndex = 1; joinIndex < arraySize; joinIndex++) + { + betaMatchCount += ListBetaMatches(theEnv,theInfo,joinIndex,arraySize,output); + + SetMFType(result->value,2,INTEGER); + SetMFValue(result->value,2,EnvAddLong(theEnv,betaMatchCount)); + } - /*===================================*/ - /* Determine the number of patterns. */ - /*===================================*/ + /*================================*/ + /* Free the array of alpha joins. */ + /*================================*/ - depth = GetPatternNumberFromJoin(lastJoin); + EnvFreeJoinArray(theEnv,theInfo,arraySize); + } - /*=========================================*/ - /* Store the alpha memory partial matches. */ - /*=========================================*/ + /*===================*/ + /* List activations. */ + /*===================*/ - theStorage = (struct partialMatch **) - genalloc(theEnv,(unsigned) (depth * sizeof(struct partialMatch))); + if (output == VERBOSE) + { EnvPrintRouter(theEnv,WDISPLAY,"Activations\n"); } - theJoin = lastJoin; - i = depth - 1; - while (theJoin != NULL) + for (agendaPtr = (struct activation *) EnvGetNextActivation(theEnv,NULL); + agendaPtr != NULL; + agendaPtr = (struct activation *) EnvGetNextActivation(theEnv,agendaPtr)) + { + if (GetHaltExecution(theEnv) == TRUE) return; + + if (((struct activation *) agendaPtr)->theRule->header.name == rulePtr->header.name) { - if (theJoin->joinFromTheRight) - { theJoin = (struct joinNode *) theJoin->rightSideEntryStructure; } - else + activations++; + + if (output == VERBOSE) { - theStorage[i] = ((struct patternNodeHeader *) theJoin->rightSideEntryStructure)->alphaMemory; - i--; - theJoin = theJoin->lastLevel; + PrintPartialMatch(theEnv,WDISPLAY,EnvGetActivationBasis(theEnv,agendaPtr)); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); } } + } + + if (output == SUCCINCT) + { + EnvPrintRouter(theEnv,WDISPLAY,"Activations: "); + PrintLongInteger(theEnv,WDISPLAY,activations); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } - /*========================================*/ - /* List the alpha memory partial matches. */ - /*========================================*/ + if ((activations == 0) && (output == VERBOSE)) EnvPrintRouter(theEnv,WDISPLAY," None\n"); + + SetMFType(result->value,3,INTEGER); + SetMFValue(result->value,3,EnvAddLong(theEnv,activations)); + } + +/****************************************************/ +/* AlphaJoinCountDriver: Driver routine to iterate */ +/* over a rule's joins to determine the number of */ +/* alpha joins. */ +/****************************************************/ +static long AlphaJoinCountDriver( + void *theEnv, + struct joinNode *theJoin) + { + long alphaCount = 0; - for (i = 0; i < depth; i++) + if (theJoin == NULL) + { return(alphaCount); } + + if (theJoin->joinFromTheRight) + { return AlphaJoinCountDriver(theEnv,(struct joinNode *) theJoin->rightSideEntryStructure); } + else if (theJoin->lastLevel != NULL) + { alphaCount += AlphaJoinCountDriver(theEnv,theJoin->lastLevel); } + + alphaCount++; + + return(alphaCount); + } + +/**************************************************/ +/* EnvAlphaJoinCount: Returns the number of alpha */ +/* joins associated with the specified rule. */ +/**************************************************/ +globle long EnvAlphaJoinCount( + void *theEnv, + void *vTheDefrule) + { + struct defrule *theDefrule = (struct defrule *) vTheDefrule; + + return AlphaJoinCountDriver(theEnv,theDefrule->lastJoin->lastLevel); + } + +/***************************************/ +/* AlphaJoinsDriver: Driver routine to */ +/* retrieve a rule's alpha joins. */ +/***************************************/ +static void AlphaJoinsDriver( + void *theEnv, + struct joinNode *theJoin, + long alphaIndex, + struct joinInformation *theInfo) + { + if (theJoin == NULL) + { return; } + + if (theJoin->joinFromTheRight) + { + AlphaJoinsDriver(theEnv,(struct joinNode *) theJoin->rightSideEntryStructure,alphaIndex,theInfo); + return; + } + else if (theJoin->lastLevel != NULL) + { AlphaJoinsDriver(theEnv,theJoin->lastLevel,alphaIndex-1,theInfo); } + + theInfo[alphaIndex-1].whichCE = alphaIndex; + theInfo[alphaIndex-1].theJoin = theJoin; + + return; + } + +/********************************************/ +/* EnvAlphaJoins: Retrieves the alpha joins */ +/* associated with the specified rule. */ +/********************************************/ +globle void EnvAlphaJoins( + void *theEnv, + void *vTheDefrule, + long alphaCount, + struct joinInformation *theInfo) + { + struct defrule *theDefrule = (struct defrule *) vTheDefrule; + + AlphaJoinsDriver(theEnv,theDefrule->lastJoin->lastLevel,alphaCount,theInfo); + } + +/****************************************************/ +/* BetaJoinCountDriver: Driver routine to iterate */ +/* over a rule's joins to determine the number of */ +/* beta joins. */ +/****************************************************/ +static long BetaJoinCountDriver( + void *theEnv, + struct joinNode *theJoin) + { + long betaCount = 0; + + if (theJoin == NULL) + { return(betaCount); } + + betaCount++; + + if (theJoin->joinFromTheRight) + { betaCount += BetaJoinCountDriver(theEnv,(struct joinNode *) theJoin->rightSideEntryStructure); } + else if (theJoin->lastLevel != NULL) + { betaCount += BetaJoinCountDriver(theEnv,theJoin->lastLevel); } + + return(betaCount); + } + +/************************************************/ +/* EnvBetaJoinCount: Returns the number of beta */ +/* joins associated with the specified rule. */ +/************************************************/ +globle long EnvBetaJoinCount( + void *theEnv, + void *vTheDefrule) + { + struct defrule *theDefrule = (struct defrule *) vTheDefrule; + + return BetaJoinCountDriver(theEnv,theDefrule->lastJoin->lastLevel); + } + +/**************************************/ +/* BetaJoinsDriver: Driver routine to */ +/* retrieve a rule's beta joins. */ +/**************************************/ +static void BetaJoinsDriver( + void *theEnv, + struct joinNode *theJoin, + long betaIndex, + struct joinInformation *theJoinInfoArray, + struct betaMemory *lastMemory, + struct joinNode *nextJoin) + { + int theCE = 0, theCount; + struct joinNode *tmpPtr; + + if (theJoin == NULL) + { return; } + + theJoinInfoArray[betaIndex-1].theJoin = theJoin; + theJoinInfoArray[betaIndex-1].theMemory = lastMemory; + theJoinInfoArray[betaIndex-1].nextJoin = nextJoin; + + /*===================================*/ + /* Determine the conditional element */ + /* index for this join. */ + /*===================================*/ + + for (tmpPtr = theJoin; tmpPtr != NULL; tmpPtr = tmpPtr->lastLevel) + { theCE++; } + + theJoinInfoArray[betaIndex-1].whichCE = theCE; + + /*==============================================*/ + /* The end pattern in the range of patterns for */ + /* this join is always the number of patterns */ + /* remaining to be encountered. */ + /*==============================================*/ + + theCount = CountPatterns(theEnv,theJoin,TRUE); + theJoinInfoArray[betaIndex-1].patternEnd = theCount; + + /*========================================================*/ + /* Determine where the block of patterns for a CE begins. */ + /*========================================================*/ + + + theCount = CountPatterns(theEnv,theJoin,FALSE); + theJoinInfoArray[betaIndex-1].patternBegin = theCount; + + /*==========================*/ + /* Find the next beta join. */ + /*==========================*/ + + if (theJoin->joinFromTheRight) + { + BetaJoinsDriver(theEnv,(struct joinNode *) theJoin->rightSideEntryStructure,betaIndex-1,theJoinInfoArray,theJoin->rightMemory,theJoin); + } + else if (theJoin->lastLevel != NULL) + { + BetaJoinsDriver(theEnv,theJoin->lastLevel,betaIndex-1,theJoinInfoArray,theJoin->leftMemory,theJoin); + } + + return; + } + +/******************************************/ +/* EnvBetaJoins: Retrieves the beta joins */ +/* associated with the specified rule. */ +/******************************************/ +globle void EnvBetaJoins( + void *theEnv, + void *vTheDefrule, + long betaArraySize, + struct joinInformation *theInfo) + { + struct defrule *theDefrule = (struct defrule *) vTheDefrule; + + BetaJoinsDriver(theEnv,theDefrule->lastJoin->lastLevel,betaArraySize,theInfo,theDefrule->lastJoin->leftMemory,theDefrule->lastJoin); + } + +/**************************************************/ +/* EnvCreateJoinArray: Creates a join information */ +/* array of the specified size. */ +/**************************************************/ +globle struct joinInformation *EnvCreateJoinArray( + void *theEnv, + long size) + { + if (size == 0) return (NULL); + + return (struct joinInformation *) genalloc(theEnv,sizeof(struct joinInformation) * size); + } + +/**********************************************/ +/* EnvFreeJoinArray: Frees a join information */ +/* array of the specified size. */ +/**********************************************/ +globle void EnvFreeJoinArray( + void *theEnv, + struct joinInformation *theArray, + long size) + { + if (size == 0) return; + + genfree(theEnv,theArray,sizeof(struct joinInformation) * size); + } + +/*********************/ +/* ListAlphaMatches: */ +/*********************/ +static long long ListAlphaMatches( + void *theEnv, + struct joinInformation *theInfo, + int output) + { + struct alphaMemoryHash *listOfHashNodes; + struct partialMatch *listOfMatches; + long long count; + struct joinNode *theJoin; + long long alphaCount = 0; + + if (GetHaltExecution(theEnv) == TRUE) + { return(alphaCount); } + + theJoin = theInfo->theJoin; + + if (output == VERBOSE) + { + EnvPrintRouter(theEnv,WDISPLAY,"Matches for Pattern "); + PrintLongInteger(theEnv,WDISPLAY,theInfo->whichCE); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (theJoin->rightSideEntryStructure == NULL) + { + if (theJoin->rightMemory->beta[0]->children != NULL) + { alphaCount += 1; } + + if (output == VERBOSE) { - if (GetHaltExecution(theEnv) == TRUE) - { - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); - return(TRUE); - } + if (theJoin->rightMemory->beta[0]->children != NULL) + { EnvPrintRouter(theEnv,WDISPLAY,"*\n"); } + else + { EnvPrintRouter(theEnv,WDISPLAY," None\n"); } + } + else if (output == SUCCINCT) + { + EnvPrintRouter(theEnv,WDISPLAY,"Pattern "); + PrintLongInteger(theEnv,WDISPLAY,theInfo->whichCE); + EnvPrintRouter(theEnv,WDISPLAY,": "); - EnvPrintRouter(theEnv,WDISPLAY,"Matches for Pattern "); - PrintLongInteger(theEnv,WDISPLAY,(long int) i + 1); + if (theJoin->rightMemory->beta[0]->children != NULL) + { EnvPrintRouter(theEnv,WDISPLAY,"1"); } + else + { EnvPrintRouter(theEnv,WDISPLAY,"0"); } EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + return(alphaCount); + } - listOfMatches = theStorage[i]; - if (listOfMatches == NULL) EnvPrintRouter(theEnv,WDISPLAY," None\n"); + listOfHashNodes = ((struct patternNodeHeader *) theJoin->rightSideEntryStructure)->firstHash; - while (listOfMatches != NULL) + for (count = 0; + listOfHashNodes != NULL; + listOfHashNodes = listOfHashNodes->nextHash) + { + listOfMatches = listOfHashNodes->alphaMemory; + + while (listOfMatches != NULL) + { + if (GetHaltExecution(theEnv) == TRUE) + { return(alphaCount); } + + count++; + if (output == VERBOSE) { - if (GetHaltExecution(theEnv) == TRUE) - { - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); - return(TRUE); - } PrintPartialMatch(theEnv,WDISPLAY,listOfMatches); EnvPrintRouter(theEnv,WDISPLAY,"\n"); - listOfMatches = listOfMatches->next; } + listOfMatches = listOfMatches->nextInMemory; } + } + + alphaCount += count; + + if ((count == 0) && (output == VERBOSE)) EnvPrintRouter(theEnv,WDISPLAY," None\n"); + + if (output == SUCCINCT) + { + EnvPrintRouter(theEnv,WDISPLAY,"Pattern "); + PrintLongInteger(theEnv,WDISPLAY,theInfo->whichCE); + EnvPrintRouter(theEnv,WDISPLAY,": "); + PrintLongInteger(theEnv,WDISPLAY,count); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + return(alphaCount); + } - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); +/********************/ +/* BetaHeaderString */ +/********************/ +static const char *BetaHeaderString( + void *theEnv, + struct joinInformation *infoArray, + long joinIndex, + long arraySize) + { + struct joinNode *theJoin; + struct joinInformation *theInfo; + long i, j, startPosition, endPosition, positionsToPrint = 0; + int nestedCEs = FALSE; + const char *returnString = ""; + long lastIndex; + char buffer[32]; - /*========================================*/ - /* Store the beta memory partial matches. */ - /*========================================*/ + /*=============================================*/ + /* Determine which joins need to be traversed. */ + /*=============================================*/ - depth = lastJoin->depth; - theStorage = (struct partialMatch **) genalloc(theEnv,(unsigned) (depth * sizeof(struct partialMatch))); + for (i = 0; i < arraySize; i++) + { infoArray[i].marked = FALSE; } - theJoin = lastJoin; - for (i = depth - 1; i >= 0; i--) + theInfo = &infoArray[joinIndex]; + theJoin = theInfo->theJoin; + lastIndex = joinIndex; + + while (theJoin != NULL) + { + for (i = lastIndex; i >= 0; i--) { - theStorage[i] = theJoin->beta; - theJoin = theJoin->lastLevel; + if (infoArray[i].theJoin == theJoin) + { + positionsToPrint++; + infoArray[i].marked = TRUE; + if (infoArray[i].patternBegin != infoArray[i].patternEnd) + { nestedCEs = TRUE; } + lastIndex = i - 1; + break; + } } + theJoin = theJoin->lastLevel; + } + + for (i = 0; i <= joinIndex; i++) + { + if (infoArray[i].marked == FALSE) continue; - /*=======================================*/ - /* List the beta memory partial matches. */ - /*=======================================*/ + positionsToPrint--; + startPosition = i; + endPosition = i; - for (i = 1; i < depth; i++) + if (infoArray[i].patternBegin == infoArray[i].patternEnd) { - if (GetHaltExecution(theEnv) == TRUE) + for (j = i + 1; j <= joinIndex; j++) { - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); - return(TRUE); + if (infoArray[j].marked == FALSE) continue; + + if (infoArray[j].patternBegin != infoArray[j].patternEnd) break; + + positionsToPrint--; + i = j; + endPosition = j; } + } - matchesDisplayed = 0; - EnvPrintRouter(theEnv,WDISPLAY,"Partial matches for CEs 1 - "); - PrintLongInteger(theEnv,WDISPLAY,(long int) i + 1); - EnvPrintRouter(theEnv,WDISPLAY,"\n"); - listOfMatches = theStorage[i]; + theInfo = &infoArray[startPosition]; - while (listOfMatches != NULL) + gensprintf(buffer,"%d",theInfo->whichCE); + returnString = AppendStrings(theEnv,returnString,buffer); + + if (nestedCEs) + { + if (theInfo->patternBegin == theInfo->patternEnd) + { + returnString = AppendStrings(theEnv,returnString," (P"); + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString,")"); + } + else { - if (GetHaltExecution(theEnv) == TRUE) + returnString = AppendStrings(theEnv,returnString," (P"); + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString," - P"); + gensprintf(buffer,"%d",theInfo->patternEnd); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString,")"); + } + } + + if (startPosition != endPosition) + { + theInfo = &infoArray[endPosition]; + + returnString = AppendStrings(theEnv,returnString," - "); + gensprintf(buffer,"%d",theInfo->whichCE); + returnString = AppendStrings(theEnv,returnString,buffer); + + if (nestedCEs) + { + if (theInfo->patternBegin == theInfo->patternEnd) { - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); - return(TRUE); + returnString = AppendStrings(theEnv,returnString," (P"); + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString,")"); } - - if (listOfMatches->counterf == FALSE) + else { - matchesDisplayed++; - PrintPartialMatch(theEnv,WDISPLAY,listOfMatches); - EnvPrintRouter(theEnv,WDISPLAY,"\n"); + returnString = AppendStrings(theEnv,returnString," (P"); + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString," - P"); + gensprintf(buffer,"%d",theInfo->patternEnd); + returnString = AppendStrings(theEnv,returnString,buffer); + returnString = AppendStrings(theEnv,returnString,")"); } - listOfMatches = listOfMatches->next; } + } + + if (positionsToPrint > 0) + { returnString = AppendStrings(theEnv,returnString," , "); } + } - if (matchesDisplayed == 0) { EnvPrintRouter(theEnv,WDISPLAY," None\n"); } + return returnString; + } + +/********************/ +/* ListBetaMatches: */ +/********************/ +static long long ListBetaMatches( + void *theEnv, + struct joinInformation *infoArray, + long joinIndex, + long arraySize, + int output) + { + long betaCount = 0; + struct joinInformation *theInfo; + long int count; + + if (GetHaltExecution(theEnv) == TRUE) + { return(betaCount); } + + theInfo = &infoArray[joinIndex]; + + if (output == VERBOSE) + { + EnvPrintRouter(theEnv,WDISPLAY,"Partial matches for CEs "); + EnvPrintRouter(theEnv,WDISPLAY, + BetaHeaderString(theEnv,infoArray,joinIndex,arraySize)); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + count = PrintBetaMemory(theEnv,WDISPLAY,theInfo->theMemory,TRUE,"",output); + + betaCount += count; + + if ((output == VERBOSE) && (count == 0)) + { EnvPrintRouter(theEnv,WDISPLAY," None\n"); } + else if (output == SUCCINCT) + { + EnvPrintRouter(theEnv,WDISPLAY,"CEs "); + EnvPrintRouter(theEnv,WDISPLAY, + BetaHeaderString(theEnv,infoArray,joinIndex,arraySize)); + EnvPrintRouter(theEnv,WDISPLAY,": "); + PrintLongInteger(theEnv,WDISPLAY,betaCount); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + return(betaCount); + } + +/******************/ +/* CountPatterns: */ +/******************/ +static int CountPatterns( + void *theEnv, + struct joinNode *theJoin, + int followRight) + { + int theCount = 0; + + if (theJoin == NULL) return theCount; + + if (theJoin->joinFromTheRight && (followRight == FALSE)) + { theCount++; } + + while (theJoin != NULL) + { + if (theJoin->joinFromTheRight) + { + if (followRight) + { theJoin = (struct joinNode *) theJoin->rightSideEntryStructure; } + else + { theJoin = theJoin->lastLevel; } + } + else + { + theCount++; + theJoin = theJoin->lastLevel; } - genfree(theEnv,theStorage,(unsigned) (depth * sizeof(struct partialMatch))); + followRight = TRUE; } - /*===================*/ - /* List activations. */ - /*===================*/ + return theCount; + } - rulePtr = tmpPtr; - EnvPrintRouter(theEnv,WDISPLAY,"Activations\n"); - flag = 1; - for (agendaPtr = (struct activation *) EnvGetNextActivation(theEnv,NULL); - agendaPtr != NULL; - agendaPtr = (struct activation *) EnvGetNextActivation(theEnv,agendaPtr)) +/*******************************************/ +/* JoinActivityCommand: H/L access routine */ +/* for the join-activity command. */ +/*******************************************/ +globle void JoinActivityCommand( + void *theEnv, + DATA_OBJECT *result) + { + const char *ruleName, *argument; + void *rulePtr; + int numberOfArguments; + DATA_OBJECT argPtr; + int output; + + result->type = SYMBOL; + result->value = EnvFalseSymbol(theEnv); + + if ((numberOfArguments = EnvArgRangeCheck(theEnv,"join-activity",1,2)) == -1) return; + + if (EnvArgTypeCheck(theEnv,"join-activity",1,SYMBOL,&argPtr) == FALSE) return; + + if (GetType(argPtr) != SYMBOL) + { + ExpectedTypeError1(theEnv,"join-activity",1,"rule name"); + return; + } + + ruleName = DOToString(argPtr); + + rulePtr = EnvFindDefrule(theEnv,ruleName); + if (rulePtr == NULL) { - if (GetHaltExecution(theEnv) == TRUE) return(TRUE); + CantFindItemErrorMessage(theEnv,"defrule",ruleName); + return; + } - if (((struct activation *) agendaPtr)->theRule->header.name == rulePtr->header.name) + if (numberOfArguments == 2) + { + if (EnvArgTypeCheck(theEnv,"join-activity",2,SYMBOL,&argPtr) == FALSE) + { return; } + + argument = DOToString(argPtr); + if (strcmp(argument,"verbose") == 0) + { output = VERBOSE; } + else if (strcmp(argument,"succinct") == 0) + { output = SUCCINCT; } + else if (strcmp(argument,"terse") == 0) + { output = TERSE; } + else { - flag = 0; - PrintPartialMatch(theEnv,WDISPLAY,GetActivationBasis(agendaPtr)); - EnvPrintRouter(theEnv,WDISPLAY,"\n"); + ExpectedTypeError1(theEnv,"join-activity",2,"symbol with value verbose, succinct, or terse"); + return; } } + else + { output = VERBOSE; } + + EnvJoinActivity(theEnv,rulePtr,output,result); + } + +/*************************************/ +/* EnvJoinActivity: C access routine */ +/* for the join-activity command. */ +/*************************************/ +globle void EnvJoinActivity( + void *theEnv, + void *theRule, + int output, + DATA_OBJECT *result) + { + struct defrule *rulePtr; + long disjunctCount, disjunctIndex, joinIndex; + long arraySize; + struct joinInformation *theInfo; + + /*==========================*/ + /* Set up the return value. */ + /*==========================*/ + + result->type = MULTIFIELD; + result->begin = 0; + result->end = 2; + result->value = EnvCreateMultifield(theEnv,3L); + + SetMFType(result->value,1,INTEGER); + SetMFValue(result->value,1,SymbolData(theEnv)->Zero); + SetMFType(result->value,2,INTEGER); + SetMFValue(result->value,2,SymbolData(theEnv)->Zero); + SetMFType(result->value,3,INTEGER); + SetMFValue(result->value,3,SymbolData(theEnv)->Zero); + + /*=================================================*/ + /* Loop through each of the disjuncts for the rule */ + /*=================================================*/ + + disjunctCount = EnvGetDisjunctCount(theEnv,theRule); + + for (disjunctIndex = 1; disjunctIndex <= disjunctCount; disjunctIndex++) + { + rulePtr = (struct defrule *) EnvGetNthDisjunct(theEnv,theRule,disjunctIndex); + + /*==============================================*/ + /* Create the array containing the list of beta */ + /* join nodes (joins from the right plus joins */ + /* connected to a pattern CE). */ + /*==============================================*/ + + arraySize = EnvBetaJoinCount(theEnv,rulePtr); + + theInfo = EnvCreateJoinArray(theEnv,arraySize); + + EnvBetaJoins(theEnv,rulePtr,arraySize,theInfo); - if (flag) EnvPrintRouter(theEnv,WDISPLAY," None\n"); + /*======================================*/ + /* List the beta matches (for all joins */ + /* except the first pattern CE). */ + /*======================================*/ + + for (joinIndex = 0; joinIndex < arraySize; joinIndex++) + { ListBetaJoinActivity(theEnv,theInfo,joinIndex,arraySize,output,result); } + + /*================================*/ + /* Free the array of alpha joins. */ + /*================================*/ - return(TRUE); + EnvFreeJoinArray(theEnv,theInfo,arraySize); + } + } + +/************************/ +/* ActivityHeaderString */ +/************************/ +static const char *ActivityHeaderString( + void *theEnv, + struct joinInformation *infoArray, + long joinIndex, + long arraySize) + { + struct joinNode *theJoin; + struct joinInformation *theInfo; + long i; + int nestedCEs = FALSE; + const char *returnString = ""; + long lastIndex; + char buffer[32]; + + /*=============================================*/ + /* Determine which joins need to be traversed. */ + /*=============================================*/ + + for (i = 0; i < arraySize; i++) + { infoArray[i].marked = FALSE; } + + theInfo = &infoArray[joinIndex]; + theJoin = theInfo->theJoin; + lastIndex = joinIndex; + + while (theJoin != NULL) + { + for (i = lastIndex; i >= 0; i--) + { + if (infoArray[i].theJoin == theJoin) + { + if (infoArray[i].patternBegin != infoArray[i].patternEnd) + { nestedCEs = TRUE; } + lastIndex = i - 1; + break; + } + } + theJoin = theJoin->lastLevel; + } + + gensprintf(buffer,"%d",theInfo->whichCE); + returnString = AppendStrings(theEnv,returnString,buffer); + if (nestedCEs == FALSE) + { return returnString; } + + if (theInfo->patternBegin == theInfo->patternEnd) + { + returnString = AppendStrings(theEnv,returnString," (P"); + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + + returnString = AppendStrings(theEnv,returnString,")"); + } + else + { + returnString = AppendStrings(theEnv,returnString," (P"); + + gensprintf(buffer,"%d",theInfo->patternBegin); + returnString = AppendStrings(theEnv,returnString,buffer); + + returnString = AppendStrings(theEnv,returnString," - P"); + + gensprintf(buffer,"%d",theInfo->patternEnd); + returnString = AppendStrings(theEnv,returnString,buffer); + + returnString = AppendStrings(theEnv,returnString,")"); + } + + return returnString; + } + +/*************************/ +/* ListBetaJoinActivity: */ +/*************************/ +static void ListBetaJoinActivity( + void *theEnv, + struct joinInformation *infoArray, + long joinIndex, + long arraySize, + int output, + DATA_OBJECT *result) + { + long long activity = 0; + long long compares, adds, deletes; + struct joinNode *theJoin, *nextJoin; + struct joinInformation *theInfo; + + if (GetHaltExecution(theEnv) == TRUE) + { return; } + + theInfo = &infoArray[joinIndex]; + + theJoin = theInfo->theJoin; + nextJoin = theInfo->nextJoin; + + compares = theJoin->memoryCompares; + if (theInfo->nextJoin->joinFromTheRight) + { + adds = nextJoin->memoryRightAdds; + deletes = nextJoin->memoryRightDeletes; + } + else + { + adds = nextJoin->memoryLeftAdds; + deletes = nextJoin->memoryLeftDeletes; + } + + activity = compares + adds + deletes; + + if (output == VERBOSE) + { + char buffer[100]; + + EnvPrintRouter(theEnv,WDISPLAY,"Activity for CE "); + EnvPrintRouter(theEnv,WDISPLAY, + ActivityHeaderString(theEnv,infoArray,joinIndex,arraySize)); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + + sprintf(buffer," Compares: %10lld\n",compares); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + sprintf(buffer," Adds: %10lld\n",adds); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + sprintf(buffer," Deletes: %10lld\n",deletes); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + } + else if (output == SUCCINCT) + { + EnvPrintRouter(theEnv,WDISPLAY,"CE "); + EnvPrintRouter(theEnv,WDISPLAY, + ActivityHeaderString(theEnv,infoArray,joinIndex,arraySize)); + EnvPrintRouter(theEnv,WDISPLAY,": "); + PrintLongInteger(theEnv,WDISPLAY,activity); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + compares += ValueToLong(GetMFValue(result->value,1)); + adds += ValueToLong(GetMFValue(result->value,2)); + deletes += ValueToLong(GetMFValue(result->value,3)); + + SetMFType(result->value,1,INTEGER); + SetMFValue(result->value,1,EnvAddLong(theEnv,compares)); + SetMFType(result->value,2,INTEGER); + SetMFValue(result->value,2,EnvAddLong(theEnv,adds)); + SetMFType(result->value,3,INTEGER); + SetMFValue(result->value,3,EnvAddLong(theEnv,deletes)); + } + +/*********************************************/ +/* JoinActivityReset: Sets the join activity */ +/* counts for each rule back to 0. */ +/*********************************************/ +static void JoinActivityReset( + void *theEnv, + struct constructHeader *theConstruct, + void *buffer) + { +#if MAC_XCD +#pragma unused(buffer) +#endif + struct defrule *theDefrule = (struct defrule *) theConstruct; + struct joinNode *theJoin = theDefrule->lastJoin; + + while (theJoin != NULL) + { + theJoin->memoryCompares = 0; + theJoin->memoryLeftAdds = 0; + theJoin->memoryRightAdds = 0; + theJoin->memoryLeftDeletes = 0; + theJoin->memoryRightDeletes = 0; + + if (theJoin->joinFromTheRight) + { theJoin = (struct joinNode *) theJoin->rightSideEntryStructure; } + else + { theJoin = theJoin->lastLevel; } + } + } + +/************************************************/ +/* JoinActivityResetCommand: H/L access routine */ +/* for the reset-join-activity command. */ +/************************************************/ +globle void JoinActivityResetCommand( + void *theEnv) + { + DoForAllConstructs(theEnv,JoinActivityReset,DefruleData(theEnv)->DefruleModuleIndex,TRUE,NULL); + } + +/***************************************/ +/* TimetagFunction: H/L access routine */ +/* for the timetag function. */ +/***************************************/ +globle long long TimetagFunction( + void *theEnv) + { + DATA_OBJECT item; + void *ptr; + + if (EnvArgCountCheck(theEnv,"timetag",EXACTLY,1) == -1) return(-1LL); + + ptr = GetFactOrInstanceArgument(theEnv,1,&item,"timetag"); + + if (ptr == NULL) return(-1); + + return ((struct patternEntity *) ptr)->timeTag; } #endif /* DEBUGGING_FUNCTIONS */ @@ -332,7 +1336,7 @@ globle intBool EnvMatches( globle long RuleComplexityCommand( void *theEnv) { - char *ruleName; + const char *ruleName; struct defrule *rulePtr; ruleName = GetConstructName(theEnv,"rule-complexity","rule name"); @@ -355,7 +1359,7 @@ globle long RuleComplexityCommand( globle void ShowJoinsCommand( void *theEnv) { - char *ruleName; + const char *ruleName; void *rulePtr; ruleName = GetConstructName(theEnv,"show-joins","rule name"); @@ -385,6 +1389,7 @@ static void ShowJoins( struct joinNode *theJoin; struct joinNode *joinList[MAXIMUM_NUMBER_OF_PATTERNS]; int numberOfJoins; + char rhsType; rulePtr = (struct defrule *) theRule; @@ -403,7 +1408,11 @@ static void ShowJoins( while (theJoin != NULL) { if (theJoin->joinFromTheRight) - { theJoin = (struct joinNode *) theJoin->rightSideEntryStructure; } + { + numberOfJoins++; + joinList[numberOfJoins] = theJoin; + theJoin = (struct joinNode *) theJoin->rightSideEntryStructure; + } else { numberOfJoins++; @@ -419,12 +1428,65 @@ static void ShowJoins( while (numberOfJoins >= 0) { char buffer[20]; - sprintf(buffer,"%2d%c%c: ",(int) joinList[numberOfJoins]->depth, - (joinList[numberOfJoins]->patternIsNegated) ? 'n' : ' ', + + if (joinList[numberOfJoins]->patternIsNegated) + { rhsType = 'n'; } + else if (joinList[numberOfJoins]->patternIsExists) + { rhsType = 'x'; } + else + { rhsType = ' '; } + + gensprintf(buffer,"%2d%c%c%c%c : ",(int) joinList[numberOfJoins]->depth, + (joinList[numberOfJoins]->firstJoin) ? 'f' : ' ', + rhsType, + (joinList[numberOfJoins]->joinFromTheRight) ? 'j' : ' ', (joinList[numberOfJoins]->logicalJoin) ? 'l' : ' '); EnvPrintRouter(theEnv,WDISPLAY,buffer); PrintExpression(theEnv,WDISPLAY,joinList[numberOfJoins]->networkTest); EnvPrintRouter(theEnv,WDISPLAY,"\n"); + + if (joinList[numberOfJoins]->ruleToActivate != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," RA : "); + EnvPrintRouter(theEnv,WDISPLAY,EnvGetDefruleName(theEnv,joinList[numberOfJoins]->ruleToActivate)); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (joinList[numberOfJoins]->secondaryNetworkTest != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," SNT : "); + PrintExpression(theEnv,WDISPLAY,joinList[numberOfJoins]->secondaryNetworkTest); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (joinList[numberOfJoins]->leftHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," LH : "); + PrintExpression(theEnv,WDISPLAY,joinList[numberOfJoins]->leftHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (joinList[numberOfJoins]->rightHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," RH : "); + PrintExpression(theEnv,WDISPLAY,joinList[numberOfJoins]->rightHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (! joinList[numberOfJoins]->firstJoin) + { + EnvPrintRouter(theEnv,WDISPLAY," LM : "); + if (PrintBetaMemory(theEnv,WDISPLAY,joinList[numberOfJoins]->leftMemory,FALSE," ",SUCCINCT) == 0) + { EnvPrintRouter(theEnv,WDISPLAY,"None\n"); } + } + + if (joinList[numberOfJoins]->joinFromTheRight) + { + EnvPrintRouter(theEnv,WDISPLAY," RM : "); + if (PrintBetaMemory(theEnv,WDISPLAY,joinList[numberOfJoins]->rightMemory,FALSE," ",SUCCINCT) == 0) + { EnvPrintRouter(theEnv,WDISPLAY,"None\n"); } + } + numberOfJoins--; }; @@ -437,7 +1499,93 @@ static void ShowJoins( } } +/******************************************************/ +/* ShowAlphaHashTable: Displays the number of entries */ +/* in each slot of the alpha hash table. */ +/******************************************************/ +globle void ShowAlphaHashTable( + void *theEnv) + { + int i, count; + long totalCount = 0; + struct alphaMemoryHash *theEntry; + struct partialMatch *theMatch; + char buffer[40]; + + for (i = 0; i < ALPHA_MEMORY_HASH_SIZE; i++) + { + for (theEntry = DefruleData(theEnv)->AlphaMemoryTable[i], count = 0; + theEntry != NULL; + theEntry = theEntry->next) + { count++; } + + if (count != 0) + { + totalCount += count; + gensprintf(buffer,"%4d: %4d ->",i,count); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + + for (theEntry = DefruleData(theEnv)->AlphaMemoryTable[i], count = 0; + theEntry != NULL; + theEntry = theEntry->next) + { + for (theMatch = theEntry->alphaMemory; + theMatch != NULL; + theMatch = theMatch->nextInMemory) + { count++; } + + gensprintf(buffer," %4d",count); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + if (theEntry->owner->rightHash == NULL) + { EnvPrintRouter(theEnv,WDISPLAY,"*"); } + } + + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + } + gensprintf(buffer,"Total Count: %ld\n",totalCount); + EnvPrintRouter(theEnv,WDISPLAY,buffer); + } + #endif /* DEVELOPER */ -#endif /* DEFRULE_CONSTRUCT */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + +globle void Matches( + void *theRule, + int output, + DATA_OBJECT *result) + { + EnvMatches(GetCurrentEnvironment(),theRule,output,result); + } + +globle void JoinActivity( + void *theRule, + int output, + DATA_OBJECT *result) + { + EnvJoinActivity(GetCurrentEnvironment(),theRule,output,result); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +globle intBool GetBetaMemoryResizing() + { + return EnvGetBetaMemoryResizing(GetCurrentEnvironment()); + } +globle intBool SetBetaMemoryResizing( + int value) + { + return EnvSetBetaMemoryResizing(GetCurrentEnvironment(),value); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* DEFRULE_CONSTRUCT */ diff --git a/src/rulecom.h b/src/rulecom.h index 2f9fb2e..47b9e70 100644 --- a/src/rulecom.h +++ b/src/rulecom.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFRULE COMMANDS HEADER FILE */ /*******************************************************/ @@ -16,11 +16,36 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ -/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES */ +/* INCREMENTAL_RESET, and LOGICAL_DEPENDENCIES */ +/* compilation flags. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Improvements to matches command. */ +/* */ +/* Add join-activity and join-activity-reset */ +/* commands. */ +/* */ +/* Added get-beta-memory-resizing and */ +/* set-beta-memory-resizing functions. */ +/* */ +/* Added timetag function. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ /* */ /*************************************************************/ @@ -41,20 +66,54 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Matches(theEnv,a) EnvMatches(theEnv,a) -#else -#define Matches(a) EnvMatches(GetCurrentEnvironment(),a) -#endif +struct joinInformation + { + int whichCE; + struct joinNode *theJoin; + int patternBegin; + int patternEnd; + int marked; + struct betaMemory *theMemory; + struct joinNode *nextJoin; + }; - LOCALE intBool EnvMatches(void *,void *); +#define VERBOSE 0 +#define SUCCINCT 1 +#define TERSE 2 + + LOCALE intBool EnvGetBetaMemoryResizing(void *); + LOCALE intBool EnvSetBetaMemoryResizing(void *,intBool); + LOCALE int GetBetaMemoryResizingCommand(void *); + LOCALE int SetBetaMemoryResizingCommand(void *); + + LOCALE void EnvMatches(void *,void *,int,DATA_OBJECT *); + LOCALE void EnvJoinActivity(void *,void *,int,DATA_OBJECT *); LOCALE void DefruleCommands(void *); - LOCALE void MatchesCommand(void *); + LOCALE void MatchesCommand(void *,DATA_OBJECT *); + LOCALE void JoinActivityCommand(void *,DATA_OBJECT *); + LOCALE long long TimetagFunction(void *); + LOCALE long EnvAlphaJoinCount(void *,void *); + LOCALE long EnvBetaJoinCount(void *,void *); + LOCALE struct joinInformation *EnvCreateJoinArray(void *,long); + LOCALE void EnvFreeJoinArray(void *,struct joinInformation *,long); + LOCALE void EnvAlphaJoins(void *,void *,long,struct joinInformation *); + LOCALE void EnvBetaJoins(void *,void *,long,struct joinInformation *); + LOCALE void JoinActivityResetCommand(void *); #if DEVELOPER LOCALE void ShowJoinsCommand(void *); LOCALE long RuleComplexityCommand(void *); + LOCALE void ShowAlphaHashTable(void *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + +#if DEBUGGING_FUNCTIONS + LOCALE void Matches(void *,int,DATA_OBJECT *); + LOCALE void JoinActivity(void *,int,DATA_OBJECT *); #endif + LOCALE intBool GetBetaMemoryResizing(void); + LOCALE intBool SetBetaMemoryResizing(int); +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ +#endif /* _H_rulecom */ diff --git a/src/rulecstr.c b/src/rulecstr.c index 7ef1cce..86c06a7 100644 --- a/src/rulecstr.c +++ b/src/rulecstr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE CONSTRAINTS MODULE */ /*******************************************************/ @@ -19,6 +19,8 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ /*************************************************************/ #define _RULECSTR_SOURCE_ @@ -199,7 +201,7 @@ static intBool MultifieldCardinalityViolation( /*=======================================*/ if (tmpNode->constraints->minFields->value != SymbolData(theEnv)->NegativeInfinity) - { minFields += ValueToLong(tmpNode->constraints->minFields->value); } + { minFields += (long) ValueToLong(tmpNode->constraints->minFields->value); } /*=========================================*/ /* The greatest maximum of all the min/max */ @@ -211,7 +213,7 @@ static intBool MultifieldCardinalityViolation( if (tmpMax->value == SymbolData(theEnv)->PositiveInfinity) { posInfinity = TRUE; } else - { maxFields += ValueToLong(tmpMax->value); } + { maxFields += (long) ValueToLong(tmpMax->value); } } /*================================================*/ @@ -233,9 +235,9 @@ static intBool MultifieldCardinalityViolation( else tempConstraint = CopyConstraintRecord(theEnv,theNode->constraints); ReturnExpression(theEnv,tempConstraint->minFields); ReturnExpression(theEnv,tempConstraint->maxFields); - tempConstraint->minFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long) minFields)); + tempConstraint->minFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long long) minFields)); if (posInfinity) tempConstraint->maxFields = GenConstant(theEnv,SYMBOL,SymbolData(theEnv)->PositiveInfinity); - else tempConstraint->maxFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long) maxFields)); + else tempConstraint->maxFields = GenConstant(theEnv,INTEGER,EnvAddLong(theEnv,(long long) maxFields)); /*================================================================*/ /* Determine the final cardinality for the multifield slot by */ @@ -449,7 +451,7 @@ globle void ConstraintReferenceErrorMessage( /*========================================*/ EnvPrintRouter(theEnv,WERROR,"found in CE #"); - PrintLongInteger(theEnv,WERROR,(long int) whichCE); + PrintLongInteger(theEnv,WERROR,(long int) theExpression->whichCE); if (slotName == NULL) { if (theField > 0) @@ -733,7 +735,11 @@ globle intBool CheckRHSForConstraintErrors( i++; tmpPtr = expressionList->nextArg; expressionList->nextArg = NULL; - if (CheckRHSForConstraintErrors(theEnv,expressionList,theLHS)) return(TRUE); + if (CheckRHSForConstraintErrors(theEnv,expressionList,theLHS)) + { + expressionList->nextArg = tmpPtr; + return(TRUE); + } expressionList->nextArg = tmpPtr; expressionList = expressionList->nextArg; } diff --git a/src/rulecstr.h b/src/rulecstr.h index a34a33a..8d18994 100644 --- a/src/rulecstr.h +++ b/src/rulecstr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE CONSTRAINTS HEADER FILE */ /*******************************************************/ @@ -19,6 +19,8 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ /*************************************************************/ #ifndef _H_rulecstr @@ -45,5 +47,5 @@ int); LOCALE intBool CheckRHSForConstraintErrors(void *,struct expr *,struct lhsParseNode *); -#endif +#endif /* _H_rulecstr */ diff --git a/src/ruledef.c b/src/ruledef.c index c722b30..62bcdbe 100644 --- a/src/ruledef.c +++ b/src/ruledef.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFRULE MODULE */ /*******************************************************/ @@ -15,10 +15,14 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ -/* 6.24: Removed CONFLICT_RESOLUTION_STRATEGIES */ +/* */ +/* 6.24: Removed DYNAMIC_SALIENCE and */ +/* LOGICAL_DEPENDENCIES compilation flags. */ +/* */ +/* Removed CONFLICT_RESOLUTION_STRATEGIES */ /* compilation flag. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ @@ -26,6 +30,31 @@ /* Corrected code to remove run-time program */ /* compiler warnings. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Added EnvGetDisjunctCount and */ +/* EnvGetNthDisjunct functions. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _RULEDEF_SOURCE_ @@ -44,6 +73,7 @@ #include "memalloc.h" #include "pattern.h" #include "retract.h" +#include "reteutil.h" #include "rulebsc.h" #include "rulecom.h" #include "rulepsr.h" @@ -69,13 +99,17 @@ static void InitializeDefruleModules(void *); static void DeallocateDefruleData(void *); static void DestroyDefruleAction(void *,struct constructHeader *,void *); +#if RUN_TIME + static void AddBetaMemoriesToRule(void *,struct joinNode *); +#endif /**********************************************************/ /* InitializeDefrules: Initializes the defrule construct. */ /**********************************************************/ globle void InitializeDefrules( void *theEnv) - { + { + unsigned long i; AllocateEnvironmentData(theEnv,DEFRULE_DATA,sizeof(struct defruleData),DeallocateDefruleData); InitializeEngine(theEnv); @@ -101,23 +135,35 @@ globle void InitializeDefrules( GetConstructNamePointer,GetConstructPPForm, GetConstructModuleItem,EnvGetNextDefrule,SetNextConstruct, EnvIsDefruleDeletable,EnvUndefrule,ReturnDefrule); + + DefruleData(theEnv)->AlphaMemoryTable = (ALPHA_MEMORY_HASH **) + gm3(theEnv,sizeof (ALPHA_MEMORY_HASH *) * ALPHA_MEMORY_HASH_SIZE); + + for (i = 0; i < ALPHA_MEMORY_HASH_SIZE; i++) DefruleData(theEnv)->AlphaMemoryTable[i] = NULL; + + DefruleData(theEnv)->BetaMemoryResizingFlag = TRUE; + + DefruleData(theEnv)->RightPrimeJoins = NULL; + DefruleData(theEnv)->LeftPrimeJoins = NULL; } - -/***************************************************/ + +/**************************************************/ /* DeallocateDefruleData: Deallocates environment */ -/* data for the deffacts construct. */ -/***************************************************/ +/* data for the defrule construct. */ +/**************************************************/ static void DeallocateDefruleData( void *theEnv) { struct defruleModule *theModuleItem; void *theModule; struct activation *theActivation, *tmpActivation; + struct salienceGroup *theGroup, *tmpGroup; #if BLOAD || BLOAD_AND_BSAVE - if (Bloaded(theEnv)) return; + if (Bloaded(theEnv)) + { return; } #endif - + DoForAllConstructs(theEnv,DestroyDefruleAction,DefruleData(theEnv)->DefruleModuleIndex,FALSE,NULL); for (theModule = EnvGetNextDefmodule(theEnv,NULL); @@ -127,43 +173,49 @@ static void DeallocateDefruleData( theModuleItem = (struct defruleModule *) GetModuleItem(theEnv,(struct defmodule *) theModule, DefruleData(theEnv)->DefruleModuleIndex); - + theActivation = theModuleItem->agenda; while (theActivation != NULL) { tmpActivation = theActivation->next; - - if (theActivation->sortedBasis != NULL) - { DestroyPartialMatch(theEnv,theActivation->sortedBasis); } rtn_struct(theEnv,activation,theActivation); - + theActivation = tmpActivation; } -#if ! RUN_TIME + theGroup = theModuleItem->groupings; + while (theGroup != NULL) + { + tmpGroup = theGroup->next; + + rtn_struct(theEnv,salienceGroup,theGroup); + + theGroup = tmpGroup; + } + +#if ! RUN_TIME rtn_struct(theEnv,defruleModule,theModuleItem); #endif } + + rm3(theEnv,DefruleData(theEnv)->AlphaMemoryTable,sizeof (ALPHA_MEMORY_HASH *) * ALPHA_MEMORY_HASH_SIZE); } - + /********************************************************/ /* DestroyDefruleAction: Action used to remove defrules */ /* as a result of DestroyEnvironment. */ /********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDefruleAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif struct defrule *theDefrule = (struct defrule *) theConstruct; - + DestroyDefrule(theEnv,theDefrule); } @@ -187,7 +239,7 @@ static void InitializeDefruleModules( #else NULL, #endif - EnvFindDefrule); + EnvFindDefruleInModule); } /***********************************************/ @@ -200,6 +252,7 @@ static void *AllocateModule( theItem = get_struct(theEnv,defruleModule); theItem->agenda = NULL; + theItem->groupings = NULL; return((void *) theItem); } @@ -221,8 +274,8 @@ static void ReturnModule( globle struct defruleModule *GetDefruleModuleItem( void *theEnv, struct defmodule *theModule) - { - return((struct defruleModule *) GetConstructModuleItemByIndex(theEnv,theModule,DefruleData(theEnv)->DefruleModuleIndex)); + { + return((struct defruleModule *) GetConstructModuleItemByIndex(theEnv,theModule,DefruleData(theEnv)->DefruleModuleIndex)); } /*******************************************************************/ @@ -231,9 +284,20 @@ globle struct defruleModule *GetDefruleModuleItem( /*******************************************************************/ globle void *EnvFindDefrule( void *theEnv, - char *defruleName) - { - return(FindNamedConstruct(theEnv,defruleName,DefruleData(theEnv)->DefruleConstruct)); + const char *defruleName) + { + return(FindNamedConstructInModuleOrImports(theEnv,defruleName,DefruleData(theEnv)->DefruleConstruct)); + } + +/*******************************************************************/ +/* EnvFindDefruleInModule: Searches for a defrule in the list of defrules. */ +/* Returns a pointer to the defrule if found, otherwise NULL. */ +/*******************************************************************/ +globle void *EnvFindDefruleInModule( + void *theEnv, + const char *defruleName) + { + return(FindNamedConstructInModule(theEnv,defruleName,DefruleData(theEnv)->DefruleConstruct)); } /************************************************************/ @@ -245,8 +309,8 @@ globle void *EnvFindDefrule( globle void *EnvGetNextDefrule( void *theEnv, void *defrulePtr) - { - return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) defrulePtr,DefruleData(theEnv)->DefruleModuleIndex)); + { + return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) defrulePtr,DefruleData(theEnv)->DefruleModuleIndex)); } /*******************************************************/ @@ -272,6 +336,259 @@ globle intBool EnvIsDefruleDeletable( return(TRUE); } +/***********************************************************/ +/* EnvGetDisjunctCount: Returns the number of disjuncts of */ +/* a rule (permutations caused by the use of or CEs). */ +/***********************************************************/ +globle long EnvGetDisjunctCount( + void *theEnv, + void *vTheDefrule) + { + struct defrule *theDefrule; + long count = 0; + + for (theDefrule = (struct defrule *) vTheDefrule; + theDefrule != NULL; + theDefrule = theDefrule->disjunct) + { count++; } + + return(count); + } + +/**********************************************************/ +/* EnvGetNthDisjunct: Returns the nth disjunct of a rule. */ +/* The disjunct indices run from 1 to N rather than 0 */ +/* to N - 1. */ +/**********************************************************/ +globle void *EnvGetNthDisjunct( + void *theEnv, + void *vTheDefrule, + long index) + { + struct defrule *theDefrule; + long count = 0; + + for (theDefrule = (struct defrule *) vTheDefrule; + theDefrule != NULL; + theDefrule = theDefrule->disjunct) + { + count++; + if (count == index) + { return theDefrule; } + } + + return(NULL); + } + +#if RUN_TIME + +/******************************************/ +/* DefruleRunTimeInitialize: Initializes */ +/* defrule in a run-time module. */ +/******************************************/ +globle void DefruleRunTimeInitialize( + void *theEnv, + struct joinLink *rightPrime, + struct joinLink *leftPrime) + { + struct defmodule *theModule; + struct defrule *theRule, *theDisjunct; + + DefruleData(theEnv)->RightPrimeJoins = rightPrime; + DefruleData(theEnv)->LeftPrimeJoins = leftPrime; + + SaveCurrentModule(theEnv); + + for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL); + theModule != NULL; + theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,theModule)) + { + EnvSetCurrentModule(theEnv,(void *) theModule); + for (theRule = (struct defrule *) EnvGetNextDefrule(theEnv,NULL); + theRule != NULL; + theRule = (struct defrule *) EnvGetNextDefrule(theEnv,theRule)) + { + for (theDisjunct = theRule; + theDisjunct != NULL; + theDisjunct = theDisjunct->disjunct) + { AddBetaMemoriesToRule(theEnv,theDisjunct->lastJoin); } + } + } + + RestoreCurrentModule(theEnv); + } + + +/******************************************/ +/* AddBetaMemoriesToRule: */ +/******************************************/ +static void AddBetaMemoriesToRule( + void *theEnv, + struct joinNode *theNode) + { + AddBetaMemoriesToJoin(theEnv,theNode); + + if (theNode->lastLevel != NULL) + { AddBetaMemoriesToRule(theEnv,theNode->lastLevel); } + + if (theNode->joinFromTheRight) + { AddBetaMemoriesToRule(theEnv,(struct joinNode *) theNode->rightSideEntryStructure); } + } + +#endif /* RUN_TIME */ + +#if RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE + +/**************************/ +/* AddBetaMemoriesToJoin: */ +/**************************/ +globle void AddBetaMemoriesToJoin( + void *theEnv, + struct joinNode *theNode) + { + if ((theNode->leftMemory != NULL) || (theNode->rightMemory != NULL)) + { return; } + + if ((! theNode->firstJoin) || theNode->patternIsExists || theNode-> patternIsNegated || theNode->joinFromTheRight) + { + if (theNode->leftHash == NULL) + { + theNode->leftMemory = get_struct(theEnv,betaMemory); + theNode->leftMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + theNode->leftMemory->beta[0] = NULL; + theNode->leftMemory->size = 1; + theNode->leftMemory->count = 0; + theNode->leftMemory->last = NULL; + } + else + { + theNode->leftMemory = get_struct(theEnv,betaMemory); + theNode->leftMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + memset(theNode->leftMemory->beta,0,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + theNode->leftMemory->size = INITIAL_BETA_HASH_SIZE; + theNode->leftMemory->count = 0; + theNode->leftMemory->last = NULL; + } + + if (theNode->firstJoin && (theNode->patternIsExists || theNode-> patternIsNegated || theNode->joinFromTheRight)) + { + theNode->leftMemory->beta[0] = CreateEmptyPartialMatch(theEnv); + theNode->leftMemory->beta[0]->owner = theNode; + } + } + else + { theNode->leftMemory = NULL; } + + if (theNode->joinFromTheRight) + { + if (theNode->leftHash == NULL) + { + theNode->rightMemory = get_struct(theEnv,betaMemory); + theNode->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + theNode->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + theNode->rightMemory->beta[0] = NULL; + theNode->rightMemory->last[0] = NULL; + theNode->rightMemory->size = 1; + theNode->rightMemory->count = 0; + } + else + { + theNode->rightMemory = get_struct(theEnv,betaMemory); + theNode->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + theNode->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *) * INITIAL_BETA_HASH_SIZE); + memset(theNode->rightMemory->beta,0,sizeof(struct partialMatch **) * INITIAL_BETA_HASH_SIZE); + memset(theNode->rightMemory->last,0,sizeof(struct partialMatch **) * INITIAL_BETA_HASH_SIZE); + theNode->rightMemory->size = INITIAL_BETA_HASH_SIZE; + theNode->rightMemory->count = 0; + } + } + else if (theNode->rightSideEntryStructure == NULL) + { + theNode->rightMemory = get_struct(theEnv,betaMemory); + theNode->rightMemory->beta = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + theNode->rightMemory->last = (struct partialMatch **) genalloc(theEnv,sizeof(struct partialMatch *)); + theNode->rightMemory->beta[0] = CreateEmptyPartialMatch(theEnv); + theNode->rightMemory->beta[0]->owner = theNode; + theNode->rightMemory->beta[0]->rhsMemory = TRUE; + theNode->rightMemory->last[0] = theNode->rightMemory->beta[0]; + theNode->rightMemory->size = 1; + theNode->rightMemory->count = 1; + } + else + { theNode->rightMemory = NULL; } + } + +#endif /* RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE */ + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDefruleModule( + void *theEnv, + void *theDefrule) + { + return GetConstructModuleName((struct constructHeader *) theDefrule); + } + +globle const char *EnvGetDefruleName( + void *theEnv, + void *theDefrule) + { + return GetConstructNameString((struct constructHeader *) theDefrule); + } + +globle const char *EnvGetDefrulePPForm( + void *theEnv, + void *theDefrule) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDefrule); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *DefruleModule( + void *theDefrule) + { + return EnvDefruleModule(GetCurrentEnvironment(),theDefrule); + } + +globle void *FindDefrule( + const char *defruleName) + { + return EnvFindDefrule(GetCurrentEnvironment(),defruleName); + } + +globle const char *GetDefruleName( + void *theDefrule) + { + return EnvGetDefruleName(GetCurrentEnvironment(),theDefrule); + } + +globle const char *GetDefrulePPForm( + void *theDefrule) + { + return EnvGetDefrulePPForm(GetCurrentEnvironment(),theDefrule); + } + +globle void *GetNextDefrule( + void *defrulePtr) + { + return EnvGetNextDefrule(GetCurrentEnvironment(),defrulePtr); + } + +globle intBool IsDefruleDeletable( + void *vTheDefrule) + { + return EnvIsDefruleDeletable(GetCurrentEnvironment(),vTheDefrule); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFRULE_CONSTRUCT */ diff --git a/src/ruledef.h b/src/ruledef.h index 649cbc2..c138d3d 100644 --- a/src/ruledef.h +++ b/src/ruledef.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFRULE HEADER FILE */ /*******************************************************/ @@ -15,15 +15,46 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ /* 6.24: Removed DYNAMIC_SALIENCE and */ /* LOGICAL_DEPENDENCIES compilation flags. */ /* */ +/* Removed CONFLICT_RESOLUTION_STRATEGIES */ +/* compilation flag. */ +/* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove run-time program */ +/* compiler warnings. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Added additional developer statistics to help */ +/* analyze join network performance. */ +/* */ +/* Added salience groups to improve performance */ +/* with large numbers of activations of different */ +/* saliences. */ +/* */ +/* Added EnvGetDisjunctCount and */ +/* EnvGetNthDisjunct functions. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_ruledef @@ -65,7 +96,6 @@ struct defruleModule; #include "network.h" #endif - struct defrule { struct constructHeader header; @@ -87,16 +117,26 @@ struct defrule struct defruleModule { struct defmoduleItemHeader header; + struct salienceGroup *groupings; struct activation *agenda; }; +#ifndef ALPHA_MEMORY_HASH_SIZE +#define ALPHA_MEMORY_HASH_SIZE 63559L +#endif + #define DEFRULE_DATA 16 struct defruleData - { + { struct construct *DefruleConstruct; int DefruleModuleIndex; - long CurrentEntityTimeTag; + long long CurrentEntityTimeTag; + struct alphaMemoryHash **AlphaMemoryTable; + intBool BetaMemoryResizingFlag; + struct joinLink *RightPrimeJoins; + struct joinLink *LeftPrimeJoins; + #if DEBUGGING_FUNCTIONS unsigned WatchRules; int DeletedRuleDebugFlags; @@ -109,10 +149,6 @@ struct defruleData #endif }; -#define EnvGetDefruleName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDefrulePPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define EnvDefruleModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) - #define DefruleData(theEnv) ((struct defruleData *) GetEnvironmentData(theEnv,DEFRULE_DATA)) #define GetPreviousJoin(theJoin) \ @@ -134,28 +170,36 @@ struct defruleData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DefruleModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefrule(theEnv,a) EnvFindDefrule(theEnv,a) -#define GetDefruleName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDefrulePPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetNextDefrule(theEnv,a) EnvGetNextDefrule(theEnv,a) -#define IsDefruleDeletable(theEnv,a) EnvIsDefruleDeletable(theEnv,a) -#else -#define DefruleModule(x) GetConstructModuleName((struct constructHeader *) x) -#define FindDefrule(a) EnvFindDefrule(GetCurrentEnvironment(),a) -#define GetDefruleName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDefrulePPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetNextDefrule(a) EnvGetNextDefrule(GetCurrentEnvironment(),a) -#define IsDefruleDeletable(a) EnvIsDefruleDeletable(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeDefrules(void *); - LOCALE void *EnvFindDefrule(void *,char *); + LOCALE void *EnvFindDefrule(void *,const char *); + LOCALE void *EnvFindDefruleInModule(void *,const char *); LOCALE void *EnvGetNextDefrule(void *,void *); LOCALE struct defruleModule *GetDefruleModuleItem(void *,struct defmodule *); LOCALE intBool EnvIsDefruleDeletable(void *,void *); - +#if RUN_TIME + LOCALE void DefruleRunTimeInitialize(void *,struct joinLink *,struct joinLink *); #endif +#if RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE + LOCALE void AddBetaMemoriesToJoin(void *,struct joinNode *); +#endif + LOCALE long EnvGetDisjunctCount(void *,void *); + LOCALE void *EnvGetNthDisjunct(void *,void *,long); + LOCALE const char *EnvDefruleModule(void *,void *); + LOCALE const char *EnvGetDefruleName(void *,void *); + LOCALE const char *EnvGetDefrulePPForm(void *,void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE const char *DefruleModule(void *); + LOCALE void *FindDefrule(const char *); + LOCALE const char *GetDefruleName(void *); + LOCALE const char *GetDefrulePPForm(void *); + LOCALE void *GetNextDefrule(void *); + LOCALE intBool IsDefruleDeletable(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + + +#endif /* _H_ruledef */ diff --git a/src/ruledlt.c b/src/ruledlt.c index ab9daa5..8ab108e 100644 --- a/src/ruledlt.c +++ b/src/ruledlt.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE DELETION MODULE */ /*******************************************************/ @@ -22,6 +22,15 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #define _RULEDLT_SOURCE_ @@ -57,7 +66,8 @@ #if (! RUN_TIME) && (! BLOAD_ONLY) static void RemoveIntranetworkLink(void *,struct joinNode *); #endif - static void DetachJoins(void *,struct defrule *,intBool); + static void DetachJoins(void *,struct joinNode *,intBool); + static void DetachJoinsDriver(void *,struct defrule *,intBool); /**********************************************************************/ /* ReturnDefrule: Returns a defrule data structure and its associated */ @@ -70,14 +80,10 @@ globle void ReturnDefrule( void *theEnv, void *vWaste) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vWaste) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) struct defrule *waste = (struct defrule *) vWaste; int first = TRUE; - struct defrule *nextPtr; + struct defrule *nextPtr, *tmpPtr; if (waste == NULL) return; @@ -110,7 +116,7 @@ globle void ReturnDefrule( /* Remove the rule's joins from the join network. */ /*================================================*/ - DetachJoins(theEnv,waste,FALSE); + DetachJoinsDriver(theEnv,waste,FALSE); /*=============================================*/ /* If this is the first disjunct, get rid of */ @@ -127,8 +133,16 @@ globle void ReturnDefrule( } if (waste->header.ppForm != NULL) { - rm(theEnv,waste->header.ppForm,strlen(waste->header.ppForm) + 1); + rm(theEnv,(void *) waste->header.ppForm,strlen(waste->header.ppForm) + 1); waste->header.ppForm = NULL; + + /*=======================================================*/ + /* All of the rule disjuncts share the same pretty print */ + /* form, so we want to avoid deleting it again. */ + /*=======================================================*/ + + for (tmpPtr = waste->disjunct; tmpPtr != NULL; tmpPtr = tmpPtr->disjunct) + { tmpPtr->header.ppForm = NULL; } } first = FALSE; @@ -137,10 +151,10 @@ globle void ReturnDefrule( /*===========================*/ /* Get rid of any user data. */ /*===========================*/ - + if (waste->header.usrData != NULL) { ClearUserDataList(theEnv,waste->header.usrData); } - + /*===========================================*/ /* Decrement the count for the defrule name. */ /*===========================================*/ @@ -185,12 +199,12 @@ globle void DestroyDefrule( struct defrule *theDefrule = (struct defrule *) vTheDefrule; struct defrule *nextDisjunct; int first = TRUE; - + if (theDefrule == NULL) return; - + while (theDefrule != NULL) { - DetachJoins(theEnv,theDefrule,TRUE); + DetachJoinsDriver(theEnv,theDefrule,TRUE); if (first) { @@ -199,22 +213,34 @@ globle void DestroyDefrule( { ReturnPackedExpression(theEnv,theDefrule->dynamicSalience); } if (theDefrule->header.ppForm != NULL) - { rm(theEnv,theDefrule->header.ppForm,strlen(theDefrule->header.ppForm) + 1); } + { + struct defrule *tmpPtr; + + rm(theEnv,(void *) theDefrule->header.ppForm,strlen(theDefrule->header.ppForm) + 1); + + /*=======================================================*/ + /* All of the rule disjuncts share the same pretty print */ + /* form, so we want to avoid deleting it again. */ + /*=======================================================*/ + + for (tmpPtr = theDefrule->disjunct; tmpPtr != NULL; tmpPtr = tmpPtr->disjunct) + { tmpPtr->header.ppForm = NULL; } + } #endif first = FALSE; } - + if (theDefrule->header.usrData != NULL) { ClearUserDataList(theEnv,theDefrule->header.usrData); } - + #if (! BLOAD_ONLY) && (! RUN_TIME) if (theDefrule->actions != NULL) { ReturnPackedExpression(theEnv,theDefrule->actions); } #endif - + nextDisjunct = theDefrule->disjunct; - + #if (! BLOAD_ONLY) && (! RUN_TIME) rtn_struct(theEnv,defrule,theDefrule); #endif @@ -224,22 +250,14 @@ globle void DestroyDefrule( } /**********************************************************************/ -/* DetachJoins: Removes a join node and all of its parent nodes from */ -/* the join network. Nodes are only removed if they are no required */ -/* by other rules (the same join can be shared by multiple rules). */ -/* Any partial matches associated with the join are also removed. */ -/* A rule's joins are typically removed by removing the bottom most */ -/* join used by the rule and then removing any parent joins which */ -/* are not shared by other rules. */ +/* DetachJoinsDriver: */ /**********************************************************************/ -static void DetachJoins( +static void DetachJoinsDriver( void *theEnv, struct defrule *theRule, intBool destroy) { struct joinNode *join; - struct joinNode *prevJoin; - struct joinNode *joinPtr, *lastJoin, *rightJoin; /*==================================*/ /* Find the last join for the rule. */ @@ -257,7 +275,28 @@ static void DetachJoins( /*===================================================*/ join->ruleToActivate = NULL; - if (join->nextLevel != NULL) return; + if (join->nextLinks != NULL) return; + + DetachJoins(theEnv,join,destroy); + } + +/**********************************************************************/ +/* DetachJoins: Removes a join node and all of its parent nodes from */ +/* the join network. Nodes are only removed if they are no required */ +/* by other rules (the same join can be shared by multiple rules). */ +/* Any partial matches associated with the join are also removed. */ +/* A rule's joins are typically removed by removing the bottom most */ +/* join used by the rule and then removing any parent joins which */ +/* are not shared by other rules. */ +/**********************************************************************/ +static void DetachJoins( + void *theEnv, + struct joinNode *join, + intBool destroy) + { + struct joinNode *prevJoin, *rightJoin; + struct joinLink *lastLink, *theLink; + int lastMark; /*===========================*/ /* Begin removing the joins. */ @@ -265,6 +304,8 @@ static void DetachJoins( while (join != NULL) { + if (join->marked) return; + /*==========================================================*/ /* Remember the join "above" this join (the one that enters */ /* from the left). If the join is entered from the right by */ @@ -282,7 +323,7 @@ static void DetachJoins( /* any structures associated with the pattern that */ /* are no longer needed. */ /*=================================================*/ - + #if (! RUN_TIME) && (! BLOAD_ONLY) if (! destroy) { @@ -290,78 +331,187 @@ static void DetachJoins( { RemoveIntranetworkLink(theEnv,join); } } #endif - + /*======================================*/ /* Remove any partial matches contained */ /* in the beta memory of the join. */ /*======================================*/ - + if (destroy) - { DestroyAlphaBetaMemory(theEnv,join->beta); } + { + DestroyBetaMemory(theEnv,join,LHS); + DestroyBetaMemory(theEnv,join,RHS); + } else - { FlushAlphaBetaMemory(theEnv,join->beta); } - join->beta = NULL; + { + FlushBetaMemory(theEnv,join,LHS); + FlushBetaMemory(theEnv,join,RHS); + } + + ReturnLeftMemory(theEnv,join); + ReturnRightMemory(theEnv,join); /*===================================*/ /* Remove the expressions associated */ /* with the join. */ /*===================================*/ - + #if (! RUN_TIME) && (! BLOAD_ONLY) if (! destroy) - { RemoveHashedExpression(theEnv,join->networkTest); } + { + RemoveHashedExpression(theEnv,join->networkTest); + RemoveHashedExpression(theEnv,join->secondaryNetworkTest); + RemoveHashedExpression(theEnv,join->leftHash); + RemoveHashedExpression(theEnv,join->rightHash); + } #endif - /*==================================================*/ - /* Remove the link to the join from the join above. */ - /*==================================================*/ + /*============================*/ + /* Fix the right prime links. */ + /*============================*/ - if (prevJoin == NULL) + if (join->firstJoin && (join->rightSideEntryStructure == NULL)) { + lastLink = NULL; + + theLink = DefruleData(theEnv)->RightPrimeJoins; + while (theLink != NULL) + { + if (theLink->join == join) + { + if (lastLink == NULL) + { DefruleData(theEnv)->RightPrimeJoins = theLink->next; } + else + { lastLink->next = theLink->next; } + #if (! RUN_TIME) && (! BLOAD_ONLY) - rtn_struct(theEnv,joinNode,join); + rtn_struct(theEnv,joinLink,theLink); #endif - return; + + theLink = NULL; + } + else + { + lastLink = theLink; + theLink = lastLink->next; + } + } } - lastJoin = NULL; - joinPtr = prevJoin->nextLevel; - while (joinPtr != NULL) + /*===========================*/ + /* Fix the left prime links. */ + /*===========================*/ + + if (join->firstJoin && (join->patternIsNegated || join->joinFromTheRight) && (! join->patternIsExists)) { - if (joinPtr == join) + lastLink = NULL; + theLink = DefruleData(theEnv)->LeftPrimeJoins; + while (theLink != NULL) { - if (lastJoin == NULL) - { prevJoin->nextLevel = joinPtr->rightDriveNode; } - else - { lastJoin->rightDriveNode = joinPtr->rightDriveNode; } + if (theLink->join == join) + { + if (lastLink == NULL) + { DefruleData(theEnv)->LeftPrimeJoins = theLink->next; } + else + { lastLink->next = theLink->next; } - joinPtr = NULL; - } - else - { - lastJoin = joinPtr; - joinPtr = joinPtr->rightDriveNode; +#if (! RUN_TIME) && (! BLOAD_ONLY) + rtn_struct(theEnv,joinLink,theLink); +#endif + + theLink = NULL; + } + else + { + lastLink = theLink; + theLink = theLink->next; + } } - } + } - /*==================*/ - /* Delete the join. */ - /*==================*/ + /*==================================================*/ + /* Remove the link to the join from the join above. */ + /*==================================================*/ + + if (prevJoin != NULL) + { + lastLink = NULL; + theLink = prevJoin->nextLinks; + while (theLink != NULL) + { + if (theLink->join == join) + { + if (lastLink == NULL) + { prevJoin->nextLinks = theLink->next; } + else + { lastLink->next = theLink->next; } #if (! RUN_TIME) && (! BLOAD_ONLY) - rtn_struct(theEnv,joinNode,join); + rtn_struct(theEnv,joinLink,theLink); #endif + theLink = NULL; + } + else + { + lastLink = theLink; + theLink = theLink->next; + } + } + } + /*==========================================*/ /* Remove the right join link if it exists. */ /*==========================================*/ if (rightJoin != NULL) { - rightJoin->nextLevel = NULL; - prevJoin = rightJoin; + lastLink = NULL; + theLink = rightJoin->nextLinks; + while (theLink != NULL) + { + if (theLink->join == join) + { + if (lastLink == NULL) + { rightJoin->nextLinks = theLink->next; } + else + { lastLink->next = theLink->next; } + +#if (! RUN_TIME) && (! BLOAD_ONLY) + rtn_struct(theEnv,joinLink,theLink); +#endif + theLink = NULL; + } + else + { + lastLink = theLink; + theLink = theLink->next; + } + } + + if ((rightJoin->nextLinks == NULL) && + (rightJoin->ruleToActivate == NULL)) + { + if (prevJoin != NULL) + { + lastMark = prevJoin->marked; + prevJoin->marked = TRUE; + DetachJoins(theEnv,rightJoin,destroy); + prevJoin->marked = lastMark; + } + else + { DetachJoins(theEnv,rightJoin,destroy); } + } } + /*==================*/ + /* Delete the join. */ + /*==================*/ + +#if (! RUN_TIME) && (! BLOAD_ONLY) + rtn_struct(theEnv,joinNode,join); +#endif + /*===========================================================*/ /* Move on to the next join to be removed. All the joins of */ /* a rule can be deleted by following the right joins links */ @@ -371,12 +521,14 @@ static void DetachJoins( /* to the join which enters join B from the left. */ /*===========================================================*/ - if (prevJoin->ruleToActivate != NULL) - { join = NULL; } - else if (prevJoin->nextLevel == NULL) + if (prevJoin == NULL) + { return; } + else if (prevJoin->ruleToActivate != NULL) + { return; } + else if (prevJoin->nextLinks == NULL) { join = prevJoin; } else - { join = NULL; } + { return; } } } diff --git a/src/ruledlt.h b/src/ruledlt.h index fbde709..8ccc6d2 100644 --- a/src/ruledlt.h +++ b/src/ruledlt.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE DELETION MODULE HEADER FILE */ /*******************************************************/ @@ -18,6 +18,19 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Removed DYNAMIC_SALIENCE compilation flag. */ +/* */ +/* Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Fixed linkage issue when BLOAD_ONLY compiler */ +/* flag is set to 1. */ +/* */ /*************************************************************/ #ifndef _H_ruledlt @@ -37,7 +50,7 @@ LOCALE void ReturnDefrule(void *,void *); LOCALE void DestroyDefrule(void *,void *); -#endif +#endif /* _H_ruledlt */ diff --git a/src/rulelhs.c b/src/rulelhs.c index 220024a..a25da33 100644 --- a/src/rulelhs.c +++ b/src/rulelhs.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 07/25/14 */ /* */ /* DEFRULE LHS PARSING MODULE */ /*******************************************************/ @@ -17,6 +17,9 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _RULELHS_SOURCE_ @@ -51,18 +54,18 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct lhsParseNode *RuleBodyParse(void *,char *,struct token *,char *,int *); - static void DeclarationParse(void *,char *,char *,int *); - static struct lhsParseNode *LHSPattern(void *,char *,int,char *,int *,int, - struct token *,char *); - static struct lhsParseNode *ConnectedPatternParse(void *,char *,struct token *,int *); - static struct lhsParseNode *GroupPatterns(void *,char *,int,char *,int *); - static struct lhsParseNode *TestPattern(void *,char *,int *); - static struct lhsParseNode *AssignmentParse(void *,char *,SYMBOL_HN *,int *); + static struct lhsParseNode *RuleBodyParse(void *,const char *,struct token *,const char *,int *); + static void DeclarationParse(void *,const char *,const char *,int *); + static struct lhsParseNode *LHSPattern(void *,const char *,int,const char *,int *,int, + struct token *,const char *); + static struct lhsParseNode *ConnectedPatternParse(void *,const char *,struct token *,int *); + static struct lhsParseNode *GroupPatterns(void *,const char *,int,const char *,int *); + static struct lhsParseNode *TestPattern(void *,const char *,int *); + static struct lhsParseNode *AssignmentParse(void *,const char *,SYMBOL_HN *,int *); static void TagLHSLogicalNodes(struct lhsParseNode *); - static struct lhsParseNode *SimplePatternParse(void *,char *,struct token *,int *); - static void ParseSalience(void *,char *,char *,int *); - static void ParseAutoFocus(void *,char *,int *); + static struct lhsParseNode *SimplePatternParse(void *,const char *,struct token *,int *); + static void ParseSalience(void *,const char *,const char *,int *); + static void ParseAutoFocus(void *,const char *,int *); /*******************************************************************/ /* ParseRuleLHS: Coordinates all the actions necessary for parsing */ @@ -71,13 +74,15 @@ /*******************************************************************/ globle struct lhsParseNode *ParseRuleLHS( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, - char *ruleName) + const char *ruleName, + int *error) { struct lhsParseNode *theLHS; int result; - int error = FALSE; + + *error = FALSE; /*========================================*/ /* Initialize salience parsing variables. */ @@ -97,9 +102,9 @@ globle struct lhsParseNode *ParseRuleLHS( /* Get the raw representation for the LHS of the rule. */ /*=====================================================*/ - theLHS = RuleBodyParse(theEnv,readSource,theToken,ruleName,&error); + theLHS = RuleBodyParse(theEnv,readSource,theToken,ruleName,error); - if (error) return(NULL); + if (*error) return(NULL); /*====================================================*/ /* Reorder the raw representation so that it consists */ @@ -127,9 +132,9 @@ globle struct lhsParseNode *ParseRuleLHS( /*********************************************************/ static struct lhsParseNode *RuleBodyParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, - char *ruleName, + const char *ruleName, int *error) { struct lhsParseNode *theNode, *otherNodes; @@ -203,8 +208,8 @@ static struct lhsParseNode *RuleBodyParse( /********************************************************/ static void DeclarationParse( void *theEnv, - char *readSource, - char *ruleName, + const char *readSource, + const char *ruleName, int *error) { struct token theToken; @@ -280,14 +285,14 @@ static void DeclarationParse( ParseAutoFocus(theEnv,readSource,error); autoFocusParsed = TRUE; } - } + } - /*==========================================*/ - /* Otherwise the symbol does not correspond */ - /* to a valid rule property. */ - /*==========================================*/ + /*==========================================*/ + /* Otherwise the symbol does not correspond */ + /* to a valid rule property. */ + /*==========================================*/ - else + else { SyntaxErrorMessage(theEnv,"declare statement"); *error = TRUE; @@ -360,8 +365,8 @@ static void DeclarationParse( /************************************************************/ static void ParseSalience( void *theEnv, - char *readSource, - char *ruleName, + const char *readSource, + const char *ruleName, int *error) { int salience; @@ -432,7 +437,7 @@ static void ParseSalience( /**************************************************************/ static void ParseAutoFocus( void *theEnv, - char *readSource, + const char *readSource, int *error) { struct token theToken; @@ -482,13 +487,13 @@ static void ParseAutoFocus( /*****************************************************************/ static struct lhsParseNode *LHSPattern( void *theEnv, - char *readSource, + const char *readSource, int terminator, - char *terminatorString, + const char *terminatorString, int *error, int allowDeclaration, struct token *firstToken, - char *ruleName) + const char *ruleName) { struct token theToken; struct lhsParseNode *theNode; @@ -631,13 +636,13 @@ static struct lhsParseNode *LHSPattern( /*********************************************************************/ static struct lhsParseNode *ConnectedPatternParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int *error) { unsigned short connectorValue = 0; struct lhsParseNode *theNode, *tempNode, *theGroup; - char *errorCE = NULL; + const char *errorCE = NULL; int logical = FALSE; int tempValue; @@ -876,9 +881,9 @@ static struct lhsParseNode *ConnectedPatternParse( /***********************************************/ static struct lhsParseNode *GroupPatterns( void *theEnv, - char *readSource, + const char *readSource, int terminator, - char *terminatorString, + const char *terminatorString, int *error) { struct lhsParseNode *lastNode, *newNode, *theNode; @@ -953,7 +958,7 @@ static struct lhsParseNode *GroupPatterns( /**************************************************************/ static struct lhsParseNode *TestPattern( void *theEnv, - char *readSource, + const char *readSource, int *error) { struct lhsParseNode *theNode; @@ -1006,7 +1011,7 @@ static struct lhsParseNode *TestPattern( /****************************************************************/ static struct lhsParseNode *AssignmentParse( void *theEnv, - char *readSource, + const char *readSource, SYMBOL_HN *factAddress, int *error) { @@ -1107,7 +1112,7 @@ static void TagLHSLogicalNodes( /***********************************************************/ static struct lhsParseNode *SimplePatternParse( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int *error) { @@ -1141,6 +1146,7 @@ static struct lhsParseNode *SimplePatternParse( theNode = GetLHSParseNode(theEnv); theNode->type = PATTERN_CE; theNode->negated = FALSE; + theNode->exists = FALSE; /*======================================================*/ /* Search for a pattern parser that claims the pattern. */ diff --git a/src/rulelhs.h b/src/rulelhs.h index 8acccd5..3665e16 100644 --- a/src/rulelhs.h +++ b/src/rulelhs.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 07/25/14 */ /* */ /* DEFRULE LHS PARSING HEADER FILE */ /*******************************************************/ @@ -17,6 +17,9 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_rulelhs @@ -45,7 +48,7 @@ #define LOCALE extern #endif -LOCALE struct lhsParseNode *ParseRuleLHS(void *,char *,struct token *,char *); +LOCALE struct lhsParseNode *ParseRuleLHS(void *,const char *,struct token *,const char *,int *); LOCALE void PropagatePatternType(struct lhsParseNode *,struct patternParser *); #endif diff --git a/src/rulepsr.c b/src/rulepsr.c index 2999c40..b1c9ed5 100644 --- a/src/rulepsr.c +++ b/src/rulepsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* RULE PARSING MODULE */ /*******************************************************/ @@ -19,6 +19,23 @@ /* 6.24: Removed DYNAMIC_SALIENCE, INCREMENTAL_RESET, */ /* and LOGICAL_DEPENDENCIES compilation flags. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _RULEPSR_SOURCE_ @@ -73,9 +90,9 @@ /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static struct expr *ParseRuleRHS(void *,char *); + static struct expr *ParseRuleRHS(void *,const char *); static int ReplaceRHSVariable(void *,struct expr *,void *); - static struct defrule *ProcessRuleLHS(void *,struct lhsParseNode *,struct expr *,SYMBOL_HN *,short *); + static struct defrule *ProcessRuleLHS(void *,struct lhsParseNode *,struct expr *,SYMBOL_HN *,int *); static struct defrule *CreateNewDisjunct(void *,SYMBOL_HN *,int,struct expr *, int,unsigned,struct joinNode *); static int RuleComplexity(void *,struct lhsParseNode *); @@ -91,12 +108,8 @@ /****************************************************/ globle int ParseDefrule( void *theEnv, - char *readSource) + const char *readSource) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,readSource) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) SYMBOL_HN *ruleName; struct lhsParseNode *theLHS; @@ -104,7 +117,7 @@ globle int ParseDefrule( struct token theToken; struct defrule *topDisjunct, *tempPtr; struct defruleModule *theModuleItem; - short error; + int error; /*================================================*/ /* Flush the buffer which stores the pretty print */ @@ -138,8 +151,8 @@ globle int ParseDefrule( #endif ruleName = GetConstructNameAndComment(theEnv,readSource,&theToken,"defrule", - EnvFindDefrule,EnvUndefrule,"*",FALSE, - TRUE,TRUE); + EnvFindDefruleInModule,EnvUndefrule,"*",FALSE, + TRUE,TRUE,FALSE); if (ruleName == NULL) return(TRUE); @@ -147,8 +160,8 @@ globle int ParseDefrule( /* Parse the LHS of the rule. */ /*============================*/ - theLHS = ParseRuleLHS(theEnv,readSource,&theToken,ValueToString(ruleName)); - if (theLHS == NULL) + theLHS = ParseRuleLHS(theEnv,readSource,&theToken,ValueToString(ruleName),&error); + if (error) { ReturnPackedExpression(theEnv,PatternData(theEnv)->SalienceExpression); PatternData(theEnv)->SalienceExpression = NULL; @@ -220,7 +233,10 @@ globle int ParseDefrule( GetModuleItem(theEnv,NULL,FindModuleItem(theEnv,"defrule")->moduleIndex); for (tempPtr = topDisjunct; tempPtr != NULL; tempPtr = tempPtr->disjunct) - { tempPtr->header.whichModule = (struct defmoduleItemHeader *) theModuleItem; } + { + tempPtr->header.whichModule = (struct defmoduleItemHeader *) theModuleItem; + tempPtr->header.ppForm = topDisjunct->header.ppForm; + } /*===============================================*/ /* Rule completely parsed. Add to list of rules. */ @@ -265,7 +281,7 @@ static struct defrule *ProcessRuleLHS( struct lhsParseNode *theLHS, struct expr *actions, SYMBOL_HN *ruleName, - short *error) + int *error) { struct lhsParseNode *tempNode = NULL; struct defrule *topDisjunct = NULL, *currentDisjunct, *lastDisjunct = NULL; @@ -274,6 +290,7 @@ static struct defrule *ProcessRuleLHS( int localVarCnt; int complexity; struct joinNode *lastJoin; + intBool emptyLHS; /*================================================*/ /* Initially set the parsing error flag to FALSE. */ @@ -287,23 +304,33 @@ static struct defrule *ProcessRuleLHS( /* top level of the pattern construct, then remove it. */ /*===========================================================*/ - if (theLHS->type == OR_CE) theLHS = theLHS->right; + if (theLHS == NULL) + { emptyLHS = TRUE; } + else + { + emptyLHS = FALSE; + if (theLHS->type == OR_CE) theLHS = theLHS->right; + } /*=========================================*/ /* Loop through each disjunct of the rule. */ /*=========================================*/ localVarCnt = CountParsedBindNames(theEnv); - for (; - theLHS != NULL; - theLHS = theLHS->bottom) + + while ((theLHS != NULL) || (emptyLHS == TRUE)) { /*===================================*/ /* Analyze the LHS of this disjunct. */ /*===================================*/ - if (theLHS->type == AND_CE) tempNode = theLHS->right; - else if (theLHS->type == PATTERN_CE) tempNode = theLHS; + if (emptyLHS) + { tempNode = NULL; } + else + { + if (theLHS->type == AND_CE) tempNode = theLHS->right; + else if (theLHS->type == PATTERN_CE) tempNode = theLHS; + } if (VariableAnalysis(theEnv,tempNode)) { @@ -328,25 +355,8 @@ static struct defrule *ProcessRuleLHS( /*========================================================*/ #if DEVELOPER && DEBUGGING_FUNCTIONS -/* if (EnvGetWatchItem(theEnv,"rule-analysis")) - { - struct lhsParseNode *traceNode; - char buffer[20]; - - EnvPrintRouter(theEnv,WDISPLAY,"\n"); - for (traceNode = tempNode; traceNode != NULL; traceNode = traceNode->bottom) - { - if (traceNode->userCE) - { - sprintf(buffer,"CE %2d: ",traceNode->whichCE); - EnvPrintRouter(theEnv,WDISPLAY,buffer); - PrintExpression(theEnv,WDISPLAY,traceNode->networkTest); - EnvPrintRouter(theEnv,WDISPLAY,"\n"); - } - } - } -*/ + { DumpRuleAnalysis(theEnv,tempNode); } #endif /*========================================*/ @@ -395,6 +405,10 @@ static struct defrule *ProcessRuleLHS( if (ConstructData(theEnv)->CheckSyntaxMode) { ReturnExpression(theEnv,newActions); + if (emptyLHS) + { emptyLHS = FALSE; } + else + { theLHS = theLHS->bottom; } continue; } @@ -410,7 +424,7 @@ static struct defrule *ProcessRuleLHS( /* Create the pattern and join data structures for the new rule. */ /*===============================================================*/ - lastJoin = ConstructJoins(theEnv,logicalJoin,tempNode); + lastJoin = ConstructJoins(theEnv,logicalJoin,tempNode,1,NULL,TRUE,TRUE); /*===================================================================*/ /* Determine the rule's complexity for use with conflict resolution. */ @@ -447,6 +461,11 @@ static struct defrule *ProcessRuleLHS( /*===========================================*/ lastDisjunct = currentDisjunct; + + if (emptyLHS) + { emptyLHS = FALSE; } + else + { theLHS = theLHS->bottom; } } return(topDisjunct); @@ -581,7 +600,7 @@ static int ReplaceRHSVariable( /*================================================*/ if (theVariable->patternType != NULL) - { (*theVariable->patternType->replaceGetJNValueFunction)(theEnv,list,theVariable); } + { (*theVariable->patternType->replaceGetJNValueFunction)(theEnv,list,theVariable,LHS); } else { return(FALSE); } @@ -598,7 +617,7 @@ static int ReplaceRHSVariable( /*******************************************************/ static struct expr *ParseRuleRHS( void *theEnv, - char *readSource) + const char *readSource) { struct expr *actions; struct token theToken; @@ -726,9 +745,11 @@ static int LogicalAnalysis( void *theEnv, struct lhsParseNode *patternList) { - int firstLogical, logicalsFound = FALSE, logicalJoin = 0; + int firstLogical, logicalsFound = FALSE, logicalJoin = 1; int gap = FALSE; + if (patternList == NULL) return(0); + firstLogical = patternList->logical; /*===================================================*/ @@ -844,6 +865,7 @@ globle struct lhsParseNode *FindVariable( if ((theLHS->type != PATTERN_CE) || (theLHS->negated == TRUE) || + (theLHS->exists == TRUE) || (theLHS->beginNandDepth > 1)) { continue; } @@ -924,17 +946,90 @@ static void AddToDefruleList( { theModuleItem->header.firstItem = (struct constructHeader *) rulePtr; } else { - tempRule = (struct defrule *) theModuleItem->header.lastItem; - while (tempRule != NULL) - { - tempRule->header.next = (struct constructHeader *) rulePtr; - tempRule = tempRule->disjunct; - } + tempRule = (struct defrule *) theModuleItem->header.lastItem; // Note: Only the first disjunct + tempRule->header.next = (struct constructHeader *) rulePtr; // points to the next rule } theModuleItem->header.lastItem = (struct constructHeader *) rulePtr; } +#if DEVELOPER && DEBUGGING_FUNCTIONS + +/************************************************************/ +/* DumpRuleAnalysis: Displays the information about network */ +/* expressions generated from the analysis of the rule. */ +/************************************************************/ +globle void DumpRuleAnalysis( + void *theEnv, + struct lhsParseNode *tempNode) + { + struct lhsParseNode *traceNode; + char buffer[20]; + + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + for (traceNode = tempNode; traceNode != NULL; traceNode = traceNode->bottom) + { + if (traceNode->userCE) + { gensprintf(buffer,"UCE %2d (%2d %2d): ",traceNode->whichCE,traceNode->beginNandDepth,traceNode->endNandDepth); } + else + { gensprintf(buffer,"SCE %2d (%2d %2d): ",traceNode->whichCE,traceNode->beginNandDepth,traceNode->endNandDepth); } + + EnvPrintRouter(theEnv,WDISPLAY,buffer); + + PrintExpression(theEnv,WDISPLAY,traceNode->networkTest); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + + if (traceNode->externalNetworkTest != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," ENT: "); + PrintExpression(theEnv,WDISPLAY,traceNode->externalNetworkTest); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->secondaryNetworkTest != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," SNT: "); + PrintExpression(theEnv,WDISPLAY,traceNode->secondaryNetworkTest); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->externalRightHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," ERH: "); + PrintExpression(theEnv,WDISPLAY,traceNode->externalRightHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->externalLeftHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," ELH: "); + PrintExpression(theEnv,WDISPLAY,traceNode->externalLeftHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->leftHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," LH: "); + PrintExpression(theEnv,WDISPLAY,traceNode->leftHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->rightHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," RH: "); + PrintExpression(theEnv,WDISPLAY,traceNode->rightHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + + if (traceNode->betaHash != NULL) + { + EnvPrintRouter(theEnv,WDISPLAY," BH: "); + PrintExpression(theEnv,WDISPLAY,traceNode->betaHash); + EnvPrintRouter(theEnv,WDISPLAY,"\n"); + } + } + } +#endif #endif /* (! RUN_TIME) && (! BLOAD_ONLY) */ diff --git a/src/rulepsr.h b/src/rulepsr.h index a6ba190..1103951 100644 --- a/src/rulepsr.h +++ b/src/rulepsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* RULE PARSING HEADER FILE */ /*******************************************************/ @@ -16,6 +16,22 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Removed DYNAMIC_SALIENCE, INCREMENTAL_RESET, */ +/* and LOGICAL_DEPENDENCIES compilation flags. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Added support for hashed memories. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_rulepsr @@ -31,10 +47,13 @@ #define LOCALE extern #endif - LOCALE int ParseDefrule(void *,char *); + LOCALE int ParseDefrule(void *,const char *); LOCALE struct lhsParseNode *FindVariable(struct symbolHashNode *, struct lhsParseNode *); - +#if DEVELOPER && DEBUGGING_FUNCTIONS + LOCALE void DumpRuleAnalysis(void *,struct lhsParseNode *); #endif +#endif /* _H_rulepsr */ + diff --git a/src/scanner.c b/src/scanner.c index 8850b6c..c309f34 100644 --- a/src/scanner.c +++ b/src/scanner.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SCANNER MODULE */ /*******************************************************/ @@ -15,10 +15,21 @@ /* */ /* Contributing Programmer(s): */ /* Chris Culbert */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added SetLineCount function. */ +/* */ +/* Added UTF-8 support. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _SCANNER_SOURCE_ @@ -28,6 +39,7 @@ #define _STDIO_INCLUDED_ #include <string.h> #include <limits.h> +#include <errno.h> #include "setup.h" #include "constant.h" @@ -36,6 +48,7 @@ #include "symbol.h" #include "utility.h" #include "memalloc.h" +#include "sysdep.h" #include "scanner.h" @@ -45,9 +58,9 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static void *ScanSymbol(void *,char *,int,unsigned short *); - static void *ScanString(void *,char *); - static void ScanNumber(void *,char *,struct token *); + static void *ScanSymbol(void *,const char *,int,unsigned short *); + static void *ScanString(void *,const char *); + static void ScanNumber(void *,const char *,struct token *); static void DeallocateScannerData(void *); /************************************************/ @@ -59,7 +72,7 @@ globle void InitializeScannerData( { AllocateEnvironmentData(theEnv,SCANNER_DATA,sizeof(struct scannerData),DeallocateScannerData); } - + /**************************************************/ /* DeallocateScannerData: Deallocates environment */ /* data for scanner routines. */ @@ -81,7 +94,7 @@ static void DeallocateScannerData( /***********************************************************************/ globle void GetToken( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken) { int inchar; @@ -123,7 +136,7 @@ globle void GetToken( /* Process Symbolic Tokens. */ /*==========================*/ - if (isalpha(inchar)) + if (isalpha(inchar) || IsUTF8MultiByteStart(inchar)) { theToken->type = SYMBOL; EnvUngetcRouter(theEnv,inchar,logicalName); @@ -170,7 +183,7 @@ globle void GetToken( case '?': inchar = EnvGetcRouter(theEnv,logicalName); - if (isalpha(inchar) + if (isalpha(inchar) || IsUTF8MultiByteStart(inchar) #if DEFGLOBAL_CONSTRUCT || (inchar == '*')) #else @@ -216,7 +229,7 @@ globle void GetToken( if ((inchar = EnvGetcRouter(theEnv,logicalName)) == '?') { inchar = EnvGetcRouter(theEnv,logicalName); - if (isalpha(inchar) + if (isalpha(inchar) || IsUTF8MultiByteStart(inchar) #if DEFGLOBAL_CONSTRUCT || (inchar == '*')) #else @@ -371,7 +384,7 @@ globle void GetToken( /*************************************/ static void *ScanSymbol( void *theEnv, - char *logicalName, + const char *logicalName, int count, unsigned short *type) { @@ -390,7 +403,9 @@ static void *ScanSymbol( (inchar != '(') && (inchar != ')') && (inchar != '&') && (inchar != '|') && (inchar != '~') && (inchar != ' ') && (inchar != ';') && - isprint(inchar) ) + (isprint(inchar) || + IsUTF8MultiByteStart(inchar) || + IsUTF8MultiByteContinuation(inchar))) { ScannerData(theEnv)->GlobalString = ExpandStringWithChar(theEnv,inchar,ScannerData(theEnv)->GlobalString,&ScannerData(theEnv)->GlobalPos,&ScannerData(theEnv)->GlobalMax,ScannerData(theEnv)->GlobalMax+80); @@ -447,11 +462,11 @@ static void *ScanSymbol( /*************************************/ static void *ScanString( void *theEnv, - char *logicalName) + const char *logicalName) { int inchar; - int pos = 0; - unsigned max = 0; + size_t pos = 0; + size_t max = 0; char *theString = NULL; void *thePtr; @@ -471,7 +486,10 @@ static void *ScanString( } if ((inchar == EOF) && (ScannerData(theEnv)->IgnoreCompletionErrors == FALSE)) - { EnvPrintRouter(theEnv,WERROR,"\nEncountered End-Of-File while scanning a string\n"); } + { + PrintErrorID(theEnv,"SCANNER",1,TRUE); + EnvPrintRouter(theEnv,WERROR,"Encountered End-Of-File while scanning a string\n"); + } /*===============================================*/ /* Add the string to the symbol table and return */ @@ -494,7 +512,7 @@ static void *ScanString( /**************************************/ static void ScanNumber( void *theEnv, - char *logicalName, + const char *logicalName, struct token *theToken) { int count = 0; @@ -502,7 +520,7 @@ static void ScanNumber( int digitFound = FALSE; int processFloat = FALSE; double fvalue; - long lvalue; + long long lvalue; unsigned short type; /* Phases: */ @@ -587,7 +605,7 @@ static void ScanNumber( (inchar == '(') || (inchar == ')') || (inchar == '&') || (inchar == '|') || (inchar == '~') || (inchar == ' ') || (inchar == ';') || - (isprint(inchar) == 0) ) + ((isprint(inchar) == 0) && (! IsUTF8MultiByteStart(inchar))) ) { phase = 5; } else { @@ -614,7 +632,7 @@ static void ScanNumber( (inchar == '(') || (inchar == ')') || (inchar == '&') || (inchar == '|') || (inchar == '~') || (inchar == ' ') || (inchar == ';') || - (isprint(inchar) == 0) ) + ((isprint(inchar) == 0) && (! IsUTF8MultiByteStart(inchar))) ) { phase = 5; } else { @@ -641,7 +659,7 @@ static void ScanNumber( (inchar == '(') || (inchar == ')') || (inchar == '&') || (inchar == '|') || (inchar == '~') || (inchar == ' ') || (inchar == ';') || - (isprint(inchar) == 0) ) + ((isprint(inchar) == 0) && (! IsUTF8MultiByteStart(inchar))) ) { digitFound = FALSE; phase = 5; @@ -664,7 +682,7 @@ static void ScanNumber( (inchar == '(') || (inchar == ')') || (inchar == '&') || (inchar == '|') || (inchar == '~') || (inchar == ' ') || (inchar == ';') || - (isprint(inchar) == 0) ) + ((isprint(inchar) == 0) && (! IsUTF8MultiByteStart(inchar))) ) { if ((ScannerData(theEnv)->GlobalString[count-1] == '+') || (ScannerData(theEnv)->GlobalString[count-1] == '-')) { digitFound = FALSE; } @@ -714,11 +732,16 @@ static void ScanNumber( } else { - lvalue = atol(ScannerData(theEnv)->GlobalString); - if ((lvalue == LONG_MAX) || (lvalue == LONG_MIN)) + errno = 0; +#if WIN_MVC + lvalue = _strtoi64(ScannerData(theEnv)->GlobalString,NULL,10); +#else + lvalue = strtoll(ScannerData(theEnv)->GlobalString,NULL,10); +#endif + if (errno) { PrintWarningID(theEnv,"SCANNER",1,FALSE); - EnvPrintRouter(theEnv,WWARNING,"Over or underflow of long integer.\n"); + EnvPrintRouter(theEnv,WWARNING,"Over or underflow of long long integer.\n"); } theToken->type = INTEGER; theToken->value = (void *) EnvAddLong(theEnv,lvalue); @@ -750,15 +773,32 @@ globle void ResetLineCount( ScannerData(theEnv)->LineCount = 0; } -/****************************************************/ -/* GettLineCount: Returns the scanner's line count. */ -/****************************************************/ +/***************************************************/ +/* GetLineCount: Returns the scanner's line count. */ +/***************************************************/ globle long GetLineCount( void *theEnv) { return(ScannerData(theEnv)->LineCount); } +/***********************************************/ +/* SetLineCount: Sets the scanner's line count */ +/* and returns the previous value. */ +/***********************************************/ +globle long SetLineCount( + void *theEnv, + long value) + { + long oldValue; + + oldValue = ScannerData(theEnv)->LineCount; + + ScannerData(theEnv)->LineCount = value; + + return(oldValue); + } + /**********************************/ /* IncrementLineCount: Increments */ /* the scanner's line count. */ diff --git a/src/scanner.h b/src/scanner.h index 43e8a65..10b7aa8 100644 --- a/src/scanner.h +++ b/src/scanner.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SCANNER HEADER FILE */ /*******************************************************/ @@ -17,6 +17,17 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added SetLineCount function. */ +/* */ +/* Added UTF-8 support. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_scanner @@ -42,16 +53,16 @@ struct token { unsigned short type; void *value; - char *printForm; + const char *printForm; }; #define SCANNER_DATA 57 struct scannerData - { + { char *GlobalString; - unsigned GlobalMax; - int GlobalPos; + size_t GlobalMax; + size_t GlobalPos; long LineCount; int IgnoreCompletionErrors; }; @@ -59,14 +70,15 @@ struct scannerData #define ScannerData(theEnv) ((struct scannerData *) GetEnvironmentData(theEnv,SCANNER_DATA)) LOCALE void InitializeScannerData(void *); - LOCALE void GetToken(void *,char *,struct token *); + LOCALE void GetToken(void *,const char *,struct token *); LOCALE void CopyToken(struct token *,struct token *); LOCALE void ResetLineCount(void *); LOCALE long GetLineCount(void *); + LOCALE long SetLineCount(void *,long); LOCALE void IncrementLineCount(void *); LOCALE void DecrementLineCount(void *); -#endif +#endif /* _H_scanner */ diff --git a/src/setup.h b/src/setup.h index 0c0b5aa..f228caf 100644 --- a/src/setup.h +++ b/src/setup.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/12/06 */ + /* CLIPS Version 6.30 02/05/15 */ /* */ /* SETUP HEADER FILE */ /*******************************************************/ @@ -15,11 +15,12 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.24: Default locale modification. */ /* */ /* Removed CONFLICT_RESOLUTION_STRATEGIES, */ @@ -33,6 +34,48 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, IBM_ICB, IBM_TBC, IBM_ZTC, and */ +/* IBM_SC). */ +/* */ +/* Renamed IBM_MSC and WIN_MVC compiler flags */ +/* and IBM_GCC to WIN_GCC. */ +/* */ +/* Added LINUX and DARWIN compiler flags. */ +/* */ +/* Removed HELP_FUNCTIONS compilation flag and */ +/* associated functionality. */ +/* */ +/* Removed EMACS_EDITOR compilation flag and */ +/* associated functionality. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the single IO_FUNCTIONS flag. */ +/* */ +/* Used #ifndef for preprocessor definitions so */ +/* they can be set at the project or makefile */ +/* level. */ +/* */ +/* Removed ENVIRONMENT_API_ONLY compilation flag. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the IO_FUNCTIONS compilation flag. */ +/* */ +/* Changed the EX_MATH compilation flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Removed VOID definition because of conflict */ +/* with Windows.h header file. */ +/* */ +/* Removed deprecated definitions. */ +/* */ +/* The ALLOW_ENVIRONMENT_GLOBALS flag now */ +/* defaults to 0. The use of functions enabled */ +/* by this flag is deprecated. */ +/* */ +/* Removed support for BLOCK_MEMORY. */ +/* */ /*************************************************************/ #ifndef _H_setup @@ -47,38 +90,63 @@ /* Only one of these flags should be turned on (set to 1) at a time. */ /*********************************************************************/ -#define GENERIC 1 /* Generic (any machine) */ -#define UNIX_V 0 /* UNIX System V, 4.2bsd, HP Unix, Darwin */ -#define UNIX_7 0 /* UNIX System III Version 7 or Sun Unix */ -#define MAC_MCW 0 /* Apple Macintosh, with CodeWarrior 9.6 */ -#define MAC_XCD 0 /* Apple Macintosh, with Xcode 2.3 */ -#define IBM_MCW 0 /* IBM PC, with CodeWarrior 9.4 */ -#define IBM_MSC 0 /* IBM PC, with Microsoft VC++ .NET 2003 */ -#define IBM_TBC 0 /* IBM PC, with Borland C++ 5.0 */ -#define IBM_GCC 0 /* IBM PC, with DJGPP 3.21 */ - /* The following are unsupported: */ -#define IBM_ZTC 0 /* IBM PC, with Zortech C++ 3.1 */ -#define IBM_ICB 0 /* IBM PC, with Intel C Code Builder 1.0 */ -#define IBM_SC 0 /* IBM PC, with Symantec C++ 6.1 */ -#define VAX_VMS 0 /* VAX VMS */ - -#if IBM_ZTC || IBM_MSC || IBM_TBC || IBM_ICB || IBM_SC || IBM_MCW -#define IBM 1 +#ifndef UNIX_V +#define UNIX_V 0 /* UNIX System V, 4.2bsd, or HP Unix, presumably with gcc */ +#endif + +#ifndef UNIX_7 +#define UNIX_7 0 /* UNIX System III Version 7 or Sun Unix, presumably with gcc */ +#endif + +#ifndef LINUX +#define LINUX 0 /* Untested, presumably with gcc */ +#endif + +#ifndef DARWIN +#define DARWIN 0 /* Darwin Mac OS 10.10.2, presumably with gcc or Xcode 6.2 with Console */ +#endif + +#ifndef MAC_XCD +#define MAC_XCD 0 /* MacOS 10.10.2, with Xcode 6.2 and Cocoa GUI */ +#endif + +#ifndef WIN_MVC +#define WIN_MVC 0 /* Windows 7, with Visual Studio 2013 */ +#endif + +/* The following are unsupported: */ + +#ifndef WIN_GCC +#define WIN_GCC 0 /* Windows XP, with DJGPP 3.21 */ +#endif + +#ifndef VAX_VMS +#define VAX_VMS 0 /* VAX VMS */ +#endif + +/* Use GENERIC if nothing else is used. */ + +#ifndef GENERIC +#if (! UNIX_V) && (! LINUX) && (! UNIX_7) && \ + (! MAC_XCD) && (! DARWIN) && \ + (! WIN_MVC) && (! WIN_GCC) && \ + (! VAX_VMS) +#define GENERIC 1 /* Generic (any machine) */ #else -#define IBM 0 +#define GENERIC 0 /* Generic (any machine) */ +#endif #endif -#if MAC_MCW || MAC_XCD -#define MAC 1 +#if WIN_MVC +#define IBM 1 #else -#define MAC 0 +#define IBM 0 #endif /***********************************************/ /* Some definitions for use with declarations. */ /***********************************************/ -#define VOID void #define VOID_ARG void #define STD_SIZE size_t @@ -99,21 +167,27 @@ /* construct is included. */ /*************************************************/ +#ifndef DEFRULE_CONSTRUCT #define DEFRULE_CONSTRUCT 1 +#endif /************************************************/ /* DEFMODULE_CONSTRUCT: Determines whether the */ /* defmodule construct is included. */ /************************************************/ +#ifndef DEFMODULE_CONSTRUCT #define DEFMODULE_CONSTRUCT 1 +#endif /****************************************************/ /* DEFTEMPLATE_CONSTRUCT: Determines whether facts */ /* and the deftemplate construct are included. */ /****************************************************/ +#ifndef DEFTEMPLATE_CONSTRUCT #define DEFTEMPLATE_CONSTRUCT 1 +#endif #if ! DEFRULE_CONSTRUCT #undef DEFTEMPLATE_CONSTRUCT @@ -125,7 +199,9 @@ /* such as any-factp and do-for-all-facts are included. */ /************************************************************/ +#ifndef FACT_SET_QUERIES #define FACT_SET_QUERIES 1 +#endif #if ! DEFTEMPLATE_CONSTRUCT #undef FACT_SET_QUERIES @@ -137,7 +213,9 @@ /* construct is included. */ /****************************************************/ +#ifndef DEFFACTS_CONSTRUCT #define DEFFACTS_CONSTRUCT 1 +#endif #if ! DEFTEMPLATE_CONSTRUCT #undef DEFFACTS_CONSTRUCT @@ -149,21 +227,27 @@ /* defglobal construct is included. */ /************************************************/ +#ifndef DEFGLOBAL_CONSTRUCT #define DEFGLOBAL_CONSTRUCT 1 +#endif /**********************************************/ /* DEFFUNCTION_CONSTRUCT: Determines whether */ /* deffunction construct is included. */ /**********************************************/ +#ifndef DEFFUNCTION_CONSTRUCT #define DEFFUNCTION_CONSTRUCT 1 +#endif /*********************************************/ /* DEFGENERIC_CONSTRUCT: Determines whether */ /* generic functions are included. */ /*********************************************/ +#ifndef DEFGENERIC_CONSTRUCT #define DEFGENERIC_CONSTRUCT 1 +#endif /*****************************************************************/ /* OBJECT_SYSTEM: Determines whether object system is included. */ @@ -171,14 +255,18 @@ /* to be able to manipulate multi-field slots. */ /*****************************************************************/ +#ifndef OBJECT_SYSTEM #define OBJECT_SYSTEM 1 +#endif /*****************************************************************/ /* DEFINSTANCES_CONSTRUCT: Determines whether the definstances */ /* construct is enabled. */ /*****************************************************************/ +#ifndef DEFINSTANCES_CONSTRUCT #define DEFINSTANCES_CONSTRUCT 1 +#endif #if ! OBJECT_SYSTEM #undef DEFINSTANCES_CONSTRUCT @@ -190,7 +278,9 @@ /* such as any-instancep and do-for-all-instances are included. */ /********************************************************************/ +#ifndef INSTANCE_SET_QUERIES #define INSTANCE_SET_QUERIES 1 +#endif #if ! OBJECT_SYSTEM #undef INSTANCE_SET_QUERIES @@ -212,8 +302,12 @@ /* binary files */ /*******************************************************************/ +#ifndef BLOAD_INSTANCES #define BLOAD_INSTANCES 1 +#endif +#ifndef BSAVE_INSTANCES #define BSAVE_INSTANCES 1 +#endif #if ! OBJECT_SYSTEM #undef BLOAD_INSTANCES @@ -231,24 +325,17 @@ /* machines. */ /****************************************************************/ -#define EX_MATH 1 +#ifndef EXTENDED_MATH_FUNCTIONS +#define EXTENDED_MATH_FUNCTIONS 1 +#endif /****************************************************************/ /* TEXT PROCESSING : Turn on this flag for support of the */ /* hierarchical lookup system. */ /****************************************************************/ +#ifndef TEXTPRO_FUNCTIONS #define TEXTPRO_FUNCTIONS 1 - -/****************************************************************/ -/* HELP: To implement the help facility, set the flag below and */ -/* specify the path and name of the help data file your system. */ -/****************************************************************/ - -#define HELP_FUNCTIONS 1 - -#if HELP_FUNCTIONS -#define HELP_DEFAULT "clips.hlp" #endif /*************************************************************************/ @@ -257,9 +344,15 @@ /* BLOAD_AND_BSAVE: Enables bload, and bsave commands. */ /*************************************************************************/ +#ifndef BLOAD_ONLY #define BLOAD_ONLY 0 +#endif +#ifndef BLOAD #define BLOAD 0 +#endif +#ifndef BLOAD_AND_BSAVE #define BLOAD_AND_BSAVE 1 +#endif #if RUN_TIME #undef BLOAD_ONLY @@ -270,18 +363,6 @@ #define BLOAD_AND_BSAVE 0 #endif -/****************************************************************/ -/* EMACS_EDITOR: If this flag is turned on, an integrated EMACS */ -/* style editor can be utilized on supported machines. */ -/****************************************************************/ - -#define EMACS_EDITOR 1 - -#if GENERIC || MAC -#undef EMACS_EDITOR /* Editor can't be used */ -#define EMACS_EDITOR 0 /* with Generic or Mac */ -#endif - /********************************************************************/ /* CONSTRUCT COMPILER: If this flag is turned on, you can generate */ /* C code representing the constructs in the current environment. */ @@ -289,24 +370,22 @@ /* linked to create a stand-alone run-time executable. */ /********************************************************************/ +#ifndef CONSTRUCT_COMPILER #define CONSTRUCT_COMPILER 1 +#endif #if CONSTRUCT_COMPILER #define API_HEADER "clips.h" #endif -/*******************************************/ -/* BASIC_IO: Includes printout, fprintout, */ -/* read, open, and close functions. */ -/*******************************************/ - -#define BASIC_IO 1 - -/***************************************************/ -/* EXT_IO: Includes format and readline functions. */ -/***************************************************/ +/************************************************/ +/* IO_FUNCTIONS: Includes printout, read, open, */ +/* close, format, and readline functions. */ +/************************************************/ -#define EXT_IO 1 +#ifndef IO_FUNCTIONS +#define IO_FUNCTIONS 1 +#endif /************************************************/ /* STRING_FUNCTIONS: Includes string functions: */ @@ -314,7 +393,9 @@ /* sub-string, str-index, and eval. */ /************************************************/ +#ifndef STRING_FUNCTIONS #define STRING_FUNCTIONS 1 +#endif /*********************************************/ /* MULTIFIELD_FUNCTIONS: Includes multifield */ @@ -322,63 +403,40 @@ /* mv-append, str-explode, str-implode. */ /*********************************************/ +#ifndef MULTIFIELD_FUNCTIONS #define MULTIFIELD_FUNCTIONS 1 +#endif /****************************************************/ /* DEBUGGING_FUNCTIONS: Includes functions such as */ /* rules, facts, matches, ppdefrule, etc. */ /****************************************************/ +#ifndef DEBUGGING_FUNCTIONS #define DEBUGGING_FUNCTIONS 1 +#endif /***************************************************/ /* PROFILING_FUNCTIONS: Enables code for profiling */ /* constructs and user functions. */ /***************************************************/ +#ifndef PROFILING_FUNCTIONS #define PROFILING_FUNCTIONS 1 - -/************************************************************************/ -/* BLOCK_MEMORY: Causes memory to be allocated in large blocks. */ -/* INITBUFFERSIZE and BLOCKSIZE should both be set to less than the */ -/* maximum size of a signed integer. On a 16-bit machine, they should */ -/* be less than 32768. */ -/************************************************************************/ - -#define BLOCK_MEMORY 0 - -#if BLOCK_MEMORY - -#define INITBLOCKSIZE 32000 -#define BLOCKSIZE 32000 - #endif -/*****************************************************************/ -/* WINDOW_INTERFACE : Set this flag if you are recompiling the */ -/* IBM-PC MS-DOS Window Interface or the Macintosh LSC Window */ -/* Interface. Currently, when enabled, this flag disables the */ -/* more processing used by the help system. */ -/* This flag also prevents any input or output being directly */ -/* sent to stdin or stdout. */ -/*****************************************************************/ +/*******************************************************************/ +/* WINDOW_INTERFACE : Set this flag if you are recompiling any of */ +/* the machine specific GUI interfaces. Currently, when enabled, */ +/* this flag disables the more processing used by the help */ +/* system. This flag also prevents any input or output being */ +/* directly sent to stdin or stdout. */ +/*******************************************************************/ #ifndef WINDOW_INTERFACE -#define WINDOW_INTERFACE 1 -#endif - -#if WINDOW_INTERFACE -#undef EMACS_EDITOR /* Editor can't be used with */ -#define EMACS_EDITOR 0 /* windowed interface */ +#define WINDOW_INTERFACE 0 #endif -/*********************************************************/ -/* ENVIRONMENT_API_ONLY: If enabled, only the enviroment */ -/* API may be used to interface with CLIPS. */ -/*********************************************************/ - -#define ENVIRONMENT_API_ONLY 0 - /*************************************************************/ /* ALLOW_ENVIRONMENT_GLOBALS: If enabled, tracks the current */ /* environment and allows environments to be referred to */ @@ -386,14 +444,8 @@ /* variables. */ /*************************************************************/ -#define ALLOW_ENVIRONMENT_GLOBALS 1 - -#if ! ALLOW_ENVIRONMENT_GLOBALS -#undef ENVIRONMENT_API_ONLY /* Environment API must be used */ -#define ENVIRONMENT_API_ONLY 1 /* if no environment globals */ - -#undef EMACS_EDITOR /* Editor can't be used without */ -#define EMACS_EDITOR 0 /* environment globals */ +#ifndef ALLOW_ENVIRONMENT_GLOBALS +#define ALLOW_ENVIRONMENT_GLOBALS 0 #endif /********************************************/ @@ -418,25 +470,6 @@ #include "envrnmnt.h" -/******************************/ -/* Compatibilty Redefinitions */ -/******************************/ - -#define PrintCLIPS(x,y) EnvPrintRouter(GetCurrentEnvironment(),x,y) -#define GetcCLIPS(x,y) EnvGetcRouter(GetCurrentEnvironment(),x) -#define UngetcCLIPS(x,y) EnvUngetcRouter(GetCurrentEnvironment(),x,y) -#define ExitCLIPS(x) EnvExitRouter(GetCurrentEnvironment(),x) -#define CLIPSSystemError(x,y) SystemError(x,y) -#define CLIPSFunctionCall(x,y,z) FunctionCall(x,y,z) -#define InitializeCLIPS() InitializeEnvironment() -#define WCLIPS WPROMPT -#define CLIPSTrueSymbol SymbolData(GetCurrentEnvironment())->TrueSymbol -#define CLIPSFalseSymbol SymbolData(GetCurrentEnvironment())->FalseSymbol -#define EnvCLIPSTrueSymbol(theEnv) SymbolData(theEnv)->TrueSymbol -#define EnvCLIPSFalseSymbol(theEnv) SymbolData(theEnv)->FalseSymbol -#define CLIPS_FALSE 0 -#define CLIPS_TRUE 1 - /*************************************************/ /* Any user defined global setup information can */ /* be included in the file usrsetup.h which is */ diff --git a/src/sortfun.c b/src/sortfun.c index 0f722af..cd59a6d 100644 --- a/src/sortfun.c +++ b/src/sortfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* SORT FUNCTIONS MODULE */ /*******************************************************/ @@ -15,12 +15,16 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: The sort function leaks memory when called */ /* with a multifield value of length zero. */ /* DR0864 */ /* */ +/* 6.30: Added environment cleanup call function */ +/* DeallocateSortFunctionData. */ +/* */ /*************************************************************/ #define _SORTFUN_SOURCE_ @@ -41,7 +45,7 @@ #define SORTFUN_DATA 7 struct sortFunctionData - { + { struct expr *SortComparisonFunction; }; @@ -55,6 +59,7 @@ struct sortFunctionData unsigned long,unsigned long,unsigned long, int (*)(void *,DATA_OBJECT *,DATA_OBJECT *)); static int DefaultCompareSwapFunction(void *,DATA_OBJECT *,DATA_OBJECT *); + static void DeallocateSortFunctionData(void *); /****************************************/ /* SortFunctionDefinitions: Initializes */ @@ -63,12 +68,22 @@ struct sortFunctionData globle void SortFunctionDefinitions( void *theEnv) { - AllocateEnvironmentData(theEnv,SORTFUN_DATA,sizeof(struct sortFunctionData),NULL); + AllocateEnvironmentData(theEnv,SORTFUN_DATA,sizeof(struct sortFunctionData),DeallocateSortFunctionData); #if ! RUN_TIME EnvDefineFunction2(theEnv,"sort",'u', PTIEF SortFunction,"SortFunction","1**w"); #endif } +/*******************************************************/ +/* DeallocateSortFunctionData: Deallocates environment */ +/* data for the sort function. */ +/*******************************************************/ +static void DeallocateSortFunctionData( + void *theEnv) + { + ReturnExpression(theEnv,SortFunctionData(theEnv)->SortComparisonFunction); + } + /**************************************/ /* DefaultCompareSwapFunction: */ /**************************************/ @@ -106,7 +121,7 @@ globle void SortFunction( DATA_OBJECT *theArguments, *theArguments2; DATA_OBJECT theArg; struct multifield *theMultifield, *tempMultifield; - char *functionName; + const char *functionName; struct expr *functionReference; int argumentSize = 0; struct FunctionDefinition *fptr; @@ -147,7 +162,7 @@ globle void SortFunction( /* For an external function, verify the */ /* correct number of arguments. */ /*======================================*/ - + if (functionReference->type == FCALL) { fptr = (struct FunctionDefinition *) functionReference->value; @@ -160,12 +175,12 @@ globle void SortFunction( return; } } - + /*=======================================*/ /* For a deffunction, verify the correct */ /* number of arguments. */ /*=======================================*/ - + #if DEFFUNCTION_CONSTRUCT if (functionReference->type == PCALL) { @@ -192,7 +207,7 @@ globle void SortFunction( ReturnExpression(theEnv,functionReference); return; } - + /*=====================================*/ /* Retrieve the arguments to be sorted */ /* and determine how many there are. */ @@ -208,20 +223,20 @@ globle void SortFunction( else { argumentSize++; } } - + if (argumentSize == 0) - { + { genfree(theEnv,theArguments,(argumentCount - 1) * sizeof(DATA_OBJECT)); /* Bug Fix */ EnvSetMultifieldErrorValue(theEnv,returnValue); ReturnExpression(theEnv,functionReference); return; } - + /*====================================*/ /* Pack all of the items to be sorted */ /* into a data object array. */ /*====================================*/ - + theArguments2 = (DATA_OBJECT *) genalloc(theEnv,argumentSize * sizeof(DATA_OBJECT)); for (i = 2; i <= argumentCount; i++) @@ -242,7 +257,7 @@ globle void SortFunction( k++; } } - + genfree(theEnv,theArguments,(argumentCount - 1) * sizeof(DATA_OBJECT)); functionReference->nextArg = SortFunctionData(theEnv)->SortComparisonFunction; @@ -252,7 +267,7 @@ globle void SortFunction( { ValueInstall(theEnv,&theArguments2[i]); } MergeSort(theEnv,(unsigned long) argumentSize,theArguments2,DefaultCompareSwapFunction); - + for (i = 0; i < argumentSize; i++) { ValueDeinstall(theEnv,&theArguments2[i]); } @@ -267,7 +282,7 @@ globle void SortFunction( SetMFType(theMultifield,i+1,GetType(theArguments2[i])); SetMFValue(theMultifield,i+1,GetValue(theArguments2[i])); } - + genfree(theEnv,theArguments2,argumentSize * sizeof(DATA_OBJECT)); SetpType(returnValue,MULTIFIELD); diff --git a/src/sortfun.h b/src/sortfun.h index dc07345..89e9093 100644 --- a/src/sortfun.h +++ b/src/sortfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SORT FUNCTIONS HEADER MODULE */ /*******************************************************/ @@ -16,6 +16,15 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.24: The sort function leaks memory when called */ +/* with a multifield value of length zero. */ +/* DR0864 */ +/* */ +/* 6.30: Added environment cleanup call function */ +/* DeallocateSortFunctionData. */ +/* */ /*************************************************************/ #ifndef _H_sortfun @@ -37,7 +46,7 @@ int (*)(void *,DATA_OBJECT *,DATA_OBJECT *)); LOCALE void SortFunction(void *,DATA_OBJECT *); -#endif +#endif /* _H_sortfun */ diff --git a/src/strngfun.c b/src/strngfun.c index 4bcf7a6..112650a 100644 --- a/src/strngfun.c +++ b/src/strngfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* STRING FUNCTIONS MODULE */ /*******************************************************/ @@ -19,8 +19,34 @@ /* Barry Cameron */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added support for UTF-8 strings to str-length, */ +/* str-index, and sub-string functions. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added code to keep track of pointers to */ +/* constructs that are contained externally to */ +/* to constructs, DanglingConstructs. */ +/* */ +/* Fixed str-cat bug that could be invoked by */ +/* (funcall str-cat). */ +/* */ /*************************************************************/ #define _STRNGFUN_SOURCE_ @@ -35,6 +61,7 @@ #include <string.h> #include "argacces.h" +#include "commline.h" #include "constrct.h" #include "cstrcpsr.h" #include "engine.h" @@ -46,6 +73,7 @@ #include "router.h" #include "strngrtr.h" #include "scanner.h" +#include "sysdep.h" #if DEFRULE_CONSTRUCT #include "drive.h" @@ -69,8 +97,8 @@ globle void StringFunctionDefinitions( #if ! RUN_TIME EnvDefineFunction2(theEnv,"str-cat", 'k', PTIEF StrCatFunction, "StrCatFunction", "1*"); EnvDefineFunction2(theEnv,"sym-cat", 'k', PTIEF SymCatFunction, "SymCatFunction", "1*"); - EnvDefineFunction2(theEnv,"str-length", 'l', PTIEF StrLengthFunction, "StrLengthFunction", "11j"); - EnvDefineFunction2(theEnv,"str-compare", 'l', PTIEF StrCompareFunction, "StrCompareFunction", "23*jji"); + EnvDefineFunction2(theEnv,"str-length", 'g', PTIEF StrLengthFunction, "StrLengthFunction", "11j"); + EnvDefineFunction2(theEnv,"str-compare", 'g', PTIEF StrCompareFunction, "StrCompareFunction", "23*jji"); EnvDefineFunction2(theEnv,"upcase", 'j', PTIEF UpcaseFunction, "UpcaseFunction", "11j"); EnvDefineFunction2(theEnv,"lowcase", 'j', PTIEF LowcaseFunction, "LowcaseFunction", "11j"); EnvDefineFunction2(theEnv,"sub-string", 's', PTIEF SubStringFunction, "SubStringFunction", "33*iij"); @@ -79,7 +107,7 @@ globle void StringFunctionDefinitions( EnvDefineFunction2(theEnv,"build", 'b', PTIEF BuildFunction, "BuildFunction", "11k"); EnvDefineFunction2(theEnv,"string-to-field", 'u', PTIEF StringToFieldFunction, "StringToFieldFunction", "11j"); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -92,7 +120,7 @@ globle void StringFunctionDefinitions( globle void StrCatFunction( void *theEnv, DATA_OBJECT_PTR returnValue) - { + { StrOrSymCatFunction(theEnv,returnValue,STRING); } @@ -121,7 +149,7 @@ static void StrOrSymCatFunction( char *theString; SYMBOL_HN **arrayOfStrings; SYMBOL_HN *hashPtr; - char *functionName; + const char *functionName; /*============================================*/ /* Determine the calling function name. */ @@ -148,8 +176,10 @@ static void StrOrSymCatFunction( /*===============================================*/ numArgs = EnvRtnArgCount(theEnv); + if (numArgs == 0) return; + arrayOfStrings = (SYMBOL_HN **) gm1(theEnv,(int) sizeof(SYMBOL_HN *) * numArgs); - for (i = 0; i < numArgs; i++) + for (i = 0; i < numArgs; i++) { arrayOfStrings[i] = NULL; } /*=============================================*/ @@ -171,7 +201,7 @@ static void StrOrSymCatFunction( case SYMBOL: hashPtr = (SYMBOL_HN *) GetValue(theArg); arrayOfStrings[i-1] = hashPtr; - IncrementSymbolCount(hashPtr); + IncrementSymbolCount(hashPtr); break; case FLOAT: @@ -218,7 +248,7 @@ static void StrOrSymCatFunction( j = 0; for (i = 0 ; i < numArgs ; i++) { - sprintf(&theString[j],"%s",ValueToString(arrayOfStrings[i])); + gensprintf(&theString[j],"%s",ValueToString(arrayOfStrings[i])); j += (int) strlen(ValueToString(arrayOfStrings[i])); } @@ -243,7 +273,7 @@ static void StrOrSymCatFunction( /* StrLengthFunction: H/L access routine */ /* for the str-length function. */ /*******************************************/ -globle long int StrLengthFunction( +globle long long StrLengthFunction( void *theEnv) { DATA_OBJECT theArg; @@ -253,20 +283,20 @@ globle long int StrLengthFunction( /*===================================================*/ if (EnvArgCountCheck(theEnv,"str-length",EXACTLY,1) == -1) - { return(-1L); } + { return(-1LL); } /*==================================================*/ /* The argument should be of type symbol or string. */ /*==================================================*/ if (EnvArgTypeCheck(theEnv,"str-length",1,SYMBOL_OR_STRING,&theArg) == FALSE) - { return(-1L); } + { return(-1LL); } /*============================================*/ /* Return the length of the string or symbol. */ /*============================================*/ - return( (long) strlen(DOToString(theArg))); + return(UTF8Length(DOToString(theArg))); } /****************************************/ @@ -280,7 +310,8 @@ globle void UpcaseFunction( DATA_OBJECT theArg; unsigned i; size_t slen; - char *osptr, *nsptr; + const char *osptr; + char *nsptr; /*===============================================*/ /* Function upcase expects exactly one argument. */ @@ -343,7 +374,8 @@ globle void LowcaseFunction( DATA_OBJECT theArg; unsigned i; size_t slen; - char *osptr, *nsptr; + const char *osptr; + char *nsptr; /*================================================*/ /* Function lowcase expects exactly one argument. */ @@ -399,12 +431,12 @@ globle void LowcaseFunction( /* StrCompareFunction: H/L access routine */ /* for the str-compare function. */ /********************************************/ -globle long int StrCompareFunction( +globle long long StrCompareFunction( void *theEnv) { int numArgs, length; DATA_OBJECT arg1, arg2, arg3; - long returnValue; + long long returnValue; /*=======================================================*/ /* Function str-compare expects either 2 or 3 arguments. */ @@ -459,8 +491,9 @@ globle void *SubStringFunction( void *theEnv) { DATA_OBJECT theArgument; - char *tempString, *returnString; - int start, end, i, j; + const char *tempString; + char *returnString; + size_t start, end, i, j, length; void *returnValue; /*===================================*/ @@ -473,30 +506,39 @@ globle void *SubStringFunction( if (EnvArgTypeCheck(theEnv,"sub-string",1,INTEGER,&theArgument) == FALSE) { return((void *) EnvAddSymbol(theEnv,"")); } - start = CoerceToInteger(theArgument.type,theArgument.value) - 1; + if (CoerceToLongInteger(theArgument.type,theArgument.value) < 1) + { start = 0; } + else + { start = (size_t) CoerceToLongInteger(theArgument.type,theArgument.value) - 1; } if (EnvArgTypeCheck(theEnv,"sub-string",2,INTEGER,&theArgument) == FALSE) { return((void *) EnvAddSymbol(theEnv,"")); } - end = CoerceToInteger(theArgument.type,theArgument.value) - 1; + if (CoerceToLongInteger(theArgument.type,theArgument.value) < 1) + { return((void *) EnvAddSymbol(theEnv,"")); } + else + { end = (size_t) CoerceToLongInteger(theArgument.type,theArgument.value) - 1; } if (EnvArgTypeCheck(theEnv,"sub-string",3,SYMBOL_OR_STRING,&theArgument) == FALSE) { return((void *) EnvAddSymbol(theEnv,"")); } + tempString = DOToString(theArgument); + /*================================================*/ /* If parameters are out of range return an error */ /*================================================*/ - if (start < 0) start = 0; - if (end > (int) strlen(DOToString(theArgument))) - { end = (int) strlen(DOToString(theArgument)); } + length = UTF8Length(tempString); + + if (end > length) + { end = length; } /*==================================*/ /* If the start is greater than the */ /* end, return a null string. */ /*==================================*/ - if (start > end) + if ((start > end) || (length == 0)) { return((void *) EnvAddSymbol(theEnv,"")); } /*=============================================*/ @@ -507,8 +549,10 @@ globle void *SubStringFunction( else { + start = UTF8Offset(tempString,start); + end = UTF8Offset(tempString,end + 1) - 1; + returnString = (char *) gm2(theEnv,(unsigned) (end - start + 2)); /* (end - start) inclusive + EOS */ - tempString = DOToString(theArgument); for(j=0, i=start;i <= end; i++, j++) { *(returnString+j) = *(tempString+i); } *(returnString+j) = '\0'; @@ -532,8 +576,8 @@ globle void StrIndexFunction( DATA_OBJECT_PTR result) { DATA_OBJECT theArgument1, theArgument2; - char *strg1, *strg2; - int i, j; + const char *strg1, *strg2, *strg3; + size_t i, j; result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); @@ -559,10 +603,11 @@ globle void StrIndexFunction( if (strlen(strg1) == 0) { result->type = INTEGER; - result->value = (void *) EnvAddLong(theEnv,(long) strlen(strg2) + 1L); + result->value = (void *) EnvAddLong(theEnv,(long long) UTF8Length(strg2) + 1LL); return; } + strg3 = strg2; for (i=1; *strg2; i++, strg2++) { for (j=0; *(strg1+j) && *(strg1+j) == *(strg2+j); j++) @@ -571,7 +616,7 @@ globle void StrIndexFunction( if (*(strg1+j) == '\0') { result->type = INTEGER; - result->value = (void *) EnvAddLong(theEnv,(long) i); + result->value = (void *) EnvAddLong(theEnv,(long long) UTF8CharNum(strg3,i)); return; } } @@ -623,7 +668,7 @@ globle void StringToFieldFunction( /*************************************************************/ globle void StringToField( void *theEnv, - char *theString, + const char *theString, DATA_OBJECT *returnValue) { struct token theToken; @@ -664,7 +709,7 @@ globle void StringToField( returnValue->value = (void *) EnvAddSymbol(theEnv,theToken.printForm); } } - + #if (! RUN_TIME) && (! BLOAD_ONLY) /**************************************/ @@ -706,13 +751,26 @@ globle void EvalFunction( EnvEval(theEnv,DOToString(theArg),returnValue); } +/****************************/ +/* Eval: C access routine */ +/* for the eval function. */ +/****************************/ +#if ALLOW_ENVIRONMENT_GLOBALS +globle int Eval( + const char *theString, + DATA_OBJECT_PTR returnValue) + { + return EnvEval(GetCurrentEnvironment(),theString,returnValue); + } +#endif + /*****************************/ /* EnvEval: C access routine */ /* for the eval function. */ /*****************************/ globle int EnvEval( void *theEnv, - char *theString, + const char *theString, DATA_OBJECT_PTR returnValue) { struct expr *top; @@ -720,6 +778,7 @@ globle int EnvEval( static int depth = 0; char logicalNameBuffer[20]; struct BindInfo *oldBinds; + int danglingConstructs; /*======================================================*/ /* Evaluate the string. Create a different logical name */ @@ -727,7 +786,7 @@ globle int EnvEval( /*======================================================*/ depth++; - sprintf(logicalNameBuffer,"Eval-%d",depth); + gensprintf(logicalNameBuffer,"Eval-%d",depth); if (OpenStringSource(theEnv,logicalNameBuffer,theString,0) == 0) { SetpType(returnValue,SYMBOL); @@ -745,6 +804,7 @@ globle int EnvEval( SetPPBufferStatus(theEnv,FALSE); oldBinds = GetParsedBindNames(theEnv); SetParsedBindNames(theEnv,NULL); + danglingConstructs = ConstructData(theEnv)->DanglingConstructs; /*========================================================*/ /* Parse the string argument passed to the eval function. */ @@ -771,6 +831,7 @@ globle int EnvEval( SetpType(returnValue,SYMBOL); SetpValue(returnValue,EnvFalseSymbol(theEnv)); depth--; + ConstructData(theEnv)->DanglingConstructs = danglingConstructs; return(FALSE); } @@ -789,6 +850,7 @@ globle int EnvEval( SetpValue(returnValue,EnvFalseSymbol(theEnv)); ReturnExpression(theEnv,top); depth--; + ConstructData(theEnv)->DanglingConstructs = danglingConstructs; return(FALSE); } @@ -807,6 +869,7 @@ globle int EnvEval( SetpValue(returnValue,EnvFalseSymbol(theEnv)); ReturnExpression(theEnv,top); depth--; + ConstructData(theEnv)->DanglingConstructs = danglingConstructs; return(FALSE); } @@ -823,6 +886,26 @@ globle int EnvEval( ReturnExpression(theEnv,top); CloseStringSource(theEnv,logicalNameBuffer); + /*==============================================*/ + /* If embedded, reset dangling construct count. */ + /*==============================================*/ + + if ((! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL)) + { ConstructData(theEnv)->DanglingConstructs = danglingConstructs; } + + /*==========================================*/ + /* Perform periodic cleanup if the eval was */ + /* issued from an embedded controller. */ + /*==========================================*/ + + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,returnValue); + CallPeriodicTasks(theEnv); + } + if (GetEvaluationError(theEnv)) return(FALSE); return(TRUE); } @@ -849,13 +932,9 @@ globle void EvalFunction( /*****************************************************/ globle int EnvEval( void *theEnv, - char *theString, + const char *theString, DATA_OBJECT_PTR returnValue) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theString) -#endif - PrintErrorID(theEnv,"STRNGFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Function eval does not work in run time modules.\n"); SetpType(returnValue,SYMBOL); @@ -895,15 +974,27 @@ globle int BuildFunction( return(EnvBuild(theEnv,DOToString(theArg))); } +/*****************************/ +/* Build: C access routine */ +/* for the build function. */ +/*****************************/ +#if ALLOW_ENVIRONMENT_GLOBALS +globle int Build( + const char *theString) + { + return EnvBuild(GetCurrentEnvironment(),theString); + } +#endif + /******************************/ /* EnvBuild: C access routine */ /* for the build function. */ /******************************/ globle int EnvBuild( void *theEnv, - char *theString) + const char *theString) { - char *constructType; + const char *constructType; struct token theToken; int errorFlag; @@ -952,7 +1043,7 @@ globle int EnvBuild( /*======================*/ /* Parse the construct. */ /*======================*/ - + errorFlag = ParseConstruct(theEnv,constructType,"build"); /*=================================*/ @@ -975,6 +1066,18 @@ globle int EnvBuild( DestroyPPBuffer(theEnv); + /*===========================================*/ + /* Perform periodic cleanup if the build was */ + /* issued from an embedded controller. */ + /*===========================================*/ + + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } + /*===============================================*/ /* Return TRUE if the construct was successfully */ /* parsed, otherwise return FALSE. */ @@ -1003,12 +1106,8 @@ globle int BuildFunction( /******************************************************/ globle int EnvBuild( void *theEnv, - char *theString) - { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theString) -#endif - + const char *theString) + { PrintErrorID(theEnv,"STRNGFUN",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Function build does not work in run time modules.\n"); return(FALSE); diff --git a/src/strngfun.h b/src/strngfun.h index 958a04f..c3b63db 100644 --- a/src/strngfun.h +++ b/src/strngfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* STRING FUNCTIONS HEADER FILE */ /*******************************************************/ @@ -16,6 +16,26 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added support for UTF-8 strings to str-length, */ +/* str-index, and sub-string functions. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_strngfun @@ -36,31 +56,28 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define Eval(theEnv,a,b) EnvEval(theEnv,a,b) -#define Build(theEnv,a) EnvBuild(theEnv,a) -#else -#define Eval(a,b) EnvEval(GetCurrentEnvironment(),a,b) -#define Build(a) EnvBuild(GetCurrentEnvironment(),a) +#if ALLOW_ENVIRONMENT_GLOBALS + LOCALE int Build(const char *); + LOCALE int Eval(const char *,DATA_OBJECT_PTR); #endif + LOCALE int EnvBuild(void *,const char *); + LOCALE int EnvEval(void *,const char *,DATA_OBJECT_PTR); LOCALE void StringFunctionDefinitions(void *); LOCALE void StrCatFunction(void *,DATA_OBJECT_PTR); LOCALE void SymCatFunction(void *,DATA_OBJECT_PTR); - LOCALE long int StrLengthFunction(void *); + LOCALE long long StrLengthFunction(void *); LOCALE void UpcaseFunction(void *,DATA_OBJECT_PTR); LOCALE void LowcaseFunction(void *,DATA_OBJECT_PTR); - LOCALE long int StrCompareFunction(void *); + LOCALE long long StrCompareFunction(void *); LOCALE void *SubStringFunction(void *); LOCALE void StrIndexFunction(void *,DATA_OBJECT_PTR); LOCALE void EvalFunction(void *,DATA_OBJECT_PTR); - LOCALE int EnvEval(void *,char *,DATA_OBJECT_PTR); LOCALE int BuildFunction(void *); - LOCALE int EnvBuild(void *,char *); LOCALE void StringToFieldFunction(void *,DATA_OBJECT *); - LOCALE void StringToField(void *,char *,DATA_OBJECT *); + LOCALE void StringToField(void *,const char *,DATA_OBJECT *); -#endif +#endif /* _H_strngfun */ diff --git a/src/strngrtr.c b/src/strngrtr.c index 70784ca..69c82db 100644 --- a/src/strngrtr.c +++ b/src/strngrtr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.22 06/15/04 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* STRING I/O ROUTER MODULE */ /*******************************************************/ @@ -14,10 +14,21 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.30: Used genstrcpy instead of strcpy. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _STRNGRTR_SOURCE_ @@ -33,6 +44,7 @@ #include "envrnmnt.h" #include "memalloc.h" #include "router.h" +#include "sysdep.h" #include "strngrtr.h" @@ -43,12 +55,12 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int FindString(void *,char *); - static int PrintString(void *,char *,char *); - static int GetcString(void *,char *); - static int UngetcString(void *,int,char *); - static struct stringRouter *FindStringRouter(void *,char *); - static int CreateReadStringSource(void *,char *,char *,int,unsigned); + static int FindString(void *,const char *); + static int PrintString(void *,const char *,const char *); + static int GetcString(void *,const char *); + static int UngetcString(void *,int,const char *); + static struct stringRouter *FindStringRouter(void *,const char *); + static int CreateReadStringSource(void *,const char *,const char *,size_t,size_t); static void DeallocateStringRouterData(void *); /**********************************************************/ @@ -61,7 +73,7 @@ globle void InitializeStringRouter( EnvAddRouter(theEnv,"string",0,FindString,PrintString,GetcString,UngetcString,NULL); } - + /*******************************************/ /* DeallocateStringRouterData: Deallocates */ /* environment data for string routers. */ @@ -70,12 +82,12 @@ static void DeallocateStringRouterData( void *theEnv) { struct stringRouter *tmpPtr, *nextPtr; - + tmpPtr = StringRouterData(theEnv)->ListOfStringRouters; while (tmpPtr != NULL) { nextPtr = tmpPtr->next; - rm(theEnv,tmpPtr->name,strlen(tmpPtr->name) + 1); + rm(theEnv,(void *) tmpPtr->name,strlen(tmpPtr->name) + 1); rtn_struct(theEnv,stringRouter,tmpPtr); tmpPtr = nextPtr; } @@ -86,7 +98,7 @@ static void DeallocateStringRouterData( /*************************************************************/ static int FindString( void *theEnv, - char *fileid) + const char *fileid) { struct stringRouter *head; @@ -106,8 +118,8 @@ static int FindString( /**************************************************/ static int PrintString( void *theEnv, - char *logicalName, - char *str) + const char *logicalName, + const char *str) { struct stringRouter *head; @@ -119,12 +131,16 @@ static int PrintString( } if (head->readWriteType != WRITE_STRING) return(1); - if (head->currentPosition >= (int) (head->maximumPosition - 1)) return(1); - strncpy(&head->str[head->currentPosition], - str,(STD_SIZE) (head->maximumPosition - head->currentPosition) - 1); + if (head->maximumPosition == 0) return(1); + + if ((head->currentPosition + 1) >= head->maximumPosition) return(1); + + genstrncpy(&head->writeString[head->currentPosition], + str,(STD_SIZE) (head->maximumPosition - head->currentPosition) - 1); + + head->currentPosition += strlen(str); - head->currentPosition += (int) strlen(str); return(1); } @@ -133,7 +149,7 @@ static int PrintString( /************************************************/ static int GetcString( void *theEnv, - char *logicalName) + const char *logicalName) { struct stringRouter *head; int rc; @@ -146,13 +162,13 @@ static int GetcString( } if (head->readWriteType != READ_STRING) return(EOF); - if (head->currentPosition >= (int) head->maximumPosition) + if (head->currentPosition >= head->maximumPosition) { head->currentPosition++; return(EOF); } - rc = (unsigned char) head->str[head->currentPosition]; + rc = (unsigned char) head->readString[head->currentPosition]; head->currentPosition++; return(rc); @@ -161,16 +177,13 @@ static int GetcString( /****************************************************/ /* UngetcString: Ungetc routine for string routers. */ /****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int UngetcString( void *theEnv, int ch, - char *logicalName) + const char *logicalName) { struct stringRouter *head; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(ch) #endif @@ -194,11 +207,11 @@ static int UngetcString( /************************************************/ globle int OpenStringSource( void *theEnv, - char *name, - char *str, - int currentPosition) + const char *name, + const char *str, + size_t currentPosition) { - unsigned maximumPosition; + size_t maximumPosition; if (str == NULL) { @@ -217,10 +230,10 @@ globle int OpenStringSource( /******************************************************/ globle int OpenTextSource( void *theEnv, - char *name, - char *str, - int currentPosition, - unsigned maximumPosition) + const char *name, + const char *str, + size_t currentPosition, + size_t maximumPosition) { if (str == NULL) { @@ -236,19 +249,22 @@ globle int OpenTextSource( /******************************************************************/ static int CreateReadStringSource( void *theEnv, - char *name, - char *str, - int currentPosition, - unsigned maximumPosition) + const char *name, + const char *str, + size_t currentPosition, + size_t maximumPosition) { struct stringRouter *newStringRouter; + char *theName; if (FindStringRouter(theEnv,name) != NULL) return(0); newStringRouter = get_struct(theEnv,stringRouter); - newStringRouter->name = (char *) gm1(theEnv,(int) strlen(name) + 1); - strcpy(newStringRouter->name,name); - newStringRouter->str = str; + theName = (char *) gm1(theEnv,strlen(name) + 1); + genstrcpy(theName,name); + newStringRouter->name = theName; + newStringRouter->writeString = NULL; + newStringRouter->readString = str; newStringRouter->currentPosition = currentPosition; newStringRouter->readWriteType = READ_STRING; newStringRouter->maximumPosition = maximumPosition; @@ -263,7 +279,7 @@ static int CreateReadStringSource( /**********************************************/ globle int CloseStringSource( void *theEnv, - char *name) + const char *name) { struct stringRouter *head, *last; @@ -276,14 +292,14 @@ globle int CloseStringSource( if (last == NULL) { StringRouterData(theEnv)->ListOfStringRouters = head->next; - rm(theEnv,head->name,strlen(head->name) + 1); + rm(theEnv,(void *) head->name,strlen(head->name) + 1); rtn_struct(theEnv,stringRouter,head); return(1); } else { last->next = head->next; - rm(theEnv,head->name,strlen(head->name) + 1); + rm(theEnv,(void *) head->name,strlen(head->name) + 1); rtn_struct(theEnv,stringRouter,head); return(1); } @@ -300,18 +316,21 @@ globle int CloseStringSource( /******************************************************************/ globle int OpenStringDestination( void *theEnv, - char *name, + const char *name, char *str, - unsigned maximumPosition) + size_t maximumPosition) { struct stringRouter *newStringRouter; + char *theName; if (FindStringRouter(theEnv,name) != NULL) return(0); newStringRouter = get_struct(theEnv,stringRouter); - newStringRouter->name = (char *) gm1(theEnv,(int) strlen(name) + 1); - strcpy(newStringRouter->name,name); - newStringRouter->str = str; + theName = (char *) gm1(theEnv,(int) strlen(name) + 1); + genstrcpy(theName,name); + newStringRouter->name = theName; + newStringRouter->readString = NULL; + newStringRouter->writeString = str; newStringRouter->currentPosition = 0; newStringRouter->readWriteType = WRITE_STRING; newStringRouter->maximumPosition = maximumPosition; @@ -326,7 +345,7 @@ globle int OpenStringDestination( /***************************************************/ globle int CloseStringDestination( void *theEnv, - char *name) + const char *name) { return(CloseStringSource(theEnv,name)); } @@ -336,7 +355,7 @@ globle int CloseStringDestination( /*******************************************************************/ static struct stringRouter *FindStringRouter( void *theEnv, - char *name) + const char *name) { struct stringRouter *head; diff --git a/src/strngrtr.h b/src/strngrtr.h index df5a230..43bc1b3 100644 --- a/src/strngrtr.h +++ b/src/strngrtr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* STRING I/O ROUTER HEADER FILE */ /*******************************************************/ @@ -17,6 +17,17 @@ /* */ /* Revision History: */ /* */ +/* 6.30: Used genstrcpy instead of strcpy. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_strngrtr @@ -31,16 +42,18 @@ struct stringRouter { - char *name; - char *str; - int currentPosition; - unsigned maximumPosition; + const char *name; + const char *readString; + char *writeString; + //char *str; + size_t currentPosition; + size_t maximumPosition; int readWriteType; struct stringRouter *next; }; struct stringRouterData - { + { struct stringRouter *ListOfStringRouters; }; @@ -61,12 +74,12 @@ struct stringRouterData /**************************/ LOCALE void InitializeStringRouter(void *); - LOCALE int OpenStringSource(void *,char *,char *,int); - LOCALE int OpenTextSource(void *,char *,char *,int,unsigned); - LOCALE int CloseStringSource(void *,char *); - LOCALE int OpenStringDestination(void *,char *,char *,unsigned); - LOCALE int CloseStringDestination(void *,char *); + LOCALE int OpenStringSource(void *,const char *,const char *,size_t); + LOCALE int OpenTextSource(void *,const char *,const char *,size_t,size_t); + LOCALE int CloseStringSource(void *,const char *); + LOCALE int OpenStringDestination(void *,const char *,char *,size_t); + LOCALE int CloseStringDestination(void *,const char *); -#endif +#endif /* _H_strngrtr */ diff --git a/src/symblbin.c b/src/symblbin.c index 57a2d8d..7083369 100644 --- a/src/symblbin.c +++ b/src/symblbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SYMBOL BSAVE MODULE */ /*******************************************************/ @@ -12,12 +12,16 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ /*************************************************************/ #define _BSAVE_SOURCE_ @@ -152,10 +156,11 @@ globle void WriteNeededSymbols( FILE *fp) { unsigned long i; - unsigned length; + size_t length; SYMBOL_HN **symbolArray; SYMBOL_HN *symbolPtr; - unsigned long int numberOfUsedSymbols = 0, size = 0; + unsigned long int numberOfUsedSymbols = 0; + size_t size = 0; /*=================================*/ /* Get a copy of the symbol table. */ @@ -319,7 +324,7 @@ static void WriteNeededBitMaps( BITMAP_HN **bitMapArray; BITMAP_HN *bitMapPtr; unsigned long int numberOfUsedBitMaps = 0, size = 0; - char tempSize; + unsigned short tempSize; /*=================================*/ /* Get a copy of the bitmap table. */ @@ -340,7 +345,7 @@ static void WriteNeededBitMaps( if (bitMapPtr->neededBitMap) { numberOfUsedBitMaps++; - size += (unsigned long) (bitMapPtr->size + 1); + size += (unsigned long) (bitMapPtr->size + sizeof(unsigned short)); } } } @@ -360,8 +365,8 @@ static void WriteNeededBitMaps( { if (bitMapPtr->neededBitMap) { - tempSize = (char) bitMapPtr->size; - GenWrite((void *) &tempSize,(unsigned long) sizeof(char),fp); + tempSize = (unsigned short) bitMapPtr->size; + GenWrite((void *) &tempSize,(unsigned long) sizeof(unsigned short),fp); GenWrite((void *) bitMapPtr->contents,(unsigned long) bitMapPtr->size,fp); } } @@ -486,7 +491,7 @@ globle void ReadNeededFloats( globle void ReadNeededIntegers( void *theEnv) { - long int *integerValues; + long long *integerValues; long i; /*==============================================*/ @@ -504,8 +509,8 @@ globle void ReadNeededIntegers( /* Allocate area for the integers. */ /*=================================*/ - integerValues = (long *) gm3(theEnv,(long) (sizeof(long) * SymbolData(theEnv)->NumberOfIntegers)); - GenReadBinary(theEnv,(void *) integerValues,(unsigned long) (sizeof(long) * SymbolData(theEnv)->NumberOfIntegers)); + integerValues = (long long *) gm3(theEnv,(long) (sizeof(long long) * SymbolData(theEnv)->NumberOfIntegers)); + GenReadBinary(theEnv,(void *) integerValues,(unsigned long) (sizeof(long long) * SymbolData(theEnv)->NumberOfIntegers)); /*==========================================*/ /* Store the integers in the integer array. */ @@ -520,7 +525,7 @@ globle void ReadNeededIntegers( /* Free the integer buffer. */ /*==========================*/ - rm3(theEnv,(void *) integerValues,(long) (sizeof(long int) * SymbolData(theEnv)->NumberOfIntegers)); + rm3(theEnv,(void *) integerValues,(long) (sizeof(long long) * SymbolData(theEnv)->NumberOfIntegers)); } /*******************************************/ @@ -533,6 +538,7 @@ static void ReadNeededBitMaps( char *bitMapStorage, *bitMapPtr; unsigned long space; long i; + unsigned short *tempSize; /*=======================================*/ /* Determine the number of bitmaps to be */ @@ -563,8 +569,9 @@ static void ReadNeededBitMaps( bitMapPtr = bitMapStorage; for (i = 0; i < SymbolData(theEnv)->NumberOfBitMaps; i++) { - SymbolData(theEnv)->BitMapArray[i] = (BITMAP_HN *) AddBitMap(theEnv,bitMapPtr+1,*bitMapPtr); - bitMapPtr += *bitMapPtr + 1; + tempSize = (unsigned short *) bitMapPtr; + SymbolData(theEnv)->BitMapArray[i] = (BITMAP_HN *) EnvAddBitMap(theEnv,bitMapPtr+sizeof(unsigned short),*tempSize); + bitMapPtr += *tempSize + sizeof(unsigned short); } /*=========================*/ @@ -590,7 +597,7 @@ globle void FreeAtomicValueStorage( rm3(theEnv,(void *) SymbolData(theEnv)->IntegerArray,(long) sizeof(INTEGER_HN *) * SymbolData(theEnv)->NumberOfIntegers); if (SymbolData(theEnv)->BitMapArray != NULL) rm3(theEnv,(void *) SymbolData(theEnv)->BitMapArray,(long) sizeof(BITMAP_HN *) * SymbolData(theEnv)->NumberOfBitMaps); - + SymbolData(theEnv)->SymbolArray = NULL; SymbolData(theEnv)->FloatArray = NULL; SymbolData(theEnv)->IntegerArray = NULL; diff --git a/src/symblbin.h b/src/symblbin.h index 2ed678c..b2ab031 100644 --- a/src/symblbin.h +++ b/src/symblbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SYMBOL BINARY SAVE HEADER FILE */ /*******************************************************/ @@ -12,12 +12,16 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for long long integers. */ +/* */ /*************************************************************/ #ifndef _H_symblbin @@ -59,7 +63,7 @@ LOCALE void ReadNeededFloats(void *); LOCALE void ReadNeededIntegers(void *); -#endif +#endif /* _H_symblbin */ diff --git a/src/symblcmp.c b/src/symblcmp.c index b5a4fd3..2622807 100644 --- a/src/symblcmp.c +++ b/src/symblcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SYMBOL CONSTRUCT COMPILER MODULE */ /*******************************************************/ @@ -16,7 +16,7 @@ /* Barry Cameron */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ @@ -24,6 +24,14 @@ /* */ /* Corrected code to remove compiler warnings. */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _SYMBLCMP_SOURCE_ @@ -56,13 +64,13 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int SymbolHashNodesToCode(void *,char *,int); - static int BitMapHashNodesToCode(void *,char *,int); - static int BitMapValuesToCode(void *,char *,int); - static int FloatHashNodesToCode(void *,char *,int); - static int IntegerHashNodesToCode(void *,char *,int); - static int HashTablesToCode(void *,char *); - static void PrintCString(FILE *,char *); + static int SymbolHashNodesToCode(void *,const char *,const char *,char *,int); + static int BitMapHashNodesToCode(void *,const char *,const char *,char *,int); + static int BitMapValuesToCode(void *,const char *,const char *, char *,int); + static int FloatHashNodesToCode(void *,const char *,const char *,char *,int); + static int IntegerHashNodesToCode(void *,const char *,const char *,char *,int); + static int HashTablesToCode(void *,const char *,const char *,char *); + static void PrintCString(FILE *,const char *); /**************************************************************/ /* AtomicValuesToCode: Driver routine for generating the code */ @@ -70,19 +78,21 @@ /**************************************************************/ globle void AtomicValuesToCode( void *theEnv, - char *fileName) + const char *fileName, + const char *pathName, + char *fileNameBuffer) { - int version; + int version; // TBD Necessary? SetAtomicValueIndices(theEnv,TRUE); - HashTablesToCode(theEnv,fileName); + HashTablesToCode(theEnv,fileName,pathName,fileNameBuffer); - version = SymbolHashNodesToCode(theEnv,fileName,5); - version = FloatHashNodesToCode(theEnv,fileName,version); - version = IntegerHashNodesToCode(theEnv,fileName,version); - version = BitMapHashNodesToCode(theEnv,fileName,version); - BitMapValuesToCode(theEnv,fileName,version); + version = SymbolHashNodesToCode(theEnv,fileName,pathName,fileNameBuffer,5); + version = FloatHashNodesToCode(theEnv,fileName,pathName,fileNameBuffer,version); + version = IntegerHashNodesToCode(theEnv,fileName,pathName,fileNameBuffer,version); + version = BitMapHashNodesToCode(theEnv,fileName,pathName,fileNameBuffer,version); + BitMapValuesToCode(theEnv,fileName,pathName,fileNameBuffer,version); } /*****************************************************/ @@ -92,7 +102,9 @@ globle void AtomicValuesToCode( /*****************************************************/ static int SymbolHashNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int version) { unsigned long i, j; @@ -128,7 +140,7 @@ static int SymbolHashNodesToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -158,7 +170,7 @@ static int SymbolHashNodesToCode( { fprintf(fp,"{&S%d_%d[%ld],",ConstructCompilerData(theEnv)->ImageID,arrayVersion,j + 1); } } - fprintf(fp,"%ld,0,1,0,0,%ld,",hashPtr->count + 1,i); + fprintf(fp,"%ld,1,0,0,%ld,",hashPtr->count + 1,i); PrintCString(fp,hashPtr->contents); count++; @@ -173,7 +185,7 @@ static int SymbolHashNodesToCode( version++; if (count < numberOfEntries) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -192,7 +204,9 @@ static int SymbolHashNodesToCode( /******************************************************/ static int BitMapHashNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int version) { int i, j; @@ -229,7 +243,7 @@ static int BitMapHashNodesToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -259,7 +273,7 @@ static int BitMapHashNodesToCode( { fprintf(fp,"{&B%d_%d[%d],",ConstructCompilerData(theEnv)->ImageID,arrayVersion,j + 1); } } - fprintf(fp,"%ld,0,1,0,0,%d,(char *) &L%d_%d[%d],%d", + fprintf(fp,"%ld,1,0,0,%d,(char *) &L%d_%d[%d],%d", hashPtr->count + 1,i, ConstructCompilerData(theEnv)->ImageID,longsReqdPartition,longsReqdPartitionCount, hashPtr->size); @@ -285,7 +299,7 @@ static int BitMapHashNodesToCode( version++; if (count < numberOfEntries) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -304,7 +318,9 @@ static int BitMapHashNodesToCode( /*****************************************************/ static int BitMapValuesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int version) { int i, j, k; @@ -347,7 +363,7 @@ static int BitMapValuesToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -378,7 +394,7 @@ static int BitMapValuesToCode( tmpLong = 0L; for (l = 0 ; ((l < sizeof(unsigned long)) && - (((k * sizeof(unsigned long)) + l) < hashPtr->size)) ; + (((k * sizeof(unsigned long)) + l) < (size_t) hashPtr->size)) ; l++) ((char *) &tmpLong)[l] = hashPtr->contents[(k * sizeof(unsigned long)) + l]; fprintf(fp,"0x%lxL",tmpLong); @@ -396,7 +412,7 @@ static int BitMapValuesToCode( version++; if (count < numberOfEntries) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -415,7 +431,9 @@ static int BitMapValuesToCode( /****************************************************/ static int FloatHashNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int version) { int i, j; @@ -451,7 +469,7 @@ static int FloatHashNodesToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -481,7 +499,7 @@ static int FloatHashNodesToCode( { fprintf(fp,"{&F%d_%d[%d],",ConstructCompilerData(theEnv)->ImageID,arrayVersion,j + 1); } } - fprintf(fp,"%ld,0,1,0,0,%d,",hashPtr->count + 1,i); + fprintf(fp,"%ld,1,0,0,%d,",hashPtr->count + 1,i); fprintf(fp,"%s",FloatToString(theEnv,hashPtr->contents)); count++; @@ -496,7 +514,7 @@ static int FloatHashNodesToCode( arrayVersion++; if (count < numberOfEntries) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -515,7 +533,9 @@ static int FloatHashNodesToCode( /******************************************************/ static int IntegerHashNodesToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int version) { int i, j; @@ -551,7 +571,7 @@ static int IntegerHashNodesToCode( /* Create the file. */ /*==================*/ - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(-1); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(-1); /*===================*/ /* List the entries. */ @@ -581,8 +601,8 @@ static int IntegerHashNodesToCode( { fprintf(fp,"{&I%d_%d[%d],",ConstructCompilerData(theEnv)->ImageID,arrayVersion,j + 1); } } - fprintf(fp,"%ld,0,1,0,0,%d,",hashPtr->count + 1,i); - fprintf(fp,"%ld",hashPtr->contents); + fprintf(fp,"%ld,1,0,0,%d,",hashPtr->count + 1,i); + fprintf(fp,"%lldLL",hashPtr->contents); count++; j++; @@ -596,7 +616,7 @@ static int IntegerHashNodesToCode( arrayVersion++; if (count < numberOfEntries) { - if ((fp = NewCFile(theEnv,fileName,1,version,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,version,FALSE)) == NULL) return(0); newHeader = TRUE; } } @@ -615,7 +635,9 @@ static int IntegerHashNodesToCode( /****************************************************************/ static int HashTablesToCode( void *theEnv, - char *fileName) + const char *fileName, + const char *pathName, + char *fileNameBuffer) { unsigned long i; FILE *fp; @@ -630,7 +652,7 @@ static int HashTablesToCode( symbolTable = GetSymbolTable(theEnv); - if ((fp = NewCFile(theEnv,fileName,1,1,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,1,FALSE)) == NULL) return(0); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"extern struct symbolHashNode *sht%d[];\n",ConstructCompilerData(theEnv)->ImageID); fprintf(fp,"struct symbolHashNode *sht%d[%ld] = {\n",ConstructCompilerData(theEnv)->ImageID,SYMBOL_HASH_SIZE); @@ -652,7 +674,7 @@ static int HashTablesToCode( floatTable = GetFloatTable(theEnv); - if ((fp = NewCFile(theEnv,fileName,1,2,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,2,FALSE)) == NULL) return(0); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"extern struct floatHashNode *fht%d[];\n",ConstructCompilerData(theEnv)->ImageID); fprintf(fp,"struct floatHashNode *fht%d[%d] = {\n",ConstructCompilerData(theEnv)->ImageID,FLOAT_HASH_SIZE); @@ -675,7 +697,7 @@ static int HashTablesToCode( integerTable = GetIntegerTable(theEnv); - if ((fp = NewCFile(theEnv,fileName,1,3,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,3,FALSE)) == NULL) return(0); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"extern struct integerHashNode *iht%d[];\n",ConstructCompilerData(theEnv)->ImageID); fprintf(fp,"struct integerHashNode *iht%d[%d] = {\n",ConstructCompilerData(theEnv)->ImageID,INTEGER_HASH_SIZE); @@ -698,7 +720,7 @@ static int HashTablesToCode( bitMapTable = GetBitMapTable(theEnv); - if ((fp = NewCFile(theEnv,fileName,1,4,FALSE)) == NULL) return(0); + if ((fp = NewCFile(theEnv,fileName,pathName,fileNameBuffer,1,4,FALSE)) == NULL) return(0); fprintf(ConstructCompilerData(theEnv)->HeaderFP,"extern struct bitMapHashNode *bmht%d[];\n",ConstructCompilerData(theEnv)->ImageID); fprintf(fp,"struct bitMapHashNode *bmht%d[%d] = {\n",ConstructCompilerData(theEnv)->ImageID,BITMAP_HASH_SIZE); @@ -787,7 +809,7 @@ globle void PrintBitMapReference( /*********************************************************/ static void PrintCString( FILE *theFile, - char *str) + const char *str) { unsigned i; size_t slen; diff --git a/src/symblcmp.h b/src/symblcmp.h index ed85b04..237e1f4 100644 --- a/src/symblcmp.h +++ b/src/symblcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* SYMBOL CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -13,12 +13,24 @@ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.24: Added environment parameter to GenClose. */ +/* */ +/* Corrected code to remove compiler warnings. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_symblcmp @@ -47,8 +59,8 @@ LOCALE void PrintFloatReference(void *,FILE *,FLOAT_HN *); LOCALE void PrintIntegerReference(void *,FILE *,INTEGER_HN *); LOCALE void PrintBitMapReference(void *,FILE *,BITMAP_HN *); - LOCALE void AtomicValuesToCode(void *,char *); + LOCALE void AtomicValuesToCode(void *,const char *,const char *,char *); -#endif +#endif /* _H_symblcmp */ diff --git a/src/symbol.c b/src/symbol.c index 0d79049..9b2ad58 100644 --- a/src/symbol.c +++ b/src/symbol.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/03/15 */ /* */ /* SYMBOL MODULE */ /*******************************************************/ @@ -17,9 +17,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: CLIPS crashing on AMD64 processor in the */ @@ -32,10 +33,33 @@ /* Corrected code generating compilation */ /* warnings. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for hashing EXTERNAL_ADDRESS data */ +/* type. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added support for external address hash table */ +/* and subtyping. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _SYMBOL_SOURCE_ - + #include <stdio.h> #define _STDIO_INCLUDED_ #include <stdlib.h> @@ -49,6 +73,8 @@ #include "router.h" #include "utility.h" #include "argacces.h" +#include "sysdep.h" + #include "symbol.h" /***************/ @@ -70,12 +96,12 @@ static void RemoveHashNode(void *,GENERIC_HN *,GENERIC_HN **,int,int); static void AddEphemeralHashNode(void *,GENERIC_HN *,struct ephemeron **, - int,int); + int,int,int); static void RemoveEphemeralHashNodes(void *,struct ephemeron **, GENERIC_HN **, int,int,int); - static char *StringWithinString(char *,char *); - static unsigned CommonPrefixLength(char *,char *); + static const char *StringWithinString(const char *,const char *); + static size_t CommonPrefixLength(const char *,const char *); static void DeallocateSymbolData(void *); /*******************************************************/ @@ -83,26 +109,23 @@ /* IntegerTable, and FloatTable. It also initializes */ /* the TrueSymbol and FalseSymbol. */ /*******************************************************/ -#if IBM_TBC && (! RUN_TIME) -#pragma argsused -#endif globle void InitializeAtomTables( void *theEnv, struct symbolHashNode **symbolTable, struct floatHashNode **floatTable, struct integerHashNode **integerTable, - struct bitMapHashNode **bitmapTable) + struct bitMapHashNode **bitmapTable, + struct externalAddressHashNode **externalAddressTable) { -#if ! RUN_TIME -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(symbolTable) #pragma unused(floatTable) #pragma unused(integerTable) #pragma unused(bitmapTable) +#pragma unused(externalAddressTable) #endif unsigned long i; -#endif - + AllocateEnvironmentData(theEnv,SYMBOL_DATA,sizeof(struct symbolData),DeallocateSymbolData); #if ! RUN_TIME @@ -122,6 +145,9 @@ globle void InitializeAtomTables( SymbolData(theEnv)->BitMapTable = (BITMAP_HN **) gm2(theEnv,(int) sizeof (BITMAP_HN *) * BITMAP_HASH_SIZE); + SymbolData(theEnv)->ExternalAddressTable = (EXTERNAL_ADDRESS_HN **) + gm2(theEnv,(int) sizeof (EXTERNAL_ADDRESS_HN *) * EXTERNAL_ADDRESS_HASH_SIZE); + /*===================================================*/ /* Initialize all of the hash table entries to NULL. */ /*===================================================*/ @@ -130,6 +156,7 @@ globle void InitializeAtomTables( for (i = 0; i < FLOAT_HASH_SIZE; i++) SymbolData(theEnv)->FloatTable[i] = NULL; for (i = 0; i < INTEGER_HASH_SIZE; i++) SymbolData(theEnv)->IntegerTable[i] = NULL; for (i = 0; i < BITMAP_HASH_SIZE; i++) SymbolData(theEnv)->BitMapTable[i] = NULL; + for (i = 0; i < EXTERNAL_ADDRESS_HASH_SIZE; i++) SymbolData(theEnv)->ExternalAddressTable[i] = NULL; /*========================*/ /* Predefine some values. */ @@ -143,13 +170,18 @@ globle void InitializeAtomTables( IncrementSymbolCount(SymbolData(theEnv)->PositiveInfinity); SymbolData(theEnv)->NegativeInfinity = EnvAddSymbol(theEnv,NEGATIVE_INFINITY_STRING); IncrementSymbolCount(SymbolData(theEnv)->NegativeInfinity); - SymbolData(theEnv)->Zero = EnvAddLong(theEnv,0L); + SymbolData(theEnv)->Zero = EnvAddLong(theEnv,0LL); IncrementIntegerCount(SymbolData(theEnv)->Zero); #else SetSymbolTable(theEnv,symbolTable); SetFloatTable(theEnv,floatTable); SetIntegerTable(theEnv,integerTable); SetBitMapTable(theEnv,bitmapTable); + + SymbolData(theEnv)->ExternalAddressTable = (EXTERNAL_ADDRESS_HN **) + gm2(theEnv,(int) sizeof (EXTERNAL_ADDRESS_HN *) * EXTERNAL_ADDRESS_HASH_SIZE); + + for (i = 0; i < EXTERNAL_ADDRESS_HASH_SIZE; i++) SymbolData(theEnv)->ExternalAddressTable[i] = NULL; #endif } @@ -165,31 +197,32 @@ static void DeallocateSymbolData( INTEGER_HN *ihPtr, *nextIHPtr; FLOAT_HN *fhPtr, *nextFHPtr; BITMAP_HN *bmhPtr, *nextBMHPtr; - struct ephemeron *edPtr, *nextEDPtr; + EXTERNAL_ADDRESS_HN *eahPtr, *nextEAHPtr; if ((SymbolData(theEnv)->SymbolTable == NULL) || (SymbolData(theEnv)->FloatTable == NULL) || (SymbolData(theEnv)->IntegerTable == NULL) || - (SymbolData(theEnv)->BitMapTable == NULL)) + (SymbolData(theEnv)->BitMapTable == NULL) || + (SymbolData(theEnv)->ExternalAddressTable == NULL)) { return; } - - for (i = 0; i < SYMBOL_HASH_SIZE; i++) + + for (i = 0; i < SYMBOL_HASH_SIZE; i++) { shPtr = SymbolData(theEnv)->SymbolTable[i]; - + while (shPtr != NULL) { nextSHPtr = shPtr->next; if (! shPtr->permanent) { - rm(theEnv,shPtr->contents,strlen(shPtr->contents)+1); + rm(theEnv,(void *) shPtr->contents,strlen(shPtr->contents)+1); rtn_struct(theEnv,symbolHashNode,shPtr); - } + } shPtr = nextSHPtr; - } + } } - - for (i = 0; i < FLOAT_HASH_SIZE; i++) + + for (i = 0; i < FLOAT_HASH_SIZE; i++) { fhPtr = SymbolData(theEnv)->FloatTable[i]; @@ -201,8 +234,8 @@ static void DeallocateSymbolData( fhPtr = nextFHPtr; } } - - for (i = 0; i < INTEGER_HASH_SIZE; i++) + + for (i = 0; i < INTEGER_HASH_SIZE; i++) { ihPtr = SymbolData(theEnv)->IntegerTable[i]; @@ -214,8 +247,8 @@ static void DeallocateSymbolData( ihPtr = nextIHPtr; } } - - for (i = 0; i < BITMAP_HASH_SIZE; i++) + + for (i = 0; i < BITMAP_HASH_SIZE; i++) { bmhPtr = SymbolData(theEnv)->BitMapTable[i]; @@ -224,58 +257,33 @@ static void DeallocateSymbolData( nextBMHPtr = bmhPtr->next; if (! bmhPtr->permanent) { - rm(theEnv,bmhPtr->contents,bmhPtr->size); - rtn_struct(theEnv,bitMapHashNode,bmhPtr); - } + rm(theEnv,(void *) bmhPtr->contents,bmhPtr->size); + rtn_struct(theEnv,bitMapHashNode,bmhPtr); + } bmhPtr = nextBMHPtr; } } - /*=========================================*/ - /* Remove the ephemeral symbol structures. */ - /*=========================================*/ - - edPtr = SymbolData(theEnv)->EphemeralSymbolList; - - while (edPtr != NULL) - { - nextEDPtr = edPtr->next; - rtn_struct(theEnv,ephemeron,edPtr); - edPtr = nextEDPtr; - } - - edPtr = SymbolData(theEnv)->EphemeralFloatList; - - while (edPtr != NULL) - { - nextEDPtr = edPtr->next; - rtn_struct(theEnv,ephemeron,edPtr); - edPtr = nextEDPtr; - } - - edPtr = SymbolData(theEnv)->EphemeralIntegerList; - - while (edPtr != NULL) + for (i = 0; i < EXTERNAL_ADDRESS_HASH_SIZE; i++) { - nextEDPtr = edPtr->next; - rtn_struct(theEnv,ephemeron,edPtr); - edPtr = nextEDPtr; - } + eahPtr = SymbolData(theEnv)->ExternalAddressTable[i]; - edPtr = SymbolData(theEnv)->EphemeralBitMapList; - - while (edPtr != NULL) - { - nextEDPtr = edPtr->next; - rtn_struct(theEnv,ephemeron,edPtr); - edPtr = nextEDPtr; + while (eahPtr != NULL) + { + nextEAHPtr = eahPtr->next; + if (! eahPtr->permanent) + { + rtn_struct(theEnv,externalAddressHashNode,eahPtr); + } + eahPtr = nextEAHPtr; + } } /*================================*/ /* Remove the symbol hash tables. */ /*================================*/ - - #if ! RUN_TIME + + #if ! RUN_TIME rm3(theEnv,SymbolData(theEnv)->SymbolTable,sizeof (SYMBOL_HN *) * SYMBOL_HASH_SIZE); genfree(theEnv,SymbolData(theEnv)->FloatTable,(int) sizeof (FLOAT_HN *) * FLOAT_HASH_SIZE); @@ -284,11 +292,13 @@ static void DeallocateSymbolData( genfree(theEnv,SymbolData(theEnv)->BitMapTable,(int) sizeof (BITMAP_HN *) * BITMAP_HASH_SIZE); #endif - + + genfree(theEnv,SymbolData(theEnv)->ExternalAddressTable,(int) sizeof (EXTERNAL_ADDRESS_HN *) * EXTERNAL_ADDRESS_HASH_SIZE); + /*==============================*/ /* Remove binary symbol tables. */ /*==============================*/ - + #if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE || BLOAD_INSTANCES || BSAVE_INSTANCES if (SymbolData(theEnv)->SymbolArray != NULL) rm3(theEnv,(void *) SymbolData(theEnv)->SymbolArray,(long) sizeof(SYMBOL_HN *) * SymbolData(theEnv)->NumberOfSymbols); @@ -310,11 +320,12 @@ static void DeallocateSymbolData( /*********************************************************************/ globle void *EnvAddSymbol( void *theEnv, - char *str) + const char *str) { unsigned long tally; size_t length; SYMBOL_HN *past = NULL, *peek; + char *buffer; /*====================================*/ /* Get the hash value for the string. */ @@ -354,20 +365,21 @@ globle void *EnvAddSymbol( else past->next = peek; length = strlen(str) + 1; - peek->contents = (char *) gm2(theEnv,length); + buffer = (char *) gm2(theEnv,length); + genstrcpy(buffer,str); + peek->contents = buffer; peek->next = NULL; peek->bucket = tally; peek->count = 0; peek->permanent = FALSE; - strcpy(peek->contents,str); - + /*================================================*/ /* Add the string to the list of ephemeral items. */ /*================================================*/ - AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&SymbolData(theEnv)->EphemeralSymbolList, - sizeof(SYMBOL_HN),AVERAGE_STRING_SIZE); - peek->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralSymbolList, + sizeof(SYMBOL_HN),AVERAGE_STRING_SIZE,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; /*===================================*/ /* Return the address of the symbol. */ @@ -382,7 +394,7 @@ globle void *EnvAddSymbol( /*****************************************************************/ globle SYMBOL_HN *FindSymbolHN( void *theEnv, - char *str) + const char *str) { unsigned long tally; SYMBOL_HN *peek; @@ -392,8 +404,8 @@ globle SYMBOL_HN *FindSymbolHN( for (peek = SymbolData(theEnv)->SymbolTable[tally]; peek != NULL; peek = peek->next) - { - if (strcmp(str,peek->contents) == 0) + { + if (strcmp(str,peek->contents) == 0) { return(peek); } } @@ -410,7 +422,7 @@ globle void *EnvAddDouble( void *theEnv, double number) { - unsigned tally; + unsigned long tally; FLOAT_HN *past = NULL, *peek; /*====================================*/ @@ -454,9 +466,9 @@ globle void *EnvAddDouble( /* Add the float to the list of ephemeral items. */ /*===============================================*/ - AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&SymbolData(theEnv)->EphemeralFloatList, - sizeof(FLOAT_HN),0); - peek->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralFloatList, + sizeof(FLOAT_HN),0,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; /*==================================*/ /* Return the address of the float. */ @@ -465,17 +477,17 @@ globle void *EnvAddDouble( return((void *) peek); } -/****************************************************************/ -/* EnvAddLong: Searches for the long in the hash table. If the */ -/* long is already in the hash table, then the address of the */ -/* long is returned. Otherwise, the long is hashed into the */ -/* table and the address of the long is also returned. */ -/****************************************************************/ +/***************************************************************/ +/* EnvAddLong: Searches for the long in the hash table. If the */ +/* long is already in the hash table, then the address of */ +/* the long is returned. Otherwise, the long is hashed into */ +/* the table and the address of the long is also returned. */ +/***************************************************************/ globle void *EnvAddLong( void *theEnv, - long int number) + long long number) { - unsigned tally; + unsigned long tally; INTEGER_HN *past = NULL, *peek; /*==================================*/ @@ -518,9 +530,9 @@ globle void *EnvAddLong( /* Add the integer to the list of ephemeral items. */ /*=================================================*/ - AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&SymbolData(theEnv)->EphemeralIntegerList, - sizeof(INTEGER_HN),0); - peek->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralIntegerList, + sizeof(INTEGER_HN),0,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; /*====================================*/ /* Return the address of the integer. */ @@ -535,36 +547,37 @@ globle void *EnvAddLong( /*****************************************************************/ globle INTEGER_HN *FindLongHN( void *theEnv, - long int theLong) + long long theLong) { - unsigned tally; + unsigned long tally; INTEGER_HN *peek; - tally = HashInteger(theLong,INTEGER_HASH_SIZE); + tally = HashInteger(theLong,INTEGER_HASH_SIZE); - for (peek = SymbolData(theEnv)->IntegerTable[tally]; - peek != NULL; - peek = peek->next) - { if (peek->contents == theLong) return(peek); } + for (peek = SymbolData(theEnv)->IntegerTable[tally]; + peek != NULL; + peek = peek->next) + { if (peek->contents == theLong) return(peek); } - return(NULL); - } + return(NULL); + } -/******************************************************************/ -/* AddBitMap: Searches for the bitmap in the hash table. If the */ -/* bitmap is already in the hash table, then the address of the */ -/* bitmap is returned. Otherwise, the bitmap is hashed into the */ -/* table and the address of the bitmap is also returned. */ -/******************************************************************/ -globle void *AddBitMap( +/*******************************************************************/ +/* EnvAddBitMap: Searches for the bitmap in the hash table. If the */ +/* bitmap is already in the hash table, then the address of the */ +/* bitmap is returned. Otherwise, the bitmap is hashed into the */ +/* table and the address of the bitmap is also returned. */ +/*******************************************************************/ +globle void *EnvAddBitMap( void *theEnv, void *vTheBitMap, unsigned size) { char *theBitMap = (char *) vTheBitMap; - unsigned tally; + unsigned long tally; unsigned i; BITMAP_HN *past = NULL, *peek; + char *buffer; /*====================================*/ /* Get the hash value for the bitmap. */ @@ -587,7 +600,7 @@ globle void *AddBitMap( while (peek != NULL) { - if (peek->size == size) + if (peek->size == (unsigned short) size) { for (i = 0; i < size ; i++) { if (peek->contents[i] != theBitMap[i]) break; } @@ -608,22 +621,22 @@ globle void *AddBitMap( if (past == NULL) SymbolData(theEnv)->BitMapTable[tally] = peek; else past->next = peek; - peek->contents = (char *) gm2(theEnv,size); + buffer = (char *) gm2(theEnv,size); + for (i = 0; i < size ; i++) buffer[i] = theBitMap[i]; + peek->contents = buffer; peek->next = NULL; peek->bucket = tally; peek->count = 0; peek->permanent = FALSE; peek->size = (unsigned short) size; - for (i = 0; i < size ; i++) peek->contents[i] = theBitMap[i]; - /*================================================*/ /* Add the bitmap to the list of ephemeral items. */ /*================================================*/ - AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&SymbolData(theEnv)->EphemeralBitMapList, - sizeof(BITMAP_HN),sizeof(long)); - peek->depth = EvaluationData(theEnv)->CurrentEvaluationDepth; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralBitMapList, + sizeof(BITMAP_HN),sizeof(long),TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; /*===================================*/ /* Return the address of the bitmap. */ @@ -632,11 +645,81 @@ globle void *AddBitMap( return((void *) peek); } +/*******************************************************************/ +/* EnvAddExternalAddress: Searches for the external address in the */ +/* hash table. If the external address is already in the hash */ +/* table, then the address of the external address is returned. */ +/* Otherwise, the external address is hashed into the table and */ +/* the address of the external address is also returned. */ +/*******************************************************************/ +globle void *EnvAddExternalAddress( + void *theEnv, + void *theExternalAddress, + unsigned theType) + { + unsigned long tally; + EXTERNAL_ADDRESS_HN *past = NULL, *peek; + + /*====================================*/ + /* Get the hash value for the bitmap. */ + /*====================================*/ + + tally = HashExternalAddress(theExternalAddress,EXTERNAL_ADDRESS_HASH_SIZE); + + peek = SymbolData(theEnv)->ExternalAddressTable[tally]; + + /*=============================================================*/ + /* Search for the external address in the list of entries for */ + /* this hash table location. If the external addressis found, */ + /* then return the address of the external address. */ + /*=============================================================*/ + + while (peek != NULL) + { + if ((peek->type == (unsigned short) theType) && + (peek->externalAddress == theExternalAddress)) + { return((void *) peek); } + + past = peek; + peek = peek->next; + } + + /*=================================================*/ + /* Add the external address at the end of the list */ + /* of entries for this hash table location. */ + /*=================================================*/ + + peek = get_struct(theEnv,externalAddressHashNode); + if (past == NULL) SymbolData(theEnv)->ExternalAddressTable[tally] = peek; + else past->next = peek; + + peek->externalAddress = theExternalAddress; + peek->type = (unsigned short) theType; + peek->next = NULL; + peek->bucket = tally; + peek->count = 0; + peek->permanent = FALSE; + + /*================================================*/ + /* Add the bitmap to the list of ephemeral items. */ + /*================================================*/ + + AddEphemeralHashNode(theEnv,(GENERIC_HN *) peek,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralExternalAddressList, + sizeof(EXTERNAL_ADDRESS_HN),sizeof(long),TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + + /*=============================================*/ + /* Return the address of the external address. */ + /*=============================================*/ + + return((void *) peek); + } + /***************************************************/ /* HashSymbol: Computes a hash value for a symbol. */ /***************************************************/ globle unsigned long HashSymbol( - char *word, + const char *word, unsigned long range) { register int i; @@ -645,52 +728,92 @@ globle unsigned long HashSymbol( for (i = 0; word[i]; i++) { tally = tally * 127 + word[i]; } + if (range == 0) + { return tally; } + return(tally % range); } /*************************************************/ /* HashFloat: Computes a hash value for a float. */ /*************************************************/ -globle unsigned HashFloat( +globle unsigned long HashFloat( double number, - unsigned range) + unsigned long range) { unsigned long tally = 0; char *word; unsigned i; - + word = (char *) &number; - + for (i = 0; i < sizeof(double); i++) { tally = tally * 127 + word[i]; } - + + if (range == 0) + { return tally; } + return(tally % range); } /******************************************************/ /* HashInteger: Computes a hash value for an integer. */ /******************************************************/ -globle unsigned HashInteger( - long int number, - unsigned range) +globle unsigned long HashInteger( + long long number, + unsigned long range) { - unsigned tally; + unsigned long tally; + +#if WIN_MVC + if (number < 0) + { number = - number; } + tally = (((unsigned) number) % range); +#else + tally = (((unsigned) llabs(number)) % range); +#endif - tally = (labs(number) % range); + if (range == 0) + { return tally; } return(tally); } +/****************************************/ +/* HashExternalAddress: Computes a hash */ +/* value for an external address. */ +/****************************************/ +globle unsigned long HashExternalAddress( + void *theExternalAddress, + unsigned long range) + { + unsigned long tally; + union + { + void *vv; + unsigned uv; + } fis; + + fis.uv = 0; + fis.vv = theExternalAddress; + tally = (fis.uv / 256); + + if (range == 0) + { return tally; } + + return(tally % range); + } + /***************************************************/ /* HashBitMap: Computes a hash value for a bitmap. */ /***************************************************/ -globle unsigned HashBitMap( - char *word, - unsigned range, +globle unsigned long HashBitMap( + const char *word, + unsigned long range, unsigned length) { register unsigned k,j,i; - unsigned tally; + unsigned long tally; unsigned longLength; unsigned long count = 0L,tmpLong; char *tmpPtr; @@ -719,6 +842,9 @@ globle unsigned HashBitMap( /* Return the hash value. */ /*========================*/ + if (range == 0) + { return count; } + tally = (count % range); return(tally); @@ -751,8 +877,9 @@ globle void DecrementSymbolCount( if (theValue->markedEphemeral == FALSE) { - AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&SymbolData(theEnv)->EphemeralSymbolList, - sizeof(SYMBOL_HN),AVERAGE_STRING_SIZE); + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralSymbolList, + sizeof(SYMBOL_HN),AVERAGE_STRING_SIZE,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; } return; @@ -779,8 +906,9 @@ globle void DecrementFloatCount( if (theValue->markedEphemeral == FALSE) { - AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&SymbolData(theEnv)->EphemeralFloatList, - sizeof(FLOAT_HN),0); + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralFloatList, + sizeof(FLOAT_HN),0,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; } return; @@ -807,8 +935,9 @@ globle void DecrementIntegerCount( if (theValue->markedEphemeral == FALSE) { - AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&SymbolData(theEnv)->EphemeralIntegerList, - sizeof(INTEGER_HN),0); + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralIntegerList, + sizeof(INTEGER_HN),0,TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; } return; @@ -841,17 +970,54 @@ globle void DecrementBitMapCount( if (theValue->markedEphemeral == FALSE) { - AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&SymbolData(theEnv)->EphemeralBitMapList, - sizeof(BITMAP_HN),sizeof(long)); + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralBitMapList, + sizeof(BITMAP_HN),sizeof(long),TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; } return; } /*************************************************************/ -/* RemoveHashNode: Removes a hash node from the SymbolTable, */ -/* FloatTable, IntegerTable, or BitMapTable. */ +/* DecrementExternalAddressCount: Decrements the count value */ +/* for an ExternAddressTable entry. Adds the bitmap to the */ +/* EphemeralExternalAddressList if the count becomes zero. */ /*************************************************************/ +globle void DecrementExternalAddressCount( + void *theEnv, + EXTERNAL_ADDRESS_HN *theValue) + { + if (theValue->count < 0) + { + SystemError(theEnv,"SYMBOL",9); + EnvExitRouter(theEnv,EXIT_FAILURE); + } + + if (theValue->count == 0) + { + SystemError(theEnv,"SYMBOL",10); + EnvExitRouter(theEnv,EXIT_FAILURE); + } + + theValue->count--; + + if (theValue->count != 0) return; + + if (theValue->markedEphemeral == FALSE) + { + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue,&UtilityData(theEnv)->CurrentGarbageFrame->ephemeralExternalAddressList, + sizeof(EXTERNAL_ADDRESS_HN),sizeof(long),TRUE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + } + + return; + } + +/************************************************/ +/* RemoveHashNode: Removes a hash node from the */ +/* SymbolTable, FloatTable, IntegerTable, */ +/* BitMapTable, or ExternalAddressTable. */ +/************************************************/ static void RemoveHashNode( void *theEnv, GENERIC_HN *theValue, @@ -860,6 +1026,7 @@ static void RemoveHashNode( int type) { GENERIC_HN *previousNode, *currentNode; + struct externalAddressHashNode *theAddress; /*=============================================*/ /* Find the entry in the specified hash table. */ @@ -875,7 +1042,7 @@ static void RemoveHashNode( if (currentNode == NULL) { - SystemError(theEnv,"SYMBOL",9); + SystemError(theEnv,"SYMBOL",11); EnvExitRouter(theEnv,EXIT_FAILURE); } } @@ -897,14 +1064,22 @@ static void RemoveHashNode( if (type == SYMBOL) { - rm(theEnv,((SYMBOL_HN *) theValue)->contents, + rm(theEnv,(void *) ((SYMBOL_HN *) theValue)->contents, strlen(((SYMBOL_HN *) theValue)->contents) + 1); } else if (type == BITMAPARRAY) { - rm(theEnv,((BITMAP_HN *) theValue)->contents, + rm(theEnv,(void *) ((BITMAP_HN *) theValue)->contents, ((BITMAP_HN *) theValue)->size); } + else if (type == EXTERNAL_ADDRESS) + { + theAddress = (struct externalAddressHashNode *) theValue; + + if ((EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type] != NULL) && + (EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type]->discardFunction != NULL)) + { (*EvaluationData(theEnv)->ExternalAddressTypes[theAddress->type]->discardFunction)(theEnv,theAddress->externalAddress); } + } /*===========================*/ /* Return the table entry to */ @@ -925,7 +1100,8 @@ static void AddEphemeralHashNode( GENERIC_HN *theHashNode, struct ephemeron **theEphemeralList, int hashNodeSize, - int averageContentsSize) + int averageContentsSize, + int checkCount) { struct ephemeron *temp; @@ -934,9 +1110,9 @@ static void AddEphemeralHashNode( /* should never have been called. */ /*===========================================*/ - if (theHashNode->count != 0) + if (checkCount && (theHashNode->count != 0)) { - SystemError(theEnv,"SYMBOL",10); + SystemError(theEnv,"SYMBOL",12); EnvExitRouter(theEnv,EXIT_FAILURE); } @@ -955,16 +1131,6 @@ static void AddEphemeralHashNode( temp->associatedValue = theHashNode; temp->next = *theEphemeralList; *theEphemeralList = temp; - - /*=========================================================*/ - /* Increment the ephemeral count and size variables. These */ - /* variables are used by the garbage collection routines */ - /* to determine when garbage collection should occur. */ - /*=========================================================*/ - - UtilityData(theEnv)->EphemeralItemCount++; - UtilityData(theEnv)->EphemeralItemSize += sizeof(struct ephemeron) + hashNodeSize + - averageContentsSize; } /***************************************************/ @@ -976,16 +1142,107 @@ static void AddEphemeralHashNode( globle void RemoveEphemeralAtoms( void *theEnv) { - RemoveEphemeralHashNodes(theEnv,&SymbolData(theEnv)->EphemeralSymbolList,(GENERIC_HN **) SymbolData(theEnv)->SymbolTable, + struct garbageFrame *theGarbageFrame; + + theGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + if (! theGarbageFrame->dirty) return; + + RemoveEphemeralHashNodes(theEnv,&theGarbageFrame->ephemeralSymbolList,(GENERIC_HN **) SymbolData(theEnv)->SymbolTable, sizeof(SYMBOL_HN),SYMBOL,AVERAGE_STRING_SIZE); - RemoveEphemeralHashNodes(theEnv,&SymbolData(theEnv)->EphemeralFloatList,(GENERIC_HN **) SymbolData(theEnv)->FloatTable, + RemoveEphemeralHashNodes(theEnv,&theGarbageFrame->ephemeralFloatList,(GENERIC_HN **) SymbolData(theEnv)->FloatTable, sizeof(FLOAT_HN),FLOAT,0); - RemoveEphemeralHashNodes(theEnv,&SymbolData(theEnv)->EphemeralIntegerList,(GENERIC_HN **) SymbolData(theEnv)->IntegerTable, + RemoveEphemeralHashNodes(theEnv,&theGarbageFrame->ephemeralIntegerList,(GENERIC_HN **) SymbolData(theEnv)->IntegerTable, sizeof(INTEGER_HN),INTEGER,0); - RemoveEphemeralHashNodes(theEnv,&SymbolData(theEnv)->EphemeralBitMapList,(GENERIC_HN **) SymbolData(theEnv)->BitMapTable, + RemoveEphemeralHashNodes(theEnv,&theGarbageFrame->ephemeralBitMapList,(GENERIC_HN **) SymbolData(theEnv)->BitMapTable, sizeof(BITMAP_HN),BITMAPARRAY,AVERAGE_BITMAP_SIZE); + RemoveEphemeralHashNodes(theEnv,&theGarbageFrame->ephemeralExternalAddressList,(GENERIC_HN **) SymbolData(theEnv)->ExternalAddressTable, + sizeof(EXTERNAL_ADDRESS_HN),EXTERNAL_ADDRESS,0); + } + +/**********************************************************/ +/* EphemerateMultifield: Marks the values of a multifield */ +/* as ephemeral if they have not already been marker. */ +/**********************************************************/ +globle void EphemerateMultifield( + void *theEnv, + struct multifield *theSegment) + { + unsigned long length, i; + struct field *theFields; + + if (theSegment == NULL) return; + + length = theSegment->multifieldLength; + + theFields = theSegment->theFields; + + for (i = 0 ; i < length ; i++) + { EphemerateValue(theEnv,theFields[i].type,theFields[i].value); } } +/***********************************************/ +/* EphemerateValue: Marks a value as ephemeral */ +/* if it is not already marked. */ +/***********************************************/ +globle void EphemerateValue( + void *theEnv, + int theType, + void *theValue) + { + SYMBOL_HN *theSymbol; + FLOAT_HN *theFloat; + INTEGER_HN *theInteger; + EXTERNAL_ADDRESS_HN *theExternalAddress; + + switch (theType) + { + case SYMBOL: + case STRING: +#if OBJECT_SYSTEM + case INSTANCE_NAME: +#endif + theSymbol = (SYMBOL_HN *) theValue; + if (theSymbol->markedEphemeral) return; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue, + &UtilityData(theEnv)->CurrentGarbageFrame->ephemeralSymbolList, + sizeof(SYMBOL_HN),AVERAGE_STRING_SIZE,FALSE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + break; + + case FLOAT: + theFloat = (FLOAT_HN *) theValue; + if (theFloat->markedEphemeral) return; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue, + &UtilityData(theEnv)->CurrentGarbageFrame->ephemeralFloatList, + sizeof(FLOAT_HN),0,FALSE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + break; + + case INTEGER: + theInteger = (INTEGER_HN *) theValue; + if (theInteger->markedEphemeral) return; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue, + &UtilityData(theEnv)->CurrentGarbageFrame->ephemeralIntegerList, + sizeof(INTEGER_HN),0,FALSE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + break; + + case EXTERNAL_ADDRESS: + theExternalAddress = (EXTERNAL_ADDRESS_HN *) theValue; + if (theExternalAddress->markedEphemeral) return; + AddEphemeralHashNode(theEnv,(GENERIC_HN *) theValue, + &UtilityData(theEnv)->CurrentGarbageFrame->ephemeralExternalAddressList, + sizeof(EXTERNAL_ADDRESS_HN),sizeof(long),FALSE); + UtilityData(theEnv)->CurrentGarbageFrame->dirty = TRUE; + break; + + case MULTIFIELD: + EphemerateMultifield(theEnv,(struct multifield *) theValue); + break; + + } + } + /****************************************************************/ /* RemoveEphemeralHashNodes: Removes symbols from the ephemeral */ /* symbol list that have a count of zero and were placed on */ @@ -1025,16 +1282,12 @@ static void RemoveEphemeralHashNodes( /* evaluation depth. */ /*==================================================*/ - if ((edPtr->associatedValue->count == 0) && - (edPtr->associatedValue->depth > EvaluationData(theEnv)->CurrentEvaluationDepth)) + if (edPtr->associatedValue->count == 0) { RemoveHashNode(theEnv,edPtr->associatedValue,theTable,hashNodeSize,hashNodeType); rtn_struct(theEnv,ephemeron,edPtr); if (lastPtr == NULL) *theEphemeralList = nextPtr; else lastPtr->next = nextPtr; - UtilityData(theEnv)->EphemeralItemCount--; - UtilityData(theEnv)->EphemeralItemSize -= sizeof(struct ephemeron) + hashNodeSize + - averageContentsSize; } /*=======================================*/ @@ -1050,9 +1303,6 @@ static void RemoveEphemeralHashNodes( if (lastPtr == NULL) *theEphemeralList = nextPtr; else lastPtr->next = nextPtr; - UtilityData(theEnv)->EphemeralItemCount--; - UtilityData(theEnv)->EphemeralItemSize -= sizeof(struct ephemeron) + hashNodeSize + - averageContentsSize; } /*==================================================*/ @@ -1142,6 +1392,25 @@ globle void SetBitMapTable( SymbolData(theEnv)->BitMapTable = value; } +/***************************************************************************/ +/* GetExternalAddressTable: Returns a pointer to the ExternalAddressTable. */ +/***************************************************************************/ +globle EXTERNAL_ADDRESS_HN **GetExternalAddressTable( + void *theEnv) + { + return(SymbolData(theEnv)->ExternalAddressTable); + } + +/************************************************************************/ +/* SetExternalAddressTable: Sets the value of the ExternalAddressTable. */ +/************************************************************************/ +globle void SetExternalAddressTable( + void *theEnv, + EXTERNAL_ADDRESS_HN **value) + { + SymbolData(theEnv)->ExternalAddressTable = value; + } + /******************************************************/ /* RefreshSpecialSymbols: Resets the values of the */ /* TrueSymbol, FalseSymbol, Zero, PositiveInfinity, */ @@ -1165,13 +1434,13 @@ globle void RefreshSpecialSymbols( /***********************************************************/ globle struct symbolMatch *FindSymbolMatches( void *theEnv, - char *searchString, + const char *searchString, unsigned *numberOfMatches, - unsigned *commonPrefixLength) + size_t *commonPrefixLength) { struct symbolMatch *reply = NULL, *temp; struct symbolHashNode *hashPtr = NULL; - unsigned searchLength; + size_t searchLength; searchLength = strlen(searchString); *numberOfMatches = 0; @@ -1227,16 +1496,16 @@ globle void ClearBitString( /*****************************************************************/ globle SYMBOL_HN *GetNextSymbolMatch( void *theEnv, - char *searchString, - unsigned searchLength, + const char *searchString, + size_t searchLength, SYMBOL_HN *prevSymbol, int anywhere, - unsigned *commonPrefixLength) + size_t *commonPrefixLength) { register unsigned long i; SYMBOL_HN *hashPtr; int flag = TRUE; - unsigned prefixLength; + size_t prefixLength; /*==========================================*/ /* If we're looking anywhere in the string, */ @@ -1360,9 +1629,9 @@ globle SYMBOL_HN *GetNextSymbolMatch( /* StringWithinString: Determines if a string */ /* is contained within another string. */ /**********************************************/ -static char *StringWithinString( - char *cs, - char *ct) +static const char *StringWithinString( + const char *cs, + const char *ct) { register unsigned i,j,k; @@ -1379,9 +1648,9 @@ static char *StringWithinString( /* CommonPrefixLength: Determines the length of */ /* the maximumcommon prefix of two strings */ /************************************************/ -static unsigned CommonPrefixLength( - char *cs, - char *ct) +static size_t CommonPrefixLength( + const char *cs, + const char *ct) { register unsigned i; @@ -1427,7 +1696,7 @@ globle void SetAtomicValueIndices( { symbolPtr->bucket = count++; if (symbolPtr->bucket != (count - 1)) - { SystemError(theEnv,"SYMBOL",667); } + { SystemError(theEnv,"SYMBOL",13); } } } } @@ -1449,7 +1718,7 @@ globle void SetAtomicValueIndices( { floatPtr->bucket = count++; if (floatPtr->bucket != (count - 1)) - { SystemError(theEnv,"SYMBOL",668); } + { SystemError(theEnv,"SYMBOL",14); } } } } @@ -1471,7 +1740,7 @@ globle void SetAtomicValueIndices( { integerPtr->bucket = count++; if (integerPtr->bucket != (count - 1)) - { SystemError(theEnv,"SYMBOL",669); } + { SystemError(theEnv,"SYMBOL",15); } } } } @@ -1493,7 +1762,7 @@ globle void SetAtomicValueIndices( { bitMapPtr->bucket = count++; if (bitMapPtr->bucket != (count - 1)) - { SystemError(theEnv,"SYMBOL",670); } + { SystemError(theEnv,"SYMBOL",16); } } } } @@ -1571,3 +1840,56 @@ globle void RestoreAtomicValueBuckets( } #endif /* BLOAD_AND_BSAVE || CONSTRUCT_COMPILER || BSAVE_INSTANCES */ + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle void *EnvFalseSymbol( + void *theEnv) + { + return SymbolData(theEnv)->FalseSymbolHN; + } + +globle void *EnvTrueSymbol( + void *theEnv) + { + return SymbolData(theEnv)->TrueSymbolHN; + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void *AddSymbol( + const char *str) + { + return EnvAddSymbol(GetCurrentEnvironment(),str); + } + +globle void *AddLong( + long long number) + { + return EnvAddLong(GetCurrentEnvironment(),number); + } + +globle void *AddDouble( + double number) + { + return EnvAddDouble(GetCurrentEnvironment(),number); + } + +globle void *FalseSymbol() + { + return SymbolData(GetCurrentEnvironment())->FalseSymbolHN; + } + +globle void *TrueSymbol() + { + return SymbolData(GetCurrentEnvironment())->TrueSymbolHN; + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + diff --git a/src/symbol.h b/src/symbol.h index 00bf577..894f808 100644 --- a/src/symbol.h +++ b/src/symbol.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/03/15 */ /* */ /* SYMBOL HEADER FILE */ /*******************************************************/ @@ -19,11 +19,45 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ -/* 6.24: Support for run-time programs directly passing */ +/* 6.24: CLIPS crashing on AMD64 processor in the */ +/* function used to generate a hash value for */ +/* integers. DR0871 */ +/* */ +/* Support for run-time programs directly passing */ /* the hash tables for initialization. */ /* */ +/* Corrected code generating compilation */ +/* warnings. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for hashing EXTERNAL_ADDRESS data */ +/* type. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Used genstrcpy instead of strcpy. */ +/* */ +/* Added support for external address hash table */ +/* and subtyping. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added ValueToPointer and EnvValueToPointer */ +/* macros. */ +/* */ /*************************************************************/ #ifndef _H_symbol @@ -39,6 +73,12 @@ #define LOCALE extern #endif +#include <stdlib.h> + +#ifndef _H_multifld +#include "multifld.h" +#endif + #ifndef SYMBOL_HASH_SIZE #define SYMBOL_HASH_SIZE 63559L #endif @@ -55,6 +95,10 @@ #define BITMAP_HASH_SIZE 8191 #endif +#ifndef EXTERNAL_ADDRESS_HASH_SIZE +#define EXTERNAL_ADDRESS_HASH_SIZE 8191 +#endif + /************************************************************/ /* symbolHashNode STRUCTURE: */ /************************************************************/ @@ -62,12 +106,11 @@ struct symbolHashNode { struct symbolHashNode *next; long count; - int depth; unsigned int permanent : 1; unsigned int markedEphemeral : 1; unsigned int neededSymbol : 1; unsigned int bucket : 29; - char *contents; + const char *contents; }; /************************************************************/ @@ -77,7 +120,6 @@ struct floatHashNode { struct floatHashNode *next; long count; - int depth; unsigned int permanent : 1; unsigned int markedEphemeral : 1; unsigned int neededFloat : 1; @@ -92,12 +134,11 @@ struct integerHashNode { struct integerHashNode *next; long count; - int depth; unsigned int permanent : 1; unsigned int markedEphemeral : 1; unsigned int neededInteger : 1; unsigned int bucket : 29; - long int contents; + long long contents; }; /************************************************************/ @@ -107,23 +148,36 @@ struct bitMapHashNode { struct bitMapHashNode *next; long count; - int depth; unsigned int permanent : 1; unsigned int markedEphemeral : 1; unsigned int neededBitMap : 1; unsigned int bucket : 29; - char *contents; + const char *contents; unsigned short size; }; /************************************************************/ +/* externalAddressHashNode STRUCTURE: */ +/************************************************************/ +struct externalAddressHashNode + { + struct externalAddressHashNode *next; + long count; + unsigned int permanent : 1; + unsigned int markedEphemeral : 1; + unsigned int neededPointer : 1; + unsigned int bucket : 29; + void *externalAddress; + unsigned short type; + }; + +/************************************************************/ /* genericHashNode STRUCTURE: */ /************************************************************/ struct genericHashNode { struct genericHashNode *next; long count; - int depth; unsigned int permanent : 1; unsigned int markedEphemeral : 1; unsigned int needed : 1; @@ -134,6 +188,7 @@ typedef struct symbolHashNode SYMBOL_HN; typedef struct floatHashNode FLOAT_HN; typedef struct integerHashNode INTEGER_HN; typedef struct bitMapHashNode BITMAP_HN; +typedef struct externalAddressHashNode EXTERNAL_ADDRESS_HN; typedef struct genericHashNode GENERIC_HN; /**********************************************************/ @@ -167,17 +222,22 @@ struct symbolMatch #define ValueToLong(target) (((struct integerHashNode *) (target))->contents) #define ValueToInteger(target) ((int) (((struct integerHashNode *) (target))->contents)) #define ValueToBitMap(target) ((void *) ((struct bitMapHashNode *) (target))->contents) +#define ValueToPointer(target) ((void *) target) +#define ValueToExternalAddress(target) ((void *) ((struct externalAddressHashNode *) (target))->externalAddress) #define EnvValueToString(theEnv,target) (((struct symbolHashNode *) (target))->contents) #define EnvValueToDouble(theEnv,target) (((struct floatHashNode *) (target))->contents) #define EnvValueToLong(theEnv,target) (((struct integerHashNode *) (target))->contents) #define EnvValueToInteger(theEnv,target) ((int) (((struct integerHashNode *) (target))->contents)) #define EnvValueToBitMap(theEnv,target) ((void *) ((struct bitMapHashNode *) (target))->contents) +#define EnvValueToPointer(theEnv,target) ((void *) target) +#define EnvValueToExternalAddress(theEnv,target) ((void *) ((struct externalAddressHashNode *) (target))->externalAddress) #define IncrementSymbolCount(theValue) (((SYMBOL_HN *) theValue)->count++) #define IncrementFloatCount(theValue) (((FLOAT_HN *) theValue)->count++) #define IncrementIntegerCount(theValue) (((INTEGER_HN *) theValue)->count++) #define IncrementBitMapCount(theValue) (((BITMAP_HN *) theValue)->count++) +#define IncrementExternalAddressCount(theValue) (((EXTERNAL_ADDRESS_HN *) theValue)->count++) /*==================*/ /* ENVIRONMENT DATA */ @@ -186,7 +246,7 @@ struct symbolMatch #define SYMBOL_DATA 49 struct symbolData - { + { void *TrueSymbolHN; void *FalseSymbolHN; void *PositiveInfinity; @@ -196,56 +256,43 @@ struct symbolData FLOAT_HN **FloatTable; INTEGER_HN **IntegerTable; BITMAP_HN **BitMapTable; - struct ephemeron *EphemeralSymbolList; - struct ephemeron *EphemeralFloatList; - struct ephemeron *EphemeralIntegerList; - struct ephemeron *EphemeralBitMapList; + EXTERNAL_ADDRESS_HN **ExternalAddressTable; #if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE || BLOAD_INSTANCES || BSAVE_INSTANCES long NumberOfSymbols; long NumberOfFloats; long NumberOfIntegers; long NumberOfBitMaps; + long NumberOfExternalAddresses; SYMBOL_HN **SymbolArray; struct floatHashNode **FloatArray; INTEGER_HN **IntegerArray; BITMAP_HN **BitMapArray; + EXTERNAL_ADDRESS_HN **ExternalAddressArray; #endif }; #define SymbolData(theEnv) ((struct symbolData *) GetEnvironmentData(theEnv,SYMBOL_DATA)) -#define EnvFalseSymbol(theEnv) SymbolData(theEnv)->FalseSymbolHN -#define EnvTrueSymbol(theEnv) SymbolData(theEnv)->TrueSymbolHN - -#if ENVIRONMENT_API_ONLY -#define FalseSymbol(theEnv) SymbolData(theEnv)->FalseSymbolHN -#define TrueSymbol(theEnv) SymbolData(theEnv)->TrueSymbolHN -#define AddSymbol(theEnv,a) EnvAddSymbol(theEnv,a) -#define AddLong(theEnv,a) EnvAddLong(theEnv,a) -#define AddDouble(theEnv,a) EnvAddDouble(theEnv,a) -#else -#define FalseSymbol() SymbolData(GetCurrentEnvironment())->FalseSymbolHN -#define TrueSymbol() SymbolData(GetCurrentEnvironment())->TrueSymbolHN -#define AddSymbol(a) EnvAddSymbol(GetCurrentEnvironment(),a) -#define AddLong(a) EnvAddLong(GetCurrentEnvironment(),a) -#define AddDouble(a) EnvAddDouble(GetCurrentEnvironment(),a) -#endif LOCALE void InitializeAtomTables(void *,struct symbolHashNode **,struct floatHashNode **, - struct integerHashNode **,struct bitMapHashNode **); - LOCALE void *EnvAddSymbol(void *,char *); - LOCALE SYMBOL_HN *FindSymbolHN(void *,char *); + struct integerHashNode **,struct bitMapHashNode **, + struct externalAddressHashNode **); + LOCALE void *EnvAddSymbol(void *,const char *); + LOCALE SYMBOL_HN *FindSymbolHN(void *,const char *); LOCALE void *EnvAddDouble(void *,double); - LOCALE void *EnvAddLong(void *,long int); - LOCALE void *AddBitMap(void *,void *,unsigned); - LOCALE INTEGER_HN *FindLongHN(void *,long int); - LOCALE unsigned long HashSymbol(char *,unsigned long); - LOCALE unsigned HashFloat(double,unsigned); - LOCALE unsigned HashInteger(long int,unsigned); - LOCALE unsigned HashBitMap(char *,unsigned,unsigned); + LOCALE void *EnvAddLong(void *,long long); + LOCALE void *EnvAddBitMap(void *,void *,unsigned); + LOCALE void *EnvAddExternalAddress(void *,void *,unsigned); + LOCALE INTEGER_HN *FindLongHN(void *,long long); + LOCALE unsigned long HashSymbol(const char *,unsigned long); + LOCALE unsigned long HashFloat(double,unsigned long); + LOCALE unsigned long HashInteger(long long,unsigned long); + LOCALE unsigned long HashBitMap(const char *,unsigned long,unsigned); + LOCALE unsigned long HashExternalAddress(void *,unsigned long); LOCALE void DecrementSymbolCount(void *,struct symbolHashNode *); LOCALE void DecrementFloatCount(void *,struct floatHashNode *); LOCALE void DecrementIntegerCount(void *,struct integerHashNode *); LOCALE void DecrementBitMapCount(void *,struct bitMapHashNode *); + LOCALE void DecrementExternalAddressCount(void *,struct externalAddressHashNode *); LOCALE void RemoveEphemeralAtoms(void *); LOCALE struct symbolHashNode **GetSymbolTable(void *); LOCALE void SetSymbolTable(void *,struct symbolHashNode **); @@ -255,15 +302,32 @@ struct symbolData LOCALE void SetIntegerTable(void *,struct integerHashNode **); LOCALE struct bitMapHashNode **GetBitMapTable(void *); LOCALE void SetBitMapTable(void *,struct bitMapHashNode **); + LOCALE struct externalAddressHashNode + **GetExternalAddressTable(void *); + LOCALE void SetExternalAddressTable(void *,struct externalAddressHashNode **); LOCALE void RefreshSpecialSymbols(void *); - LOCALE struct symbolMatch *FindSymbolMatches(void *,char *,unsigned *,unsigned *); + LOCALE struct symbolMatch *FindSymbolMatches(void *,const char *,unsigned *,size_t *); LOCALE void ReturnSymbolMatches(void *,struct symbolMatch *); - LOCALE SYMBOL_HN *GetNextSymbolMatch(void *,char *,unsigned,SYMBOL_HN *,int,unsigned *); + LOCALE SYMBOL_HN *GetNextSymbolMatch(void *,const char *,size_t,SYMBOL_HN *,int,size_t *); LOCALE void ClearBitString(void *,unsigned); LOCALE void SetAtomicValueIndices(void *,int); LOCALE void RestoreAtomicValueBuckets(void *); + LOCALE void *EnvFalseSymbol(void *); + LOCALE void *EnvTrueSymbol(void *); + LOCALE void EphemerateValue(void *,int,void *); + LOCALE void EphemerateMultifield(void *,struct multifield *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void *AddDouble(double); + LOCALE void *AddLong(long long); + LOCALE void *AddSymbol(const char *); + LOCALE void *FalseSymbol(void); + LOCALE void *TrueSymbol(void); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_symbol */ diff --git a/src/sysdep.c b/src/sysdep.c index 7d9928b..32e2204 100644 --- a/src/sysdep.c +++ b/src/sysdep.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 05/17/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* SYSTEM DEPENDENT MODULE */ /*******************************************************/ @@ -13,9 +13,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Modified GenOpen to check the file length */ /* against the system constant FILENAME_MAX. */ /* */ @@ -32,6 +33,48 @@ /* */ /* Updated UNIX_V gentime functionality. */ /* */ +/* Removed GenOpen check against FILENAME_MAX. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, IBM_ICB, IBM_TBC, IBM_ZTC, and */ +/* IBM_SC). */ +/* */ +/* Renamed IBM_MSC and WIN_MVC compiler flags */ +/* and IBM_GCC to WIN_GCC. */ +/* */ +/* Added LINUX and DARWIN compiler flags. */ +/* */ +/* Removed HELP_FUNCTIONS compilation flag and */ +/* associated functionality. */ +/* */ +/* Removed EMACS_EDITOR compilation flag and */ +/* associated functionality. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the single IO_FUNCTIONS flag. */ +/* */ +/* Changed the EX_MATH compilation flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* GenOpen function checks for UTF-8 Byte Order */ +/* Marker. */ +/* */ +/* Added gengetchar, genungetchar, genprintfile, */ +/* genstrcpy, genstrncpy, genstrcat, genstrncat, */ +/* and gensprintf functions. */ +/* */ +/* Added SetJmpBuffer function. */ +/* */ +/* Added environment argument to genexit. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _SYSDEP_SOURCE_ @@ -44,6 +87,7 @@ #include <stdlib.h> #include <time.h> +#include <stdarg.h> #if VAX_VMS #include timeb @@ -54,70 +98,42 @@ extern int LIB$SPAWN(); #endif -#if MAC - -#if MAC_MCW || MAC_XCD +#if MAC_XCD #include <Carbon/Carbon.h> +#define kTwoPower32 (4294967296.0) /* 2^32 */ #endif -#define kTwoPower32 (4294967296.0) /* 2^32 */ -#if MAC_MCW || MAC_XCD +#if MAC_XCD #include <strings.h> #endif -#endif -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #include <unistd.h> #endif - -#if IBM_ICB -#include <i32.h> -#include <stk.h> -#include <sys\types.h> -#include <sys\timeb.h> -#include <io.h> -#include <fcntl.h> -#include <limits.h> -#include <process.h> +/* +#if WIN_MVC +#define _UNICODE +#define UNICODE +#include <Windows.h> #endif - -#if IBM_MSC +*/ +#if WIN_MVC #include <sys\types.h> #include <sys\timeb.h> #include <io.h> #include <fcntl.h> #include <limits.h> #include <process.h> +#include <signal.h> #endif -#if IBM_TBC -#include <bios.h> -#include <io.h> -#include <fcntl.h> -#include <limits.h> -#endif - -#if IBM_MCW -#include <io.h> -#include <limits.h> -#endif - -#if IBM_ZTC || IBM_SC -#include <time.h> -#include <controlc.h> -#include <io.h> -#include <fcntl.h> -#include <limits.h> -#include <process.h> -#endif - -#if UNIX_7 || IBM_GCC +#if UNIX_7 || WIN_GCC #include <sys/types.h> #include <sys/timeb.h> #include <signal.h> #endif -#if UNIX_V +#if UNIX_V || LINUX || DARWIN #include <sys/types.h> #include <sys/time.h> #include <sys/times.h> @@ -184,10 +200,6 @@ extern int LIB$SPAWN(); #include "moduldef.h" -#if EMACS_EDITOR -#include "ed.h" -#endif - #if DEVELOPER #include "developr.h" #endif @@ -212,29 +224,26 @@ struct systemDependentData void (*RedrawScreenFunction)(void *); void (*PauseEnvFunction)(void *); void (*ContinueEnvFunction)(void *,int); +/* #if ! WINDOW_INTERFACE -#if IBM_TBC - void interrupt (*OldCtrlC)(void); - void interrupt (*OldBreak)(void); -#endif -#if IBM_MSC +#if WIN_MVC void (interrupt *OldCtrlC)(void); void (interrupt *OldBreak)(void); #endif -#if IBM_ICB -#pragma interrupt (OldCtrlC,OldBreak) - void (*OldCtrlC)(void); - void (*OldBreak)(void); #endif -#endif -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW || IBM_ZTC */ +*/ +#if WIN_MVC int BinaryFileHandle; + unsigned char getcBuffer[7]; + int getcLength; + int getcPosition; #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) && (! IBM_ZTC) */ +#if (! WIN_MVC) FILE *BinaryFP; #endif int (*BeforeOpenFunction)(void *); int (*AfterOpenFunction)(void *); + jmp_buf *jmpBuffer; }; #define SystemDependentData(theEnv) ((struct systemDependentData *) GetEnvironmentData(theEnv,SYSTEM_DEPENDENT_DATA)) @@ -254,24 +263,15 @@ struct systemDependentData static void SystemFunctionDefinitions(void *); static void InitializeKeywords(void *); static void InitializeNonportableFeatures(void *); -#if (VAX_VMS || UNIX_V || UNIX_7 || IBM_GCC) && (! WINDOW_INTERFACE) +#if (VAX_VMS || UNIX_V || LINUX || DARWIN || UNIX_7 || WIN_GCC || WIN_MVC) && (! WINDOW_INTERFACE) static void CatchCtrlC(int); #endif -#if (IBM_TBC || IBM_MSC) && (! WINDOW_INTERFACE) +/* +#if (WIN_MVC) && (! WINDOW_INTERFACE) static void interrupt CatchCtrlC(void); static void RestoreInterruptVectors(void); #endif -#if IBM_ICB && (! WINDOW_INTERFACE) -#pragma interrupt (CatchCtrlC) - static void CatchCtrlC(void); - static void RestoreInterruptVectors(void); -#endif -#if (IBM_ZTC || IBM_SC) && (! WINDOW_INTERFACE) - static void _cdecl CatchCtrlC(void); -#endif -#if MAC && (! WINDOW_INTERFACE) - static void CallSystemTask(void); -#endif +*/ /********************************************************/ /* InitializeSystemDependentData: Allocates environment */ @@ -287,7 +287,7 @@ static void InitializeSystemDependentData( /* InitializeEnvironment: Performs initialization */ /* of the KB environment. */ /**************************************************/ -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS +#if ALLOW_ENVIRONMENT_GLOBALS globle void InitializeEnvironment() { if (GetCurrentEnvironment() == NULL) @@ -304,7 +304,8 @@ globle void EnvInitializeEnvironment( struct symbolHashNode **symbolTable, struct floatHashNode **floatTable, struct integerHashNode **integerTable, - struct bitMapHashNode **bitmapTable) + struct bitMapHashNode **bitmapTable, + struct externalAddressHashNode **externalAddressTable) { struct environmentData *theEnvironment = (struct environmentData *) vtheEnvironment; @@ -331,7 +332,6 @@ globle void EnvInitializeEnvironment( InitializeConstructData(theEnvironment); InitializeEvaluationData(theEnvironment); InitializeExternalFunctionData(theEnvironment); - InitializeMultifieldData(theEnvironment); InitializePrettyPrintData(theEnvironment); InitializePrintUtilityData(theEnvironment); InitializeScannerData(theEnvironment); @@ -346,7 +346,7 @@ globle void EnvInitializeEnvironment( /* Initialize the hash tables for atomic values. */ /*===============================================*/ - InitializeAtomTables(theEnvironment,symbolTable,floatTable,integerTable,bitmapTable); + InitializeAtomTables(theEnvironment,symbolTable,floatTable,integerTable,bitmapTable,externalAddressTable); /*=========================================*/ /* Initialize file and string I/O routers. */ @@ -613,10 +613,6 @@ globle void RerouteStdin( case LOAD_SWITCH: EnvPrintRouter(theEnv,WERROR,"-l"); - break; - - default: - break; } EnvPrintRouter(theEnv,WERROR," option\n"); @@ -637,9 +633,6 @@ globle void RerouteStdin( case LOAD_SWITCH: EnvLoad(theEnv,argv[++i]); break; - - default: - break; #endif } } @@ -655,7 +648,7 @@ static void SystemFunctionDefinitions( ProceduralFunctionDefinitions(theEnv); MiscFunctionDefinitions(theEnv); -#if BASIC_IO || EXT_IO +#if IO_FUNCTIONS IOFunctionDefinitions(theEnv); #endif @@ -676,18 +669,14 @@ static void SystemFunctionDefinitions( StringFunctionDefinitions(theEnv); #endif -#if EX_MATH +#if EXTENDED_MATH_FUNCTIONS ExtendedMathFunctionDefinitions(theEnv); #endif -#if TEXTPRO_FUNCTIONS || HELP_FUNCTIONS +#if TEXTPRO_FUNCTIONS HelpFunctionDefinitions(theEnv); #endif -#if EMACS_EDITOR - EditorFunctionDefinition(theEnv); -#endif - #if CONSTRUCT_COMPILER && (! RUN_TIME) ConstructsToCCommandDefinition(theEnv); #endif @@ -706,29 +695,33 @@ static void SystemFunctionDefinitions( /*********************************************************/ globle double gentime() { -#if MAC +#if MAC_XCD UnsignedWide result; Microseconds(&result); return(((((double) result.hi) * kTwoPower32) + result.lo) / 1000000.0); -#elif IBM_MCW - unsigned long int result; - - result = GetTickCount(); - - return((double) result / 1000.0); - -#elif IBM_TBC && (! WINDOW_INTERFACE) - unsigned long int result; - - result = biostime(0,(long int) 0); +#elif UNIX_V || DARWIN +#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) + struct timespec now; + clock_gettime( - return((double) result / 18.2); +#if defined(_POSIX_MONOTONIC_CLOCK) + CLOCK_MONOTONIC, +#else + CLOCK_REALTIME, +#endif + &now); + return (now.tv_nsec / 1000000000.0) + now.tv_sec; +#else + struct timeval now; + gettimeofday(&now, 0); + return (now.tv_usec / 1000000.0) + now.tv_sec; +#endif -#elif UNIX_V -#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) +#elif LINUX +#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) && defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 199309L) struct timespec now; clock_gettime( @@ -745,6 +738,11 @@ globle double gentime() return (now.tv_usec / 1000000.0) + now.tv_sec; #endif +#elif UNIX_7 + struct timeval now; + gettimeofday(&now, 0); + return (now.tv_usec / 1000000.0) + now.tv_sec; + #else return((double) clock() / (double) CLOCKS_PER_SEC); #endif @@ -758,11 +756,11 @@ globle void gensystem( void *theEnv) { char *commandBuffer = NULL; - int bufferPosition = 0; - unsigned bufferMaximum = 0; + size_t bufferPosition = 0; + size_t bufferMaximum = 0; int numa, i; DATA_OBJECT tempValue; - char *theString; + const char *theString; /*===========================================*/ /* Check for the corret number of arguments. */ @@ -806,7 +804,7 @@ globle void gensystem( if (SystemDependentData(theEnv)->RedrawScreenFunction != NULL) (*SystemDependentData(theEnv)->RedrawScreenFunction)(theEnv); #endif -#if UNIX_7 || UNIX_V || IBM_MSC || IBM_TBC || IBM_ICB || IBM_ZTC || IBM_SC || IBM_MCW || IBM_GCC || MAC_XCD +#if UNIX_7 || UNIX_V || LINUX || DARWIN || WIN_MVC || WIN_GCC || MAC_XCD if (SystemDependentData(theEnv)->PauseEnvFunction != NULL) (*SystemDependentData(theEnv)->PauseEnvFunction)(theEnv); system(commandBuffer); if (SystemDependentData(theEnv)->ContinueEnvFunction != NULL) (*SystemDependentData(theEnv)->ContinueEnvFunction)(theEnv,1); @@ -849,52 +847,133 @@ globle void VMSSystem( #endif +/*******************************************/ +/* gengetchar: Generic routine for getting */ +/* a character from stdin. */ +/*******************************************/ +globle int gengetchar( + void *theEnv) + { +/* +#if WIN_MVC + if (SystemDependentData(theEnv)->getcLength == + SystemDependentData(theEnv)->getcPosition) + { + TCHAR tBuffer = 0; + DWORD count = 0; + WCHAR wBuffer = 0; + + ReadConsole(GetStdHandle(STD_INPUT_HANDLE),&tBuffer,1,&count,NULL); + + wBuffer = tBuffer; + + SystemDependentData(theEnv)->getcLength = + WideCharToMultiByte(CP_UTF8,0,&wBuffer,1, + (char *) SystemDependentData(theEnv)->getcBuffer, + 7,NULL,NULL); + + SystemDependentData(theEnv)->getcPosition = 0; + } + + return SystemDependentData(theEnv)->getcBuffer[SystemDependentData(theEnv)->getcPosition++]; +#else +*/ + return(getc(stdin)); +/* +#endif +*/ + } + +/***********************************************/ +/* genungetchar: Generic routine for ungetting */ +/* a character from stdin. */ +/***********************************************/ +globle int genungetchar( + void *theEnv, + int theChar) + { + /* +#if WIN_MVC + if (SystemDependentData(theEnv)->getcPosition > 0) + { + SystemDependentData(theEnv)->getcPosition--; + return theChar; + } + else + { return EOF; } +#else +*/ + return(ungetc(theChar,stdin)); +/* +#endif +*/ + } + +/****************************************************/ +/* genprintfile: Generic routine for print a single */ +/* character string to a file (including stdout). */ +/****************************************************/ +globle void genprintfile( + void *theEnv, + FILE *fptr, + const char *str) + { + if (fptr != stdout) + { + fprintf(fptr,"%s",str); + fflush(fptr); + } + else + { +#if WIN_MVC +/* + int rv; + wchar_t *wbuffer; + size_t len = strlen(str); + + wbuffer = genalloc(theEnv,sizeof(wchar_t) * (len + 1)); + rv = MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,-1,wbuffer,len+1); + + fwprintf(fptr,L"%ls",wbuffer); + fflush(fptr); + genfree(theEnv,wbuffer,sizeof(wchar_t) * (len + 1)); +*/ + fprintf(fptr,"%s",str); + fflush(fptr); +#else + fprintf(fptr,"%s",str); + fflush(fptr); +#endif + } + } + /***********************************************************/ /* InitializeNonportableFeatures: Initializes non-portable */ /* features. Currently, the only non-portable feature */ /* requiring initialization is the interrupt handler */ /* which allows execution to be halted. */ /***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void InitializeNonportableFeatures( void *theEnv) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #if ! WINDOW_INTERFACE -#if MAC - AddPeriodicFunction("systemtask",CallSystemTask,0); -#endif - -#if VAX_VMS || UNIX_V || UNIX_7 || IBM_GCC +#if VAX_VMS || UNIX_V || LINUX || DARWIN || UNIX_7 || WIN_GCC || WIN_MVC signal(SIGINT,CatchCtrlC); #endif -#if IBM_TBC - SystemDependentData(theEnv)->OldCtrlC = getvect(0x23); - SystemDependentData(theEnv)->OldBreak = getvect(0x1b); - setvect(0x23,CatchCtrlC); - setvect(0x1b,CatchCtrlC); - atexit(RestoreInterruptVectors); -#endif - -#if IBM_MSC || IBM_ICB +/* +#if WIN_MVC SystemDependentData(theEnv)->OldCtrlC = _dos_getvect(0x23); SystemDependentData(theEnv)->OldBreak = _dos_getvect(0x1b); _dos_setvect(0x23,CatchCtrlC); _dos_setvect(0x1b,CatchCtrlC); atexit(RestoreInterruptVectors); #endif - -#if IBM_ZTC || IBM_SC - _controlc_handler = CatchCtrlC; - controlc_open(); -#endif - +*/ #endif } @@ -909,23 +988,7 @@ static void InitializeNonportableFeatures( #if ! WINDOW_INTERFACE -#if MAC -/************************************************************/ -/* CallSystemTask: Macintosh specific function which allows */ -/* periodic tasks to be handled by the operating system. */ -/************************************************************/ -static void CallSystemTask() - { - static unsigned long int lastCall; - - if (TickCount() < (lastCall + 10)) return; - SystemTask(); - lastCall = TickCount(); - return; - } -#endif - -#if VAX_VMS || UNIX_V || UNIX_7 || IBM_GCC +#if VAX_VMS || UNIX_V || LINUX || DARWIN || UNIX_7 || WIN_GCC || WIN_MVC || DARWIN /**********************************************/ /* CatchCtrlC: VMS and UNIX specific function */ /* to allow control-c interrupts. */ @@ -941,11 +1004,12 @@ static void CatchCtrlC( } #endif -#if IBM_TBC || IBM_MSC +#if WIN_MVC /******************************************************/ /* CatchCtrlC: IBM Microsoft C and Borland Turbo C */ /* specific function to allow control-c interrupts. */ /******************************************************/ +/* static void interrupt CatchCtrlC() { #if ALLOW_ENVIRONMENT_GLOBALS @@ -953,11 +1017,12 @@ static void interrupt CatchCtrlC() CloseAllBatchSources(GetCurrentEnvironment()); #endif } - +*/ /**************************************************************/ /* RestoreInterruptVectors: IBM Microsoft C and Borland Turbo */ /* C specific function for restoring interrupt vectors. */ /**************************************************************/ +/* static void RestoreInterruptVectors() { #if ALLOW_ENVIRONMENT_GLOBALS @@ -965,74 +1030,98 @@ static void RestoreInterruptVectors() theEnv = GetCurrentEnvironment(); -#if IBM_TBC - setvect(0x23,SystemDependentData(theEnv)->OldCtrlC); - setvect(0x1b,SystemDependentData(theEnv)->OldBreak); -#else _dos_setvect(0x23,SystemDependentData(theEnv)->OldCtrlC); _dos_setvect(0x1b,SystemDependentData(theEnv)->OldBreak); #endif -#endif } +*/ #endif -#if IBM_ZTC || IBM_SC -/***********************************************/ -/* CatchCtrlC: IBM Zortech C specific function */ -/* to allow control-c interrupts. */ -/***********************************************/ -static void _cdecl CatchCtrlC() - { -#if ALLOW_ENVIRONMENT_GLOBALS - SetHaltExecution(GetCurrentEnvironment(),TRUE); - CloseAllBatchSources(GetCurrentEnvironment()); -#endif - } #endif -#if IBM_ICB -/*************************************************/ -/* CatchCtrlC: IBM Intel C Code Builder specific */ -/* function to allow control-c interrupts. */ -/*************************************************/ -static void CatchCtrlC() +/**************************************/ +/* genexit: A generic exit function. */ +/**************************************/ +globle void genexit( + void *theEnv, + int num) { -#if ALLOW_ENVIRONMENT_GLOBALS - _XSTACK *sf; /* Real-mode interrupt handler stack frame. */ + if (SystemDependentData(theEnv)->jmpBuffer != NULL) + { longjmp(*SystemDependentData(theEnv)->jmpBuffer,1); } - sf = (_XSTACK *) _get_stk_frame(); /* Get pointer to V86 _XSTACK frame. */ - SetHaltExecution(GetCurrentEnvironment(),TRUE); /* Terminate execution and */ - CloseAllBatchSources(GetCurrentEnvironment()); /* return to the command prompt. */ - sf->opts |= _STK_NOINT; /* Set _ST_NOINT to prevent V86 call. */ -#endif + exit(num); } -/********************************************************/ -/* RestoreInterruptVectors: IBM Intel C Code Builder */ -/* specific function for restoring interrupt vectors. */ -/********************************************************/ -static void RestoreInterruptVectors() +/**************************************/ +/* SetJmpBuffer: */ +/**************************************/ +globle void SetJmpBuffer( + void *theEnv, + jmp_buf *theJmpBuffer) { -#if ALLOW_ENVIRONMENT_GLOBALS - void *theEnv; + SystemDependentData(theEnv)->jmpBuffer = theJmpBuffer; + } - theEnv = GetCurrentEnvironment(); +/******************************************/ +/* genstrcpy: Generic genstrcpy function. */ +/******************************************/ +char *genstrcpy( + char *dest, + const char *src) + { + return strcpy(dest,src); + } - _dos_setvect(0x23,SystemDependentData(theEnv)->OldCtrlC); - _dos_setvect(0x1b,SystemDependentData(theEnv)->OldBreak); -#endif +/********************************************/ +/* genstrncpy: Generic genstrncpy function. */ +/********************************************/ +char *genstrncpy( + char *dest, + const char *src, + size_t n) + { + return strncpy(dest,src,n); } -#endif -#endif +/******************************************/ +/* genstrcat: Generic genstrcat function. */ +/******************************************/ +char *genstrcat( + char *dest, + const char *src) + { + return strcat(dest,src); + } -/**************************************/ -/* GENEXIT: A generic exit function. */ -/**************************************/ -globle void genexit( - int num) +/********************************************/ +/* genstrncat: Generic genstrncat function. */ +/********************************************/ +char *genstrncat( + char *dest, + const char *src, + size_t n) { - exit(num); + return strncat(dest,src,n); + } + +/*****************************************/ +/* gensprintf: Generic sprintf function. */ +/*****************************************/ +int gensprintf( + char *buffer, + const char *restrictStr, + ...) + { + va_list args; + int rv; + + va_start(args,restrictStr); + + rv = vsprintf(buffer,restrictStr,args); + + va_end(args); + + return rv; } /******************************************************/ @@ -1056,14 +1145,11 @@ globle void genseed( /* gengetcwd: Generic function for returning */ /* the current directory. */ /*********************************************/ -#if IBM_TBC -#pragma argsused -#endif globle char *gengetcwd( char *buffer, int buflength) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD return(getcwd(buffer,buflength)); #endif @@ -1076,7 +1162,7 @@ globle char *gengetcwd( /* genremove: Generic function for removing a file. */ /****************************************************/ globle int genremove( - char *fileName) + const char *fileName) { if (remove(fileName)) return(FALSE); @@ -1087,8 +1173,8 @@ globle int genremove( /* genrename: Generic function for renaming a file. */ /****************************************************/ globle int genrename( - char *oldFileName, - char *newFileName) + const char *oldFileName, + const char *newFileName) { if (rename(oldFileName,newFileName)) return(FALSE); @@ -1128,22 +1214,69 @@ globle int (*EnvSetAfterOpenFunction(void *theEnv, /*********************************************/ globle FILE *GenOpen( void *theEnv, - char *fileName, - char *accessType) + const char *fileName, + const char *accessType) { FILE *theFile; - if (strlen(fileName) > FILENAME_MAX) - { return(NULL); } + /*==================================*/ + /* Invoke the before open function. */ + /*==================================*/ if (SystemDependentData(theEnv)->BeforeOpenFunction != NULL) { (*SystemDependentData(theEnv)->BeforeOpenFunction)(theEnv); } + /*================*/ + /* Open the file. */ + /*================*/ + +#if WIN_MVC +#if _MSC_VER >= 1400 + fopen_s(&theFile,fileName,accessType); +#else + theFile = fopen(fileName,accessType); +#endif +#else theFile = fopen(fileName,accessType); +#endif + + /*=====================================*/ + /* Check for a UTF-8 Byte Order Marker */ + /* (BOM): 0xEF,0xBB,0xBF. */ + /*=====================================*/ + + if ((theFile != NULL) & (strcmp(accessType,"r") == 0)) + { + int theChar; + + theChar = getc(theFile); + if (theChar == 0xEF) + { + theChar = getc(theFile); + if (theChar == 0xBB) + { + theChar = getc(theFile); + if (theChar != 0xBF) + { ungetc(theChar,theFile);} + } + else + { ungetc(theChar,theFile);} + } + else + { ungetc(theChar,theFile); } + } + + /*=================================*/ + /* Invoke the after open function. */ + /*=================================*/ if (SystemDependentData(theEnv)->AfterOpenFunction != NULL) { (*SystemDependentData(theEnv)->AfterOpenFunction)(theEnv); } + /*===============================*/ + /* Return a pointer to the file. */ + /*===============================*/ + return theFile; } @@ -1175,15 +1308,15 @@ globle int GenClose( /************************************************************/ globle int GenOpenReadBinary( void *theEnv, - char *funcName, - char *fileName) + const char *funcName, + const char *fileName) { if (SystemDependentData(theEnv)->BeforeOpenFunction != NULL) { (*SystemDependentData(theEnv)->BeforeOpenFunction)(theEnv); } -#if IBM_TBC || IBM_MSC || IBM_ICB +#if WIN_MVC - SystemDependentData(theEnv)->BinaryFileHandle = open(fileName,O_RDONLY | O_BINARY); + SystemDependentData(theEnv)->BinaryFileHandle = _open(fileName,O_RDONLY | O_BINARY); if (SystemDependentData(theEnv)->BinaryFileHandle == -1) { if (SystemDependentData(theEnv)->AfterOpenFunction != NULL) @@ -1193,7 +1326,7 @@ globle int GenOpenReadBinary( } #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) +#if (! WIN_MVC) if ((SystemDependentData(theEnv)->BinaryFP = fopen(fileName,"rb")) == NULL) { @@ -1217,53 +1350,25 @@ globle int GenOpenReadBinary( globle void GenReadBinary( void *theEnv, void *dataPtr, - unsigned long size) + size_t size) { -/* -#if MAC - long dataSize; - - dataSize = (long) size; - FSRead(SystemDependentData(theEnv)->BinaryRefNum,&dataSize,dataPtr); -#endif -*/ -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW */ +#if WIN_MVC char *tempPtr; tempPtr = (char *) dataPtr; while (size > INT_MAX) { - read(SystemDependentData(theEnv)->BinaryFileHandle,tempPtr,INT_MAX); + _read(SystemDependentData(theEnv)->BinaryFileHandle,tempPtr,INT_MAX); size -= INT_MAX; tempPtr = tempPtr + INT_MAX; } if (size > 0) - { read(SystemDependentData(theEnv)->BinaryFileHandle,tempPtr,(STD_SIZE) size); } + { _read(SystemDependentData(theEnv)->BinaryFileHandle,tempPtr,(unsigned int) size); } #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) && (! IBM_ZTC) */ - unsigned int temp, number_of_reads, read_size; - - if (sizeof(int) == sizeof(long)) - { read_size = size; } - else -// { read_size = (1L << (sizeof(int) * 8L)) - 1L ; } - { read_size = (1ULL << (sizeof(int) * 8L)) - 1L ; } - - number_of_reads = size / read_size; - temp = size - ((long) number_of_reads * (long) read_size); - - while (number_of_reads > 0) - { -// fread(dataPtr,(STD_SIZE) read_size,1,SystemDependentData(theEnv)->BinaryFP); - if (fread(dataPtr,(STD_SIZE) read_size,1,SystemDependentData(theEnv)->BinaryFP)){}; - dataPtr = ((char *) dataPtr) + read_size; - number_of_reads--; - } - -// fread(dataPtr,(STD_SIZE) temp,1,SystemDependentData(theEnv)->BinaryFP); - if (fread(dataPtr,(STD_SIZE) temp,1,SystemDependentData(theEnv)->BinaryFP)){} +#if (! WIN_MVC) + fread(dataPtr,size,1,SystemDependentData(theEnv)->BinaryFP); #endif } @@ -1275,16 +1380,11 @@ globle void GetSeekCurBinary( void *theEnv, long offset) { -/* -#if MAC - SetFPos(SystemDependentData(theEnv)->BinaryRefNum,fsFromMark,offset); -#endif -*/ -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW || IBM_ZTC */ - lseek(SystemDependentData(theEnv)->BinaryFileHandle,offset,SEEK_CUR); +#if WIN_MVC + _lseek(SystemDependentData(theEnv)->BinaryFileHandle,offset,SEEK_CUR); #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) && (! IBM_ZTC) */ +#if (! WIN_MVC) fseek(SystemDependentData(theEnv)->BinaryFP,offset,SEEK_CUR); #endif } @@ -1297,16 +1397,11 @@ globle void GetSeekSetBinary( void *theEnv, long offset) { -/* -#if MAC - SetFPos(SystemDependentData(theEnv)->BinaryRefNum,fsFromStart,offset); -#endif -*/ -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW || IBM_ZTC */ - lseek(SystemDependentData(theEnv)->BinaryFileHandle,offset,SEEK_SET); +#if WIN_MVC + _lseek(SystemDependentData(theEnv)->BinaryFileHandle,offset,SEEK_SET); #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) && (! IBM_ZTC) */ +#if (! WIN_MVC) fseek(SystemDependentData(theEnv)->BinaryFP,offset,SEEK_SET); #endif } @@ -1319,16 +1414,11 @@ globle void GenTellBinary( void *theEnv, long *offset) { -/* -#if MAC - GetFPos(SystemDependentData(theEnv)->BinaryRefNum,offset); -#endif -*/ -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW || IBM_ZTC */ - *offset = lseek(SystemDependentData(theEnv)->BinaryFileHandle,0,SEEK_CUR); +#if WIN_MVC + *offset = _lseek(SystemDependentData(theEnv)->BinaryFileHandle,0,SEEK_CUR); #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) && (! IBM_ZTC) */ +#if (! WIN_MVC) *offset = ftell(SystemDependentData(theEnv)->BinaryFP); #endif } @@ -1340,20 +1430,14 @@ globle void GenTellBinary( globle void GenCloseBinary( void *theEnv) { -/* -#if MAC - FSClose(SystemDependentData(theEnv)->BinaryRefNum); -#endif -*/ - if (SystemDependentData(theEnv)->BeforeOpenFunction != NULL) { (*SystemDependentData(theEnv)->BeforeOpenFunction)(theEnv); } -#if IBM_TBC || IBM_MSC || IBM_ICB /* || IBM_MCW */ - close(SystemDependentData(theEnv)->BinaryFileHandle); +#if WIN_MVC + _close(SystemDependentData(theEnv)->BinaryFileHandle); #endif -#if (! IBM_TBC) && (! IBM_MSC) && (! IBM_ICB) /* && (! IBM_MCW) */ +#if (! WIN_MVC) fclose(SystemDependentData(theEnv)->BinaryFP); #endif @@ -1367,14 +1451,14 @@ globle void GenCloseBinary( /***********************************************/ globle void GenWrite( void *dataPtr, - unsigned long size, + size_t size, FILE *fp) { if (size == 0) return; #if UNIX_7 - fwrite(dataPtr,(STD_SIZE) size,1,fp); + fwrite(dataPtr,size,1,fp); #else - fwrite(dataPtr,(STD_SIZE) size,1,fp); + fwrite(dataPtr,size,1,fp); #endif } @@ -1612,10 +1696,8 @@ static void InitializeKeywords( ts = EnvAddSymbol(theEnv,"focus"); IncrementSymbolCount(ts); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif } - - diff --git a/src/sysdep.h b/src/sysdep.h index 0294601..fef4c9a 100644 --- a/src/sysdep.h +++ b/src/sysdep.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/04/15 */ /* */ /* SYSTEM DEPENDENT HEADER FILE */ /*******************************************************/ @@ -16,15 +16,64 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Modified GenOpen to check the file length */ +/* against the system constant FILENAME_MAX. */ +/* */ /* 6.24: Support for run-time programs directly passing */ /* the hash tables for initialization. */ /* */ +/* Made gensystem functional for Xcode. */ +/* */ /* Added BeforeOpenFunction and AfterOpenFunction */ /* hooks. */ /* */ /* Added environment parameter to GenClose. */ /* Added environment parameter to GenOpen. */ /* */ +/* Updated UNIX_V gentime functionality. */ +/* */ +/* Removed GenOpen check against FILENAME_MAX. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, IBM_ICB, IBM_TBC, IBM_ZTC, and */ +/* IBM_SC). */ +/* */ +/* Renamed IBM_MSC and WIN_MVC compiler flags */ +/* and IBM_GCC to WIN_GCC. */ +/* */ +/* Added LINUX and DARWIN compiler flags. */ +/* */ +/* Removed HELP_FUNCTIONS compilation flag and */ +/* associated functionality. */ +/* */ +/* Removed EMACS_EDITOR compilation flag and */ +/* associated functionality. */ +/* */ +/* Combined BASIC_IO and EXT_IO compilation */ +/* flags into the single IO_FUNCTIONS flag. */ +/* */ +/* Changed the EX_MATH compilation flag to */ +/* EXTENDED_MATH_FUNCTIONS. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* GenOpen function checks for UTF-8 Byte Order */ +/* Marker. */ +/* */ +/* Added gengetchar, genungetchar, genprintfile, */ +/* genstrcpy, genstrncpy, genstrcat, genstrncat, */ +/* and gensprintf functions. */ +/* */ +/* Added SetJmpBuffer function. */ +/* */ +/* Added environment argument to genexit. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_sysdep @@ -39,7 +88,9 @@ #include <stdio.h> #endif -#if IBM_TBC || IBM_MSC || IBM_ICB +#include <setjmp.h> + +#if WIN_MVC #include <dos.h> #endif @@ -53,9 +104,12 @@ #define LOCALE extern #endif +#if ALLOW_ENVIRONMENT_GLOBALS LOCALE void InitializeEnvironment(void); +#endif LOCALE void EnvInitializeEnvironment(void *,struct symbolHashNode **,struct floatHashNode **, - struct integerHashNode **,struct bitMapHashNode **); + struct integerHashNode **,struct bitMapHashNode **, + struct externalAddressHashNode **); LOCALE void SetRedrawFunction(void *,void (*)(void *)); LOCALE void SetPauseEnvFunction(void *,void (*)(void *)); LOCALE void SetContinueEnvFunction(void *,void (*)(void *,int)); @@ -66,25 +120,34 @@ LOCALE double gentime(void); LOCALE void gensystem(void *theEnv); LOCALE void VMSSystem(char *); - LOCALE int GenOpenReadBinary(void *,char *,char *); + LOCALE int GenOpenReadBinary(void *,const char *,const char *); LOCALE void GetSeekCurBinary(void *,long); LOCALE void GetSeekSetBinary(void *,long); LOCALE void GenTellBinary(void *,long *); LOCALE void GenCloseBinary(void *); - LOCALE void GenReadBinary(void *,void *,unsigned long); - LOCALE FILE *GenOpen(void *,char *,char *); + LOCALE void GenReadBinary(void *,void *,size_t); + LOCALE FILE *GenOpen(void *,const char *,const char *); LOCALE int GenClose(void *,FILE *); - LOCALE void genexit(int); + LOCALE void genexit(void *,int); LOCALE int genrand(void); LOCALE void genseed(int); - LOCALE int genremove(char *); - LOCALE int genrename(char *,char *); + LOCALE int genremove(const char *); + LOCALE int genrename(const char *,const char *); LOCALE char *gengetcwd(char *,int); - LOCALE void GenWrite(void *,unsigned long,FILE *); + LOCALE void GenWrite(void *,size_t,FILE *); LOCALE int (*EnvSetBeforeOpenFunction(void *,int (*)(void *)))(void *); LOCALE int (*EnvSetAfterOpenFunction(void *,int (*)(void *)))(void *); + LOCALE int gensprintf(char *,const char *,...); + LOCALE char *genstrcpy(char *,const char *); + LOCALE char *genstrncpy(char *,const char *,size_t); + LOCALE char *genstrcat(char *,const char *); + LOCALE char *genstrncat(char *,const char *,size_t); + LOCALE void SetJmpBuffer(void *,jmp_buf *); + LOCALE void genprintfile(void *,FILE *,const char *); + LOCALE int gengetchar(void *); + LOCALE int genungetchar(void *,int); -#endif +#endif /* _H_sysdep */ diff --git a/src/textpro.c b/src/textpro.c index 1ca8cbe..49116d3 100644 --- a/src/textpro.c +++ b/src/textpro.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/26/15 */ /* */ /* TEXT PROCESSING MODULE */ /*******************************************************/ @@ -10,12 +10,13 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* Gary D. Riley */ /* */ /* Revision History: */ +/* */ /* 6.23: Modified error messages so that they were */ /* directly printed rather than storing them in */ /* a string buffer which might not be large */ @@ -27,6 +28,25 @@ /* Added environment parameter to GenClose. */ /* Added environment parameter to GenOpen. */ /* */ +/* 6.30: Removed HELP_FUNCTIONS compilation flag and */ +/* associated functionality. */ +/* */ +/* Used genstrcpy and genstrncpy instead of */ +/* strcpy and strncpy. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Added STDOUT and STDIN logical name */ +/* definitions. */ +/* */ /*************************************************************/ @@ -60,7 +80,7 @@ #include "textpro.h" -#if TEXTPRO_FUNCTIONS || HELP_FUNCTIONS +#if TEXTPRO_FUNCTIONS #define NAMESIZE 80 #define NULLCHAR '\0' @@ -122,39 +142,30 @@ struct lists #define BFORMAT "%d%1s%12s%s" /*Format string for sscanf*/ #define LIT_DELIM ('$') -#if IBM_TBC -#define OPEN_READ "rb" -#else #define OPEN_READ "r" -#endif - #define TEXTPRO_DATA 8 struct textProcessingData - { + { struct lists *headings; struct entries *parent; -#if HELP_FUNCTIONS - int HELP_INIT; - char *help_file; -#endif }; #define TextProcessingData(theEnv) ((struct textProcessingData *) GetEnvironmentData(theEnv,TEXTPRO_DATA)) -int TextLookupFetch(void *,char *); -int TextLookupToss(void *,char *); -static FILE *GetEntries(void *,char *,char **,char *,int *); -static FILE *GetCurrentMenu(void *,char *,int *); +int TextLookupFetch(void *,const char *); +int TextLookupToss(void *,const char *); +static FILE *GetEntries(void *,const char *,char **,char *,int *); +static FILE *GetCurrentMenu(void *,const char *,int *); static char *grab_string(void *,FILE *,char *,int); -static int findstr(char *,char *); +static int findstr(const char *,const char *); static void upper(char *); -static struct lists *NewFetchFile(void *,char *); -static struct entries *AllocateEntryNode(void *,FILE *,char *,char *,int); -static int AttachLeaf(void *,struct lists *,struct entries *,FILE *,char *,int); -static long LookupEntry(void *,char *,char **,char *,int *); +static struct lists *NewFetchFile(void *,const char *); +static struct entries *AllocateEntryNode(void *,FILE *,const char *,const char *,int); +static int AttachLeaf(void *,struct lists *,struct entries *,FILE *,const char *,int); +static long LookupEntry(void *,const char *,char **,char *,int *); static void TossFunction(void *,struct entries *); static void DeallocateTextProcessingData(void *); @@ -187,7 +198,7 @@ static void DeallocateTextProcessingData(void *); /****************************************************************************/ globle int TextLookupFetch( void *theEnv, - char *file) + const char *file) { FILE *fp; /*Pointer into stream of input file */ char str[256]; /*Buffer for storing input file lines */ @@ -207,7 +218,7 @@ globle int TextLookupFetch( EnvPrintRouter(theEnv,WERROR,"\".\n"); return(-1); } - + if ((lnode = NewFetchFile(theEnv,file)) == NULL) { GenClose(theEnv,fp); @@ -234,7 +245,7 @@ globle int TextLookupFetch( /*=============================================================*/ /*Forces the load function to ignore lines beginning with `$$' */ /*=============================================================*/ - + if ((str[0] != LIT_DELIM) || (str[1] != LIT_DELIM)) { if (findstr(str,EDELIM) >= 0) @@ -291,12 +302,12 @@ globle int TextLookupFetch( if (INFO_END == FALSE) { TextLookupToss(theEnv,file); - + PrintErrorID(theEnv,"TEXTPRO",4,FALSE); EnvPrintRouter(theEnv,WERROR,"Line "); PrintLongInteger(theEnv,WERROR,line_ct); EnvPrintRouter(theEnv,WERROR," : Previous entry not closed.\n"); - + return(-1); } if (entries_ct == 0) @@ -313,7 +324,7 @@ globle int TextLookupFetch( /******************************************************************************/ globle int TextLookupToss( void *theEnv, - char *file) + const char *file) { struct lists *plptr, *clptr; int l_flag; @@ -367,7 +378,7 @@ globle int TextLookupToss( /******************************************************************************/ static FILE *GetEntries( void *theEnv, - char *file, + const char *file, char **menu, char *name, int *code) @@ -405,7 +416,7 @@ static FILE *GetEntries( /******************************************************************************/ static FILE *GetCurrentMenu( void *theEnv, - char *file, + const char *file, int *status) { struct lists *lptr; /*Used in searching the file list*/ @@ -511,8 +522,8 @@ static char *grab_string( /* 2) returns -1, if not found */ /**************************************************************************/ static int findstr( - char *s, - char *t) + const char *s, + const char *t) { int i,j,k; @@ -548,7 +559,7 @@ static void upper( /******************************************************************************/ static struct lists *NewFetchFile( void *theEnv, - char *file) + const char *file) { struct lists *lptr = NULL, *lnode; @@ -565,7 +576,7 @@ static struct lists *NewFetchFile( return(NULL); } lnode = (struct lists *) gm2(theEnv,(int) sizeof(struct lists)); - strcpy(lnode->file,file); + genstrcpy(lnode->file,file); lnode->topics = NULL; lnode->curr_menu = NULL; lnode->next = NULL; @@ -596,8 +607,8 @@ static struct lists *NewFetchFile( static struct entries *AllocateEntryNode( void *theEnv, FILE *fp, - char *file, - char *str, + const char *file, + const char *str, int line_ct) { struct entries *enode; @@ -692,7 +703,7 @@ static int AttachLeaf( struct lists *lnode, struct entries *enode, FILE *fp, - char *file, + const char *file, int line_ct) { int p_flag; /*Used in searching the tree for a parent*/ @@ -813,7 +824,7 @@ static int AttachLeaf( /******************************************************************************/ static long int LookupEntry( void *theEnv, - char *file, + const char *file, char **menu, char *name, int *code) @@ -992,16 +1003,8 @@ struct topics /*============================================================================*/ /******************************************************************************/ -#if HELP_FUNCTIONS -static int RecognizeHelpRouters(void *,char *); -static int HelpPrint(void *,char *,char *); -static int HelpGetc(void *,char *); -static int HelpUngetc(void *,int,char *); -static struct topics *AskForNewHelpTopic(void *,struct topics *,char **); -#endif - static struct topics *GetCommandLineTopics(void *); -static FILE *FindTopicInEntries(void *,char *,struct topics *,char **,int *); +static FILE *FindTopicInEntries(void *,const char *,struct topics *,char **,int *); /******************************************************************************/ /*============================================================================*/ @@ -1009,237 +1012,6 @@ static FILE *FindTopicInEntries(void *,char *,struct topics *,char **,int *); /*============================================================================*/ /******************************************************************************/ -/******************************************************************************/ -/*FUNCTION HelpFunction : (H/L function help) */ -/* Input : Multiple or no topic requests may be passed to the help facility */ -/* from the top level via a "stack" accessed by the */ -/* system routines num_args() and rstring(). */ -/* Output : This function loads the help file specified in setup.h into a */ -/* a hierarchical tree structure using the routines of LOOKUP.C. */ -/* It then queries the user for topics, and, using the LOOKUP */ -/* routines, branches through the tree, displaying information where */ -/* appropriate. The function returns control once the user */ -/* has indicated an exit from the help tree. */ -/* */ -/* For usage see external documentation. */ -/******************************************************************************/ - -#if HELP_FUNCTIONS - -globle void HelpFunction( - void *theEnv) - { - int status; /*Return code from the lookup routines */ - FILE *fp; /*Pointer in to the help file stream */ - struct topics *main_topic, /*Pointer to the first requested topic */ - *tptr; /*Used in deallocating the topic list */ - char buf[256], /*Buffer for storing input strings from the help file */ - *menu[1]; /*Buffer for the name of the current main topic */ -#if ! WINDOW_INTERFACE - char termbuf[2]; /*Buffer for storing the terminators of a scroll */ - int line_cnt; /*Line count used for scrolling purposes */ -#endif - - if (TextProcessingData(theEnv)->HELP_INIT == FALSE) - { - if (TextProcessingData(theEnv)->help_file == NULL) - { - TextProcessingData(theEnv)->help_file = (char *) gm2(theEnv,strlen(HELP_DEFAULT) + 1); - strcpy(TextProcessingData(theEnv)->help_file,HELP_DEFAULT); - } - EnvPrintRouter(theEnv,WDIALOG,"Loading help file entries from "); - EnvPrintRouter(theEnv,WDIALOG,TextProcessingData(theEnv)->help_file); - EnvPrintRouter(theEnv,WDIALOG,".\nPlease wait...\n"); - status = TextLookupFetch(theEnv,TextProcessingData(theEnv)->help_file); - if (status <= 0) - { - return; - } - else - { - /* ================================================================ - Enables logical name "whelp" as the destination for all help I/O - ================================================================ */ - EnvAddRouter(theEnv,"whelp",10,RecognizeHelpRouters,HelpPrint, - HelpGetc,HelpUngetc,NULL); - TextProcessingData(theEnv)->HELP_INIT = TRUE; - } - } - - EnvActivateRouter(theEnv,"whelp"); - - /* ==================================================================== - The root node of the help-tree is MAIN (see external documentation.) - Add this node to the front of the initial topic request list given - by the user on the top level command line. - ==================================================================== */ - main_topic = (struct topics *) gm2(theEnv,(int) sizeof(struct topics)); - strcpy(main_topic->name,"MAIN"); - main_topic->next = GetCommandLineTopics(theEnv); - main_topic->end_list = NULL; - - EnvPrintRouter(theEnv,"whelp","\n"); - - /*============================*/ - /*Process user topic requests */ - /*============================*/ - do - { - fp = FindTopicInEntries(theEnv,TextProcessingData(theEnv)->help_file,main_topic,menu,&status); - if (status == NO_FILE) - { - PrintErrorID(theEnv,"TEXTPRO",1,FALSE); - EnvPrintRouter(theEnv,WERROR,"Unable to access help file.\n"); - break; - } - if (status == EXIT) - break; - if (status == NO_TOPIC) - { - if (fp == NULL) - { - /*===================================================*/ - /*The lookup routines return the file location of the*/ - /*current main topic if the requested topic is not */ - /*found. The help-tree has one root: MAIN (see */ - /*external docs). This topic should always be */ - /*available. Thus, if the topic was not found and */ - /*there is no current menu, the help-file has been */ - /*tampered with and should be corrected. */ - /*===================================================*/ - EnvPrintRouter(theEnv,"whelp","Root entry \"MAIN\" not found in "); - EnvPrintRouter(theEnv,"whelp",TextProcessingData(theEnv)->help_file); - EnvPrintRouter(theEnv,"whelp",".\nSee external documentation.\n"); - break; - } - EnvPrintRouter(theEnv,"whelp","\nSorry, no information available.\n\n"); - } - if (status != BRANCH_UP) - { -#if ! WINDOW_INTERFACE - line_cnt = 0; -#endif - - /*======================================================*/ - /*Print lines from the information entry stopping after */ - /*every screenful of lines. The user at that point has */ - /*the option to continue or abort the entry to continue */ - /*at the current menu level. */ - /*======================================================*/ - while (grab_string(theEnv,fp,buf,256) != NULL) - { -#if ! WINDOW_INTERFACE - if (line_cnt >= (SCREEN_LN + 1)) - { - EnvPrintRouter(theEnv,"whelp","PRESS <RETURN> FOR MORE. "); - EnvPrintRouter(theEnv,"whelp","PRESS <A>,<RETURN> TO ABORT."); - RouterData(theEnv)->CommandBufferInputCount = 0; - do - { - termbuf[0] = (char) EnvGetcRouter(theEnv,"whelp"); - if (termbuf[0] != LNFEED) - { - if (termbuf[0] == 'a') - termbuf[0] = 'A'; - if (termbuf[0] != '\b') - RouterData(theEnv)->CommandBufferInputCount++; - else if (RouterData(theEnv)->CommandBufferInputCount != 0) - RouterData(theEnv)->CommandBufferInputCount--; - termbuf[1] = (char) EnvGetcRouter(theEnv,"whelp"); - } - } - while ((termbuf[0] != LNFEED) && - (termbuf[0] != 'A')); - RouterData(theEnv)->CommandBufferInputCount = -1; - line_cnt = 0; - if (termbuf[0] == 'A') - { - GenClose(theEnv,fp); - break; - } - } - line_cnt++; -#endif - EnvPrintRouter(theEnv,"whelp",buf); - } - } - else if (fp != NULL) - /*==========================================================*/ - /*If the user branched-up the help-tree, don't reprint that */ - /*menu. However, the help file still needs to be closed. */ - /*==========================================================*/ - GenClose(theEnv,fp); - - main_topic = AskForNewHelpTopic(theEnv,main_topic,menu); - if (EvaluationData(theEnv)->HaltExecution) - { - while (status != EXIT) - if ((fp = GetEntries(theEnv,TextProcessingData(theEnv)->help_file,menu,NULL,&status)) != NULL) - GenClose(theEnv,fp); - } - } while (status != EXIT); - EnvDeactivateRouter(theEnv,"whelp"); - - /*========================================================*/ - /*Release any space used by the user's topic request list */ - /*========================================================*/ - while (main_topic != NULL) - { - tptr = main_topic; - main_topic = main_topic->next; - rm(theEnv,(void *) tptr,(int) sizeof(struct topics)); - } - } - -/***************************************************************************/ -/*FUNCTION HelpPathFunction : (function help-path) */ -/* Input : Via the argument "stack", the name of the new help entries */ -/* file, or no input. */ -/* Output : This function redefines the lookup file for the help facility. */ -/* If no argument is given, it displays the current file name. */ -/***************************************************************************/ -globle void HelpPathFunction( - void *theEnv) - { - char *help_name; - DATA_OBJECT arg_ptr; - - if (EnvRtnArgCount(theEnv) == 0) - { - EnvPrintRouter(theEnv,WDIALOG,"The current help entries file is "); - if (TextProcessingData(theEnv)->help_file != NULL) - EnvPrintRouter(theEnv,WDIALOG,TextProcessingData(theEnv)->help_file); - else - EnvPrintRouter(theEnv,WDIALOG,HELP_DEFAULT); - EnvPrintRouter(theEnv,WDIALOG,"\n"); - } - else - { - if (TextProcessingData(theEnv)->help_file != NULL) - { - if (TextProcessingData(theEnv)->HELP_INIT == TRUE) - { - EnvPrintRouter(theEnv,WDIALOG,"Releasing help entries from file "); - EnvPrintRouter(theEnv,WDIALOG,TextProcessingData(theEnv)->help_file); - EnvPrintRouter(theEnv,WDIALOG,"...\n"); - TextLookupToss(theEnv,TextProcessingData(theEnv)->help_file); - EnvDeleteRouter(theEnv,"whelp"); - TextProcessingData(theEnv)->HELP_INIT = FALSE; - } - rm(theEnv,(void *) TextProcessingData(theEnv)->help_file,strlen(TextProcessingData(theEnv)->help_file) + 1); - } - if (EnvArgTypeCheck(theEnv,"help-path",1,SYMBOL_OR_STRING,&arg_ptr) == FALSE) return; - help_name = DOToString(arg_ptr); - TextProcessingData(theEnv)->help_file = (char *) gm2(theEnv,strlen(help_name) + 1); - strcpy(TextProcessingData(theEnv)->help_file,help_name); - EnvPrintRouter(theEnv,WDIALOG,"Help entries file reset to "); - EnvPrintRouter(theEnv,WDIALOG,help_name); - EnvPrintRouter(theEnv,WDIALOG,"\n"); - } - } - -#endif - #if TEXTPRO_FUNCTIONS /***************************************************************************/ @@ -1272,7 +1044,7 @@ globle void FetchCommand( return; } result->type = INTEGER; - result->value = (void *) EnvAddLong(theEnv,(long) load_ct); + result->value = (void *) EnvAddLong(theEnv,(long long) load_ct); } /******************************************************************************/ @@ -1308,7 +1080,7 @@ globle int PrintRegionCommand( if ((status != NO_FILE) && (status != NO_TOPIC) && (status != EXIT)) { if (strcmp(params->name,"t") == 0) - strcpy(params->name,"stdout"); + genstrcpy(params->name,STDOUT); EnvPrintRouter(theEnv,params->name,"\n"); while (grab_string(theEnv,fp,buf,256) != NULL) EnvPrintRouter(theEnv,params->name,buf); @@ -1353,9 +1125,9 @@ globle void *GetRegionCommand( int status; /*Lookup status return code */ char *theString = NULL; void *theResult; - int oldPos = 0; - unsigned oldMax = 0; - unsigned sLength; + size_t oldPos = 0; + size_t oldMax = 0; + size_t sLength; params = GetCommandLineTopics(theEnv); fp = FindTopicInEntries(theEnv,params->name,params->next,menu,&status); @@ -1415,102 +1187,19 @@ globle void *GetRegionCommand( globle int TossCommand( void *theEnv) { - char *file; /*Name of the file */ + const char *file; /*Name of the file */ DATA_OBJECT arg_ptr; if (EnvArgTypeCheck(theEnv,"toss",1,SYMBOL_OR_STRING,&arg_ptr) == FALSE) return (FALSE); file = DOToString(arg_ptr); -#if HELP_FUNCTIONS - - if (TextProcessingData(theEnv)->help_file != NULL) - if ((strcmp(file,TextProcessingData(theEnv)->help_file) == 0) && (TextProcessingData(theEnv)->HELP_INIT == TRUE)) - { - rm(theEnv,(void *) TextProcessingData(theEnv)->help_file,strlen(TextProcessingData(theEnv)->help_file) + 1); - TextProcessingData(theEnv)->help_file = NULL; - TextProcessingData(theEnv)->HELP_INIT = FALSE; - EnvDeleteRouter(theEnv,"whelp"); - } - -#endif - return(TextLookupToss(theEnv,file)); } #endif /******************************************************************************/ -/* The following four functions are the router routines for the logical name */ -/* "whelp". Currently, all they do is direct all accesses to standard I/O. */ -/******************************************************************************/ - -#if HELP_FUNCTIONS - -#if IBM_TBC -#pragma argsused -#endif -static int RecognizeHelpRouters( - void *theEnv, - char *log_name) - { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(theEnv) -#endif - - if (strcmp(log_name,"whelp") == 0) - return(TRUE); - return(FALSE); - } - -#if IBM_TBC -#pragma argsused -#endif -static int HelpPrint( - void *theEnv, - char *log_name, - char *str) - { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(log_name) -#endif - - EnvPrintRouter(theEnv,"stdout",str); - return(1); - } - -#if IBM_TBC -#pragma argsused -#endif -static int HelpGetc( - void *theEnv, - char *log_name) - { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(log_name) -#endif - - return(EnvGetcRouter(theEnv,"stdin")); - } - -#if IBM_TBC -#pragma argsused -#endif -static int HelpUngetc( - void *theEnv, - int ch, - char *log_name) - { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(log_name) -#endif - - return(EnvUngetcRouter(theEnv,ch,"stdin")); - } - -#endif - -/******************************************************************************/ /*============================================================================*/ /* INTERNAL ROUTINES */ /*============================================================================*/ @@ -1541,13 +1230,13 @@ static struct topics *GetCommandLineTopics( tnode = (struct topics *) gm2(theEnv,(int) sizeof(struct topics)); EnvRtnUnknown(theEnv,theIndex,&val); if ((GetType(val) == SYMBOL) || (GetType(val) == STRING)) - strncpy(tnode->name,DOToString(val),NAMESIZE-1); + genstrncpy(tnode->name,DOToString(val),NAMESIZE-1); else if (GetType(val) == FLOAT) - strncpy(tnode->name,FloatToString(theEnv,DOToDouble(val)),NAMESIZE-1); + genstrncpy(tnode->name,FloatToString(theEnv,DOToDouble(val)),NAMESIZE-1); else if (GetType(val) == INTEGER) - strncpy(tnode->name,LongIntegerToString(theEnv,DOToLong(val)),NAMESIZE-1); + genstrncpy(tnode->name,LongIntegerToString(theEnv,DOToLong(val)),NAMESIZE-1); else - strncpy(tnode->name,"***ERROR***",NAMESIZE-1); + genstrncpy(tnode->name,"***ERROR***",NAMESIZE-1); tnode->next = NULL; tnode->end_list = NULL; if (head == NULL) @@ -1564,120 +1253,6 @@ static struct topics *GetCommandLineTopics( } /******************************************************************************/ -/*FUNCTION QUERY_TOPIC : */ -/* Input : 1) The address of the old topic list (this routines writes over */ -/* previously allocated memory, if available) */ -/* 2) A buffer holding the name of the current menu in the tree */ -/* Output : This function prompts the user for a new set of topic(s) and */ -/* displays the name of the current menu. Each new topic is */ -/* delineated by white-space, and this function builds a linked list */ -/* of these topics. It returns the address of the top of this list. */ -/******************************************************************************/ - -#if HELP_FUNCTIONS - -static struct topics *AskForNewHelpTopic( - void *theEnv, - struct topics *old_list, - char **menu) - { - int theIndex, cnt; /*Indices of the user input buffer and topic name */ - struct topics *tmain, /*Address of the top of the topic list */ - *tnode, /*Address of the new topic node */ - *tptr; /*Used to add the new node to the topic list */ - char list[256], /*User input buffer */ - name[NAMESIZE]; /*Name of the new topic in the list */ - - /*==================================================================*/ - /*Read a line of input from the user (substituting blanks for tabs) */ - /*==================================================================*/ - EnvPrintRouter(theEnv,"whelp",*menu); - EnvPrintRouter(theEnv,"whelp"," Topic? "); - RouterData(theEnv)->CommandBufferInputCount = 0; - for ( theIndex = 0; - ((list[theIndex] = (char) EnvGetcRouter(theEnv,"whelp")) != LNFEED) && (theIndex < 254); - theIndex++ , RouterData(theEnv)->CommandBufferInputCount++) - { - if (EvaluationData(theEnv)->HaltExecution) - break; - if (list[theIndex] == TAB) - list[theIndex] = BLANK; - else if ((list[theIndex] == '\b') && (theIndex != 0)) - { - theIndex -= 2; - RouterData(theEnv)->CommandBufferInputCount -= 2; - } - } -#if VAX_VMS - EnvPrintRouter(theEnv,"whelp","\n"); -#endif - - RouterData(theEnv)->CommandBufferInputCount = -1; - if (EvaluationData(theEnv)->HaltExecution) - { - EnvPrintRouter(theEnv,"whelp","\n"); - old_list->end_list = old_list; - return(old_list); - } - list[theIndex] = BLANK; - list[theIndex+1] = NULLCHAR; - - /*=======================================*/ - /*Parse user buffer into separate topics */ - /*=======================================*/ - tmain = old_list; - theIndex = 0; cnt = 0; - while (list[theIndex] != NULLCHAR) - { - if ((list[theIndex] != BLANK) && (cnt < NAMESIZE)) - name[cnt++] = list[theIndex++]; - else if (cnt > 0) - { - while ((list[theIndex] != BLANK) && (list[theIndex] != NULLCHAR)) - theIndex++; - name[cnt] = NULLCHAR; - cnt = 0; - - /*==============================================*/ - /*Write over previous topic lists, if available */ - /*==============================================*/ - if (old_list != NULL) - { - strcpy(old_list->name,name); - old_list = old_list->next; - } - else - { - tnode = (struct topics *) gm2(theEnv,(int) sizeof(struct topics)); - strcpy(tnode->name,name); - tnode->next = NULL; - tnode->end_list = NULL; - if (tmain == NULL) - tmain = tnode; - else - { - tptr = tmain; - while (tptr->next != NULL) - tptr = tptr->next; - tptr->next = tnode; - } - } - } - else - theIndex++; - } - - /*========================================================================*/ - /*If the new list is shorter than the previous one, we must mark the end. */ - /*========================================================================*/ - tmain->end_list = old_list; - return(tmain); - } - - -#endif - -/******************************************************************************/ /*FUNCTION FIND_TOPIC : */ /* Input : 1) File to be searched for topic request */ /* 2) Address of topic request list */ @@ -1693,7 +1268,7 @@ static struct topics *AskForNewHelpTopic( /******************************************************************************/ static FILE *FindTopicInEntries( void *theEnv, - char *file, + const char *file, struct topics *main_topic, char **menu, int *status) @@ -1752,11 +1327,6 @@ globle void HelpFunctionDefinitions( { AllocateEnvironmentData(theEnv,TEXTPRO_DATA,sizeof(struct textProcessingData),DeallocateTextProcessingData); #if ! RUN_TIME -#if HELP_FUNCTIONS - EnvDefineFunction2(theEnv,"help",'v',PTIEF HelpFunction,"HelpFunction",NULL); - EnvDefineFunction2(theEnv,"help-path",'v',PTIEF HelpPathFunction,"HelpPathFunction","*1k"); -#endif - #if TEXTPRO_FUNCTIONS EnvDefineFunction2(theEnv,"fetch",'u', PTIEF FetchCommand,"FetchCommand","11k"); EnvDefineFunction2(theEnv,"toss",'b', PTIEF TossCommand,"TossCommand","11k"); @@ -1765,7 +1335,7 @@ globle void HelpFunctionDefinitions( #endif #endif } - + /*********************************************************/ /* DeallocateTextProcessingData: Deallocates environment */ /* data for text processing routines. */ @@ -1779,20 +1349,12 @@ static void DeallocateTextProcessingData( while (clptr != NULL) { nextptr = clptr->next; - + TossFunction(theEnv,clptr->topics); rm(theEnv,(void *) clptr,(int) sizeof(struct lists)); clptr = nextptr; } - -#if HELP_FUNCTIONS - if (TextProcessingData(theEnv)->help_file != NULL) - { - rm(theEnv,TextProcessingData(theEnv)->help_file, - strlen(TextProcessingData(theEnv)->help_file) + 1); - } -#endif } diff --git a/src/textpro.h b/src/textpro.h index 6f45c1e..dc47d4d 100644 --- a/src/textpro.h +++ b/src/textpro.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* TEXT PROCESSING HEADER FILE */ /*******************************************************/ @@ -10,14 +10,39 @@ /* Purpose: */ /* */ /* Principal Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Contributing Programmer(s): */ /* */ /* Revision History: */ /* */ +/* 6.23: Modified error messages so that they were */ +/* directly printed rather than storing them in */ +/* a string buffer which might not be large */ +/* enough to contain the entire message. DR0855 */ +/* Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Added get-region function. */ /* */ +/* Added environment parameter to GenClose. */ +/* Added environment parameter to GenOpen. */ +/* */ +/* 6.30: Removed HELP_FUNCTIONS compilation flag and */ +/* associated functionality. */ +/* */ +/* Used genstrcpy and genstrncpy instead of */ +/* strcpy and strncpy. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Changed integer type/precision. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_textpro @@ -41,13 +66,9 @@ int TossCommand(void *); #endif -#if HELP_FUNCTIONS - LOCALE void HelpFunction(void *); - LOCALE void HelpPathFunction(void *); -#endif - LOCALE void HelpFunctionDefinitions(void *); -#endif + +#endif /* _H_textpro */ diff --git a/src/tmpltbin.c b/src/tmpltbin.c index 8656c92..41cc875 100644 --- a/src/tmpltbin.c +++ b/src/tmpltbin.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.21 06/15/03 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE BSAVE/BLOAD MODULE */ /*******************************************************/ @@ -14,12 +14,17 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ /*************************************************************/ #define _TMPLTBIN_SOURCE_ @@ -81,7 +86,7 @@ globle void DeftemplateBinarySetup( ClearBload); #endif } - + /***********************************************************/ /* DeallocateDeftemplateBloadData: Deallocates environment */ /* data for the deftemplate bsave functionality. */ @@ -89,16 +94,16 @@ globle void DeftemplateBinarySetup( static void DeallocateDeftemplateBloadData( void *theEnv) { - unsigned long space; + size_t space; space = DeftemplateBinaryData(theEnv)->NumberOfTemplateModules * sizeof(struct deftemplateModule); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->ModuleArray,space); - + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->ModuleArray,space); + space = DeftemplateBinaryData(theEnv)->NumberOfDeftemplates * sizeof(struct deftemplate); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->DeftemplateArray,space); + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->DeftemplateArray,space); space = DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots * sizeof(struct templateSlot); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->SlotArray,space); + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->SlotArray,space); } #if BLOAD_AND_BSAVE @@ -191,7 +196,7 @@ static void BsaveStorage( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; /*========================================================================*/ /* Three data structures are saved as part of a deftemplate binary image: */ @@ -202,10 +207,10 @@ static void BsaveStorage( /*========================================================================*/ space = sizeof(long) * 3; - GenWrite(&space,(unsigned long) sizeof(long int),fp); - GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,(unsigned long) sizeof(long int),fp); - GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,(unsigned long) sizeof(long int),fp); - GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,(unsigned long) sizeof(long int),fp); + GenWrite(&space,sizeof(size_t),fp); + GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,sizeof(long int),fp); + GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,sizeof(long int),fp); + GenWrite(&DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,sizeof(long int),fp); } /***********************************************/ @@ -216,7 +221,7 @@ static void BsaveBinaryItem( void *theEnv, FILE *fp) { - unsigned long space; + size_t space; struct deftemplate *theDeftemplate; struct bsaveDeftemplate tempDeftemplate; struct templateSlot *theSlot; @@ -234,7 +239,7 @@ static void BsaveBinaryItem( space = (DeftemplateBinaryData(theEnv)->NumberOfDeftemplates * sizeof(struct bsaveDeftemplate)) + (DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots * sizeof(struct bsaveTemplateSlot)) + (DeftemplateBinaryData(theEnv)->NumberOfTemplateModules * sizeof(struct bsaveDeftemplateModule)); - GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp); + GenWrite(&space,sizeof(size_t),fp); /*===================================================*/ /* Write out each deftemplate module data structure. */ @@ -251,7 +256,7 @@ static void BsaveBinaryItem( GetModuleItem(theEnv,NULL,FindModuleItem(theEnv,"deftemplate")->moduleIndex); AssignBsaveDefmdlItemHdrVals(&tempTemplateModule.header, &theModuleItem->header); - GenWrite(&tempTemplateModule,(unsigned long) sizeof(struct bsaveDeftemplateModule),fp); + GenWrite(&tempTemplateModule,sizeof(struct bsaveDeftemplateModule),fp); } /*============================================*/ @@ -279,7 +284,7 @@ static void BsaveBinaryItem( { tempDeftemplate.slotList = DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots; } else tempDeftemplate.slotList = -1L; - GenWrite(&tempDeftemplate,(unsigned long) sizeof(struct bsaveDeftemplate),fp); + GenWrite(&tempDeftemplate,sizeof(struct bsaveDeftemplate),fp); DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots += theDeftemplate->numberOfSlots; } @@ -310,11 +315,12 @@ static void BsaveBinaryItem( tempTemplateSlot.defaultPresent = theSlot->defaultPresent; tempTemplateSlot.defaultDynamic = theSlot->defaultDynamic; tempTemplateSlot.defaultList = HashedExpressionIndex(theEnv,theSlot->defaultList); + tempTemplateSlot.facetList = HashedExpressionIndex(theEnv,theSlot->facetList); if (theSlot->next != NULL) tempTemplateSlot.next = 0L; else tempTemplateSlot.next = -1L; - GenWrite(&tempTemplateSlot,(unsigned long) sizeof(struct bsaveTemplateSlot),fp); + GenWrite(&tempTemplateSlot,sizeof(struct bsaveTemplateSlot),fp); } } } @@ -341,17 +347,17 @@ static void BsaveBinaryItem( static void BloadStorage( void *theEnv) { - unsigned long int space; + size_t space; /*=========================================================*/ /* Determine the number of deftemplate, deftemplateModule, */ /* and templateSlot data structures to be read. */ /*=========================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); - GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,(unsigned long) sizeof(long int)); - GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,(unsigned long) sizeof(long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); + GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,sizeof(long int)); + GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,sizeof(long int)); + GenReadBinary(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,sizeof(long int)); /*====================================*/ /* Allocate the space needed for the */ @@ -367,7 +373,7 @@ static void BloadStorage( } space = DeftemplateBinaryData(theEnv)->NumberOfTemplateModules * sizeof(struct deftemplateModule); - DeftemplateBinaryData(theEnv)->ModuleArray = (struct deftemplateModule *) genlongalloc(theEnv,space); + DeftemplateBinaryData(theEnv)->ModuleArray = (struct deftemplateModule *) genalloc(theEnv,space); /*===================================*/ /* Allocate the space needed for the */ @@ -382,7 +388,7 @@ static void BloadStorage( } space = DeftemplateBinaryData(theEnv)->NumberOfDeftemplates * sizeof(struct deftemplate); - DeftemplateBinaryData(theEnv)->DeftemplateArray = (struct deftemplate *) genlongalloc(theEnv,space); + DeftemplateBinaryData(theEnv)->DeftemplateArray = (struct deftemplate *) genalloc(theEnv,space); /*===================================*/ /* Allocate the space needed for the */ @@ -396,7 +402,7 @@ static void BloadStorage( } space = DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots * sizeof(struct templateSlot); - DeftemplateBinaryData(theEnv)->SlotArray = (struct templateSlot *) genlongalloc(theEnv,space); + DeftemplateBinaryData(theEnv)->SlotArray = (struct templateSlot *) genalloc(theEnv,space); } /********************************************************/ @@ -406,7 +412,7 @@ static void BloadStorage( static void BloadBinaryItem( void *theEnv) { - unsigned long int space; + size_t space; /*======================================================*/ /* Read in the amount of space used by the binary image */ @@ -414,14 +420,14 @@ static void BloadBinaryItem( /* is not available in the version being run). */ /*======================================================*/ - GenReadBinary(theEnv,&space,(unsigned long) sizeof(unsigned long int)); + GenReadBinary(theEnv,&space,sizeof(size_t)); /*===============================================*/ /* Read in the deftemplateModule data structures */ /* and refresh the pointers. */ /*===============================================*/ - BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,(unsigned) sizeof(struct bsaveDeftemplateModule), + BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateModules,sizeof(struct bsaveDeftemplateModule), UpdateDeftemplateModule); /*===============================================*/ @@ -429,7 +435,7 @@ static void BloadBinaryItem( /* and refresh the pointers. */ /*===============================================*/ - BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,(unsigned) sizeof(struct bsaveDeftemplate), + BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfDeftemplates,sizeof(struct bsaveDeftemplate), UpdateDeftemplate); /*==========================================*/ @@ -437,7 +443,7 @@ static void BloadBinaryItem( /* and refresh the pointers. */ /*==========================================*/ - BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,(unsigned) sizeof(struct bsaveTemplateSlot), + BloadandRefresh(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots,sizeof(struct bsaveTemplateSlot), UpdateDeftemplateSlot); } @@ -515,6 +521,7 @@ static void UpdateDeftemplateSlot( theSlot->slotName = SymbolPointer(btsPtr->slotName); IncrementSymbolCount(theSlot->slotName); theSlot->defaultList = HashedExpressionPointer(btsPtr->defaultList); + theSlot->facetList = HashedExpressionPointer(btsPtr->facetList); theSlot->constraints = ConstraintPointer(btsPtr->constraints); theSlot->multislot = btsPtr->multislot; @@ -535,7 +542,7 @@ static void UpdateDeftemplateSlot( static void ClearBload( void *theEnv) { - unsigned long int space; + size_t space; int i; /*=============================================*/ @@ -559,25 +566,25 @@ static void ClearBload( /*======================================================================*/ space = DeftemplateBinaryData(theEnv)->NumberOfTemplateModules * sizeof(struct deftemplateModule); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->ModuleArray,space); + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->ModuleArray,space); DeftemplateBinaryData(theEnv)->NumberOfTemplateModules = 0; - + /*================================================================*/ /* Deallocate the space used for the deftemplate data structures. */ /*================================================================*/ space = DeftemplateBinaryData(theEnv)->NumberOfDeftemplates * sizeof(struct deftemplate); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->DeftemplateArray,space); + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->DeftemplateArray,space); DeftemplateBinaryData(theEnv)->NumberOfDeftemplates = 0; - + /*=================================================================*/ /* Deallocate the space used for the templateSlot data structures. */ /*=================================================================*/ space = DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots * sizeof(struct templateSlot); - if (space != 0) genlongfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->SlotArray,space); + if (space != 0) genfree(theEnv,(void *) DeftemplateBinaryData(theEnv)->SlotArray,space); DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots = 0; - + /*======================================*/ /* Create the initial-fact deftemplate. */ /*======================================*/ diff --git a/src/tmpltbin.h b/src/tmpltbin.h index 00cff52..a04957d 100644 --- a/src/tmpltbin.h +++ b/src/tmpltbin.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE BSAVE/BLOAD HEADER FILE */ /*******************************************************/ @@ -13,13 +13,21 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ /* */ +/* 6.23: Added support for templates maintaining their */ +/* own list of facts. */ +/* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ /*************************************************************/ #if (! RUN_TIME) + #ifndef _H_tmpltbin #define _H_tmpltbin @@ -33,6 +41,7 @@ struct bsaveTemplateSlot unsigned int defaultDynamic : 1; long constraints; long defaultList; + long facetList; long next; }; @@ -60,7 +69,7 @@ struct bsaveDeftemplateModule #define TMPLTBIN_DATA 61 struct deftemplateBinaryData - { + { struct deftemplate *DeftemplateArray; long NumberOfDeftemplates; long NumberOfTemplateSlots; @@ -68,7 +77,7 @@ struct deftemplateBinaryData struct templateSlot *SlotArray; struct deftemplateModule *ModuleArray; }; - + #define DeftemplateBinaryData(theEnv) ((struct deftemplateBinaryData *) GetEnvironmentData(theEnv,TMPLTBIN_DATA)) #define DeftemplatePointer(i) ((struct deftemplate *) (&DeftemplateBinaryData(theEnv)->DeftemplateArray[i])) @@ -90,8 +99,9 @@ struct deftemplateBinaryData LOCALE void DeftemplateBinarySetup(void *); LOCALE void *BloadDeftemplateModuleReference(void *,int); -#endif -#endif +#endif /* _H_tmpltbin */ + +#endif /* (! RUN_TIME) */ diff --git a/src/tmpltbsc.c b/src/tmpltbsc.c index d489d2a..5fb985e 100644 --- a/src/tmpltbsc.c +++ b/src/tmpltbsc.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE BASIC COMMANDS MODULE */ /*******************************************************/ @@ -16,9 +16,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ @@ -31,6 +32,15 @@ /* Corrected code to remove compiler warnings */ /* when ENVIRONMENT_API_ONLY flag is set. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _TMPLTBSC_SOURCE_ @@ -73,7 +83,7 @@ static void ResetDeftemplates(void *); #endif static void ClearDeftemplates(void *); - static void SaveDeftemplates(void *,void *,char *); + static void SaveDeftemplates(void *,void *,const char *); /*********************************************************************/ /* DeftemplateBasicCommands: Initializes basic deftemplate commands. */ @@ -138,7 +148,7 @@ static void ClearDeftemplates( CreateImpliedDeftemplate(theEnv,(SYMBOL_HN *) EnvAddSymbol(theEnv,"initial-fact"),FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -151,8 +161,8 @@ static void ClearDeftemplates( static void SaveDeftemplates( void *theEnv, void *theModule, - char *logicalName) - { + const char *logicalName) + { SaveConstruct(theEnv,theModule,logicalName,DeftemplateData(theEnv)->DeftemplateConstruct); } @@ -162,8 +172,8 @@ static void SaveDeftemplates( /**********************************************/ globle void UndeftemplateCommand( void *theEnv) - { - UndefconstructCommand(theEnv,"undeftemplate",DeftemplateData(theEnv)->DeftemplateConstruct); + { + UndefconstructCommand(theEnv,"undeftemplate",DeftemplateData(theEnv)->DeftemplateConstruct); } /**************************************/ @@ -173,8 +183,8 @@ globle void UndeftemplateCommand( globle intBool EnvUndeftemplate( void *theEnv, void *theDeftemplate) - { - return(Undefconstruct(theEnv,theDeftemplate,DeftemplateData(theEnv)->DeftemplateConstruct)); + { + return(Undefconstruct(theEnv,theDeftemplate,DeftemplateData(theEnv)->DeftemplateConstruct)); } /****************************************************/ @@ -184,8 +194,8 @@ globle intBool EnvUndeftemplate( globle void GetDeftemplateListFunction( void *theEnv, DATA_OBJECT_PTR returnValue) - { - GetConstructListFunction(theEnv,"get-deftemplate-list",returnValue,DeftemplateData(theEnv)->DeftemplateConstruct); + { + GetConstructListFunction(theEnv,"get-deftemplate-list",returnValue,DeftemplateData(theEnv)->DeftemplateConstruct); } /***********************************************/ @@ -196,8 +206,8 @@ globle void EnvGetDeftemplateList( void *theEnv, DATA_OBJECT_PTR returnValue, void *theModule) - { - GetConstructList(theEnv,returnValue,DeftemplateData(theEnv)->DeftemplateConstruct,(struct defmodule *) theModule); + { + GetConstructList(theEnv,returnValue,DeftemplateData(theEnv)->DeftemplateConstruct,(struct defmodule *) theModule); } /***************************************************/ @@ -206,8 +216,8 @@ globle void EnvGetDeftemplateList( /***************************************************/ globle void *DeftemplateModuleFunction( void *theEnv) - { - return(GetConstructModuleCommand(theEnv,"deftemplate-module",DeftemplateData(theEnv)->DeftemplateConstruct)); + { + return(GetConstructModuleCommand(theEnv,"deftemplate-module",DeftemplateData(theEnv)->DeftemplateConstruct)); } #if DEBUGGING_FUNCTIONS @@ -218,8 +228,8 @@ globle void *DeftemplateModuleFunction( /**********************************************/ globle void PPDeftemplateCommand( void *theEnv) - { - PPConstructCommand(theEnv,"ppdeftemplate",DeftemplateData(theEnv)->DeftemplateConstruct); + { + PPConstructCommand(theEnv,"ppdeftemplate",DeftemplateData(theEnv)->DeftemplateConstruct); } /***************************************/ @@ -228,10 +238,10 @@ globle void PPDeftemplateCommand( /***************************************/ globle int PPDeftemplate( void *theEnv, - char *deftemplateName, - char *logicalName) - { - return(PPConstruct(theEnv,deftemplateName,logicalName,DeftemplateData(theEnv)->DeftemplateConstruct)); + const char *deftemplateName, + const char *logicalName) + { + return(PPConstruct(theEnv,deftemplateName,logicalName,DeftemplateData(theEnv)->DeftemplateConstruct)); } /*************************************************/ @@ -240,8 +250,8 @@ globle int PPDeftemplate( /*************************************************/ globle void ListDeftemplatesCommand( void *theEnv) - { - ListConstructCommand(theEnv,"list-deftemplates",DeftemplateData(theEnv)->DeftemplateConstruct); + { + ListConstructCommand(theEnv,"list-deftemplates",DeftemplateData(theEnv)->DeftemplateConstruct); } /*****************************************/ @@ -250,63 +260,54 @@ globle void ListDeftemplatesCommand( /*****************************************/ globle void EnvListDeftemplates( void *theEnv, - char *logicalName, + const char *logicalName, void *theModule) - { - ListConstruct(theEnv,DeftemplateData(theEnv)->DeftemplateConstruct,logicalName,(struct defmodule *) theModule); + { + ListConstruct(theEnv,DeftemplateData(theEnv)->DeftemplateConstruct,logicalName,(struct defmodule *) theModule); } /***********************************************************/ /* EnvGetDeftemplateWatch: C access routine for retrieving */ /* the current watch value of a deftemplate. */ /***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned EnvGetDeftemplateWatch( void *theEnv, void *theTemplate) - { -#if MAC_MCW || IBM_MCW || MAC_XCD + { +#if MAC_XCD #pragma unused(theEnv) #endif - return(((struct deftemplate *) theTemplate)->watch); + return(((struct deftemplate *) theTemplate)->watch); } /*********************************************************/ /* EnvSetDeftemplateWatch: C access routine for setting */ /* the current watch value of a deftemplate. */ /*********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void EnvSetDeftemplateWatch( void *theEnv, unsigned newState, void *theTemplate) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif - ((struct deftemplate *) theTemplate)->watch = newState; + ((struct deftemplate *) theTemplate)->watch = newState; } /**********************************************************/ /* DeftemplateWatchAccess: Access routine for setting the */ /* watch flag of a deftemplate via the watch command. */ /**********************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned DeftemplateWatchAccess( void *theEnv, int code, unsigned newState, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -318,16 +319,13 @@ globle unsigned DeftemplateWatchAccess( /* DeftemplateWatchPrint: Access routine for printing which deftemplates */ /* have their watch flag set via the list-watch-items command. */ /*************************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle unsigned DeftemplateWatchPrint( void *theEnv, - char *logName, + const char *logName, int code, EXPRESSION *argExprs) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(code) #endif @@ -337,6 +335,52 @@ globle unsigned DeftemplateWatchPrint( #endif /* DEBUGGING_FUNCTIONS */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void GetDeftemplateList( + DATA_OBJECT_PTR returnValue, + void *theModule) + { + EnvGetDeftemplateList(GetCurrentEnvironment(),returnValue,theModule); + } + +#if DEBUGGING_FUNCTIONS + +globle unsigned GetDeftemplateWatch( + void *theTemplate) + { + return EnvGetDeftemplateWatch(GetCurrentEnvironment(),theTemplate); + } + +globle void ListDeftemplates( + const char *logicalName, + void *theModule) + { + EnvListDeftemplates(GetCurrentEnvironment(),logicalName,theModule); + } + +globle void SetDeftemplateWatch( + unsigned newState, + void *theTemplate) + { + EnvSetDeftemplateWatch(GetCurrentEnvironment(),newState,theTemplate); + } + +#endif /* DEBUGGING_FUNCTIONS */ + +globle intBool Undeftemplate( + void *theDeftemplate) + { + return EnvUndeftemplate(GetCurrentEnvironment(),theDeftemplate); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/tmpltbsc.h b/src/tmpltbsc.h index e0d6769..c687e25 100644 --- a/src/tmpltbsc.h +++ b/src/tmpltbsc.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.26 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE BASIC COMMANDS HEADER FILE */ /*******************************************************/ @@ -16,14 +16,31 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Corrected compilation errors for files */ /* generated by constructs-to-c. DR0861 */ /* */ +/* Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove compiler warnings */ +/* when ENVIRONMENT_API_ONLY flag is set. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_tmpltbsc @@ -43,20 +60,6 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetDeftemplateList(theEnv,a,b) EnvGetDeftemplateList(theEnv,a,b) -#define ListDeftemplates(theEnv,a,b) EnvListDeftemplates(theEnv,a,b) -#define Undeftemplate(theEnv,a) EnvUndeftemplate(theEnv,a) -#define GetDeftemplateWatch(theEnv,a) EnvGetDeftemplateWatch(theEnv,a) -#define SetDeftemplateWatch(theEnv,a,b) EnvSetDeftemplateWatch(theEnv,a,b) -#else -#define GetDeftemplateList(a,b) EnvGetDeftemplateList(GetCurrentEnvironment(),a,b) -#define ListDeftemplates(a,b) EnvListDeftemplates(GetCurrentEnvironment(),a,b) -#define Undeftemplate(a) EnvUndeftemplate(GetCurrentEnvironment(),a) -#define GetDeftemplateWatch(a) EnvGetDeftemplateWatch(GetCurrentEnvironment(),a) -#define SetDeftemplateWatch(a,b) EnvSetDeftemplateWatch(GetCurrentEnvironment(),a,b) -#endif - LOCALE void DeftemplateBasicCommands(void *); LOCALE void UndeftemplateCommand(void *); LOCALE intBool EnvUndeftemplate(void *,void *); @@ -65,15 +68,27 @@ LOCALE void *DeftemplateModuleFunction(void *); #if DEBUGGING_FUNCTIONS LOCALE void PPDeftemplateCommand(void *); - LOCALE int PPDeftemplate(void *,char *,char *); + LOCALE int PPDeftemplate(void *,const char *,const char *); LOCALE void ListDeftemplatesCommand(void *); - LOCALE void EnvListDeftemplates(void *,char *,void *); + LOCALE void EnvListDeftemplates(void *,const char *,void *); LOCALE unsigned EnvGetDeftemplateWatch(void *,void *); LOCALE void EnvSetDeftemplateWatch(void *,unsigned,void *); LOCALE unsigned DeftemplateWatchAccess(void *,int,unsigned,struct expr *); - LOCALE unsigned DeftemplateWatchPrint(void *,char *,int,struct expr *); + LOCALE unsigned DeftemplateWatchPrint(void *,const char *,int,struct expr *); #endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void GetDeftemplateList(DATA_OBJECT_PTR,void *); +#if DEBUGGING_FUNCTIONS + LOCALE unsigned GetDeftemplateWatch(void *); + LOCALE void ListDeftemplates(const char *,void *); + LOCALE void SetDeftemplateWatch(unsigned,void *); #endif + LOCALE intBool Undeftemplate(void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_tmpltbsc */ diff --git a/src/tmpltcmp.c b/src/tmpltcmp.c index cc9ede0..1e48477 100644 --- a/src/tmpltcmp.c +++ b/src/tmpltcmp.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE CONSTRUCTS-TO-C MODULE */ /*******************************************************/ @@ -14,12 +14,29 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added code for deftemplate run time */ +/* initialization of hashed comparisons to */ +/* constants. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _TMPLTCMP_SOURCE_ @@ -45,12 +62,13 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static int ConstructToCode(void *,char *,int,FILE *,int,int); + static int ConstructToCode(void *,const char *,const char *,char *,int,FILE *,int,int); static void SlotToCode(void *,FILE *,struct templateSlot *,int,int,int); static void DeftemplateModuleToCode(void *,FILE *,struct defmodule *,int,int,int); static void DeftemplateToCode(void *,FILE *,struct deftemplate *, int,int,int,int); static void CloseDeftemplateFiles(void *,FILE *,FILE *,FILE *,int); + static void InitDeftemplateCode(void *,FILE *,int,int); /*********************************************************/ /* DeftemplateCompilerSetup: Initializes the deftemplate */ @@ -59,7 +77,7 @@ globle void DeftemplateCompilerSetup( void *theEnv) { - DeftemplateData(theEnv)->DeftemplateCodeItem = AddCodeGeneratorItem(theEnv,"deftemplate",0,NULL,NULL,ConstructToCode,3); + DeftemplateData(theEnv)->DeftemplateCodeItem = AddCodeGeneratorItem(theEnv,"deftemplate",0,NULL,InitDeftemplateCode,ConstructToCode,3); } /*************************************************************/ @@ -68,7 +86,9 @@ globle void DeftemplateCompilerSetup( /*************************************************************/ static int ConstructToCode( void *theEnv, - char *fileName, + const char *fileName, + const char *pathName, + char *fileNameBuffer, int fileID, FILE *headerFP, int imageID, @@ -101,7 +121,7 @@ static int ConstructToCode( { EnvSetCurrentModule(theEnv,(void *) theModule); - moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,fileID,imageID,&fileCount, + moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, moduleArrayVersion,headerFP, "struct deftemplateModule",ModulePrefix(DeftemplateData(theEnv)->DeftemplateCodeItem), FALSE,NULL); @@ -124,7 +144,7 @@ static int ConstructToCode( while (theTemplate != NULL) { - templateFile = OpenFileIfNeeded(theEnv,templateFile,fileName,fileID,imageID,&fileCount, + templateFile = OpenFileIfNeeded(theEnv,templateFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, templateArrayVersion,headerFP, "struct deftemplate",ConstructPrefix(DeftemplateData(theEnv)->DeftemplateCodeItem), FALSE,NULL); @@ -147,7 +167,7 @@ static int ConstructToCode( slotPtr = theTemplate->slotList; while (slotPtr != NULL) { - slotFile = OpenFileIfNeeded(theEnv,slotFile,fileName,fileID,imageID,&fileCount, + slotFile = OpenFileIfNeeded(theEnv,slotFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount, slotArrayVersion,headerFP, "struct templateSlot",SlotPrefix(),FALSE,NULL); if (slotFile == NULL) @@ -216,9 +236,6 @@ static void CloseDeftemplateFiles( /* DeftemplateModuleToCode: Writes the C code representation */ /* of a single deftemplate module to the specified file. */ /*************************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DeftemplateModuleToCode( void *theEnv, FILE *theFile, @@ -227,7 +244,7 @@ static void DeftemplateModuleToCode( int maxIndices, int moduleCount) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(moduleCount) #endif @@ -297,7 +314,7 @@ static void DeftemplateToCode( /* Print the factList and lastFact references */ /* and close the structure. */ /*============================================*/ - + fprintf(theFile,",NULL,NULL}"); } @@ -339,6 +356,13 @@ static void SlotToCode( fprintf(theFile,","); PrintHashedExpressionReference(theEnv,theFile,theSlot->defaultList,imageID,maxIndices); + + /*============*/ + /* Facet List */ + /*============*/ + + fprintf(theFile,","); + PrintHashedExpressionReference(theEnv,theFile,theSlot->facetList,imageID,maxIndices); fprintf(theFile,","); /*===========*/ @@ -397,5 +421,24 @@ globle void DeftemplateCConstructReference( } +/*******************************************/ +/* InitDeftemplateCode: Writes out runtime */ +/* initialization code for deftemplates. */ +/*******************************************/ +static void InitDeftemplateCode( + void *theEnv, + FILE *initFP, + int imageID, + int maxIndices) + { +#if MAC_XCD +#pragma unused(theEnv) +#pragma unused(imageID) +#pragma unused(maxIndices) +#endif + + fprintf(initFP," DeftemplateRunTimeInitialize(theEnv);\n"); + } + #endif /* DEFTEMPLATE_CONSTRUCT && CONSTRUCT_COMPILER && (! RUN_TIME) */ diff --git a/src/tmpltcmp.h b/src/tmpltcmp.h index f2f8d65..90025b2 100644 --- a/src/tmpltcmp.h +++ b/src/tmpltcmp.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE CONSTRUCT COMPILER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,25 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Added support for templates maintaining their */ +/* own list of facts. */ +/* */ +/* 6.30: Added support for path name argument to */ +/* constructs-to-c. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added code for deftemplate run time */ +/* initialization of hashed comparisons to */ +/* constants. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_tmpltcmp @@ -36,4 +55,4 @@ LOCALE void DeftemplateCModuleReference(void *,FILE *,int,int,int); LOCALE void DeftemplateCConstructReference(void *,FILE *,void *,int,int); -#endif +#endif /* _H_tmpltcmp */ diff --git a/src/tmpltdef.c b/src/tmpltdef.c index 309f7ec..b805ea2 100644 --- a/src/tmpltdef.c +++ b/src/tmpltdef.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFTEMPLATE MODULE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ @@ -26,6 +27,25 @@ /* Corrected code to remove run-time program */ /* compiler warnings. */ /* */ +/* 6.30: Added code for deftemplate run time */ +/* initialization of hashed comparisons to */ +/* constants. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _TMPLTDEF_SOURCE_ @@ -73,6 +93,10 @@ static void DeallocateDeftemplateData(void *); static void DestroyDeftemplateAction(void *,struct constructHeader *,void *); static void DestroyDeftemplate(void *,void *); +#if RUN_TIME + static void RuntimeDeftemplateAction(void *,struct constructHeader *,void *); + static void SearchForHashedPatternNodes(void *,struct factPatternNode *); +#endif /******************************************************************/ /* InitializeDeftemplates: Initializes the deftemplate construct. */ @@ -88,10 +112,10 @@ globle void InitializeDeftemplates( NULL, DecrementDeftemplateBusyCount, IncrementDeftemplateBusyCount, - NULL,NULL,NULL,NULL }; + NULL,NULL,NULL,NULL,NULL }; AllocateEnvironmentData(theEnv,DEFTEMPLATE_DATA,sizeof(struct deftemplateData),DeallocateDeftemplateData); - memcpy(&DeftemplateData(theEnv)->DeftemplatePtrRecord,&deftemplatePtrRecord,sizeof(struct entityRecord)); + memcpy(&DeftemplateData(theEnv)->DeftemplatePtrRecord,&deftemplatePtrRecord,sizeof(struct entityRecord)); InitializeFacts(theEnv); @@ -109,7 +133,7 @@ globle void InitializeDeftemplates( InstallPrimitive(theEnv,(ENTITY_RECORD_PTR) &DeftemplateData(theEnv)->DeftemplatePtrRecord,DEFTEMPLATE_PTR); } - + /******************************************************/ /* DeallocateDeftemplateData: Deallocates environment */ /* data for the deftemplate construct. */ @@ -125,7 +149,7 @@ static void DeallocateDeftemplateData( if (Bloaded(theEnv)) return; #endif - DoForAllConstructs(theEnv,DestroyDeftemplateAction,DeftemplateData(theEnv)->DeftemplateModuleIndex,FALSE,NULL); + DoForAllConstructs(theEnv,DestroyDeftemplateAction,DeftemplateData(theEnv)->DeftemplateModuleIndex,FALSE,NULL); #if ! RUN_TIME for (theModule = EnvGetNextDefmodule(theEnv,NULL); @@ -139,26 +163,23 @@ static void DeallocateDeftemplateData( } #endif } - + /*****************************************************/ /* DestroyDeftemplateAction: Action used to remove */ /* deftemplates as a result of DestroyEnvironment. */ /*****************************************************/ -#if IBM_TBC -#pragma argsused -#endif static void DestroyDeftemplateAction( void *theEnv, struct constructHeader *theConstruct, void *buffer) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(buffer) #endif struct deftemplate *theDeftemplate = (struct deftemplate *) theConstruct; - + if (theDeftemplate == NULL) return; - + DestroyDeftemplate(theEnv,theDeftemplate); } @@ -183,7 +204,7 @@ static void InitializeDeftemplateModules( #else NULL, #endif - EnvFindDeftemplate); + EnvFindDeftemplateInModule); #if (! BLOAD_ONLY) && (! RUN_TIME) && DEFMODULE_CONSTRUCT AddPortConstructItem(theEnv,"deftemplate",SYMBOL); @@ -195,8 +216,8 @@ static void InitializeDeftemplateModules( /***************************************************/ static void *AllocateModule( void *theEnv) - { - return((void *) get_struct(theEnv,deftemplateModule)); + { + return((void *) get_struct(theEnv,deftemplateModule)); } /*************************************************/ @@ -205,7 +226,7 @@ static void *AllocateModule( static void ReturnModule( void *theEnv, void *theItem) - { + { FreeConstructHeaderModule(theEnv,(struct defmoduleItemHeader *) theItem,DeftemplateData(theEnv)->DeftemplateConstruct); rtn_struct(theEnv,deftemplateModule,theItem); } @@ -217,8 +238,8 @@ static void ReturnModule( globle struct deftemplateModule *GetDeftemplateModuleItem( void *theEnv, struct defmodule *theModule) - { - return((struct deftemplateModule *) GetConstructModuleItemByIndex(theEnv,theModule,DeftemplateData(theEnv)->DeftemplateModuleIndex)); + { + return((struct deftemplateModule *) GetConstructModuleItemByIndex(theEnv,theModule,DeftemplateData(theEnv)->DeftemplateModuleIndex)); } /*****************************************************/ @@ -228,9 +249,21 @@ globle struct deftemplateModule *GetDeftemplateModuleItem( /*****************************************************/ globle void *EnvFindDeftemplate( void *theEnv, - char *deftemplateName) - { - return(FindNamedConstruct(theEnv,deftemplateName,DeftemplateData(theEnv)->DeftemplateConstruct)); + const char *deftemplateName) + { + return(FindNamedConstructInModuleOrImports(theEnv,deftemplateName,DeftemplateData(theEnv)->DeftemplateConstruct)); + } + +/*****************************************************/ +/* EnvFindDeftemplateInModule: Searches for a deftemplate in */ +/* the list of deftemplates. Returns a pointer to */ +/* the deftemplate if found, otherwise NULL. */ +/*****************************************************/ +globle void *EnvFindDeftemplateInModule( + void *theEnv, + const char *deftemplateName) + { + return(FindNamedConstructInModule(theEnv,deftemplateName,DeftemplateData(theEnv)->DeftemplateConstruct)); } /***********************************************************************/ @@ -241,8 +274,8 @@ globle void *EnvFindDeftemplate( globle void *EnvGetNextDeftemplate( void *theEnv, void *deftemplatePtr) - { - return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) deftemplatePtr,DeftemplateData(theEnv)->DeftemplateModuleIndex)); + { + return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) deftemplatePtr,DeftemplateData(theEnv)->DeftemplateModuleIndex)); } /***********************************************************/ @@ -272,10 +305,6 @@ static void ReturnDeftemplate( void *theEnv, void *vTheConstruct) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,vTheConstruct) -#endif - #if (! BLOAD_ONLY) && (! RUN_TIME) struct deftemplate *theConstruct = (struct deftemplate *) vTheConstruct; struct templateSlot *slotPtr; @@ -301,6 +330,8 @@ static void ReturnDeftemplate( DecrementSymbolCount(theEnv,slotPtr->slotName); RemoveHashedExpression(theEnv,slotPtr->defaultList); slotPtr->defaultList = NULL; + RemoveHashedExpression(theEnv,slotPtr->facetList); + slotPtr->facetList = NULL; RemoveConstraint(theEnv,slotPtr->constraints); slotPtr->constraints = NULL; slotPtr = slotPtr->next; @@ -317,7 +348,7 @@ static void ReturnDeftemplate( rtn_struct(theEnv,deftemplate,theConstruct); #endif } - + /**************************************************************/ /* DestroyDeftemplate: Returns the data structures associated */ /* with a deftemplate construct to the pool of free memory. */ @@ -326,16 +357,12 @@ static void DestroyDeftemplate( void *theEnv, void *vTheConstruct) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(vTheConstruct) -#endif - struct deftemplate *theConstruct = (struct deftemplate *) vTheConstruct; #if (! BLOAD_ONLY) && (! RUN_TIME) struct templateSlot *slotPtr, *nextSlot; #endif if (theConstruct == NULL) return; - + #if (! BLOAD_ONLY) && (! RUN_TIME) slotPtr = theConstruct->slotList; @@ -348,7 +375,7 @@ static void DestroyDeftemplate( #endif DestroyFactPatternNetwork(theEnv,theConstruct->patternNetwork); - + /*==================================*/ /* Free storage used by the header. */ /*==================================*/ @@ -359,7 +386,7 @@ static void DestroyDeftemplate( rtn_struct(theEnv,deftemplate,theConstruct); #endif } - + /***********************************************/ /* ReturnSlots: Returns the slot structures of */ /* a deftemplate to free memory. */ @@ -368,10 +395,6 @@ globle void ReturnSlots( void *theEnv, struct templateSlot *slotPtr) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(theEnv,slotPtr) -#endif - #if (! BLOAD_ONLY) && (! RUN_TIME) struct templateSlot *nextSlot; @@ -379,6 +402,7 @@ globle void ReturnSlots( { nextSlot = slotPtr->next; ReturnExpression(theEnv,slotPtr->defaultList); + ReturnExpression(theEnv,slotPtr->facetList); RemoveConstraint(theEnv,slotPtr->constraints); rtn_struct(theEnv,templateSlot,slotPtr); slotPtr = nextSlot; @@ -403,35 +427,29 @@ globle void DecrementDeftemplateBusyCount( /* IncrementDeftemplateBusyCount: Increments the */ /* busy count of a deftemplate data structure. */ /*************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void IncrementDeftemplateBusyCount( void *theEnv, void *vTheTemplate) { struct deftemplate *theTemplate = (struct deftemplate *) vTheTemplate; -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif theTemplate->busyCount++; } - + /*******************************************************************/ /* EnvGetNextFactInTemplate: If passed a NULL pointer, returns the */ /* first fact in the template's fact-list. Otherwise returns the */ /* next template fact following the fact passed as an argument. */ /*******************************************************************/ -#if IBM_TBC -#pragma argsused -#endif globle void *EnvGetNextFactInTemplate( void *theEnv, void *theTemplate, void *factPtr) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif if (factPtr == NULL) @@ -442,6 +460,174 @@ globle void *EnvGetNextFactInTemplate( return((void *) ((struct fact *) factPtr)->nextTemplateFact); } +#if ! RUN_TIME + +/******************************/ +/* CreateDeftemplateScopeMap: */ +/******************************/ +globle void *CreateDeftemplateScopeMap( + void *theEnv, + struct deftemplate *theDeftemplate) + { + unsigned scopeMapSize; + char *scopeMap; + const char *templateName; + struct defmodule *matchModule, *theModule; + int moduleID,count; + void *theBitMap; + + templateName = ValueToString(theDeftemplate->header.name); + matchModule = theDeftemplate->header.whichModule->theModule; + + scopeMapSize = (sizeof(char) * ((GetNumberOfDefmodules(theEnv) / BITS_PER_BYTE) + 1)); + scopeMap = (char *) gm2(theEnv,scopeMapSize); + + ClearBitString((void *) scopeMap,scopeMapSize); + SaveCurrentModule(theEnv); + for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL) ; + theModule != NULL ; + theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule)) + { + EnvSetCurrentModule(theEnv,(void *) theModule); + moduleID = (int) theModule->bsaveID; + if (FindImportedConstruct(theEnv,"deftemplate",matchModule, + templateName,&count,TRUE,NULL) != NULL) + SetBitMap(scopeMap,moduleID); + } + RestoreCurrentModule(theEnv); + theBitMap = EnvAddBitMap(theEnv,scopeMap,scopeMapSize); + IncrementBitMapCount(theBitMap); + rm(theEnv,(void *) scopeMap,scopeMapSize); + return(theBitMap); + } + +#endif + +#if RUN_TIME + +/**************************************************/ +/* RuntimeDeftemplateAction: Action to be applied */ +/* to each deftemplate construct when a runtime */ +/* initialization occurs. */ +/**************************************************/ +static void RuntimeDeftemplateAction( + void *theEnv, + struct constructHeader *theConstruct, + void *buffer) + { +#if MAC_XCD +#pragma unused(buffer) +#endif + struct deftemplate *theDeftemplate = (struct deftemplate *) theConstruct; + + SearchForHashedPatternNodes(theEnv,theDeftemplate->patternNetwork); + } + +/*******************************************************************/ +/* SearchForHashedPatternNodes: */ +/*******************************************************************/ +static void SearchForHashedPatternNodes( + void *theEnv, + struct factPatternNode *theNode) + { + while (theNode != NULL) + { + if ((theNode->lastLevel != NULL) && (theNode->lastLevel->header.selector)) + { AddHashedPatternNode(theEnv,theNode->lastLevel,theNode,theNode->networkTest->type,theNode->networkTest->value); } + + SearchForHashedPatternNodes(theEnv,theNode->nextLevel); + + theNode = theNode->rightNode; + } + } + +/*******************************************************************/ +/* DeftemplateRunTimeInitialize: */ +/*******************************************************************/ +globle void DeftemplateRunTimeInitialize( + void *theEnv) + { + DoForAllConstructs(theEnv,RuntimeDeftemplateAction,DeftemplateData(theEnv)->DeftemplateModuleIndex,TRUE,NULL); + } + +#endif /* RUN_TIME */ + +/*##################################*/ +/* Additional Environment Functions */ +/*##################################*/ + +globle const char *EnvDeftemplateModule( + void *theEnv, + void *theDeftemplate) + { + return GetConstructModuleName((struct constructHeader *) theDeftemplate); + } + +globle const char *EnvGetDeftemplateName( + void *theEnv, + void *theDeftemplate) + { + return GetConstructNameString((struct constructHeader *) theDeftemplate); + } + +globle const char *EnvGetDeftemplatePPForm( + void *theEnv, + void *theDeftemplate) + { + return GetConstructPPForm(theEnv,(struct constructHeader *) theDeftemplate); + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle const char *DeftemplateModule( + void *theDeftemplate) + { + return EnvDeftemplateModule(GetCurrentEnvironment(),theDeftemplate); + } + +globle void *FindDeftemplate( + const char *deftemplateName) + { + return EnvFindDeftemplate(GetCurrentEnvironment(),deftemplateName); + } + +globle const char *GetDeftemplateName( + void *theDeftemplate) + { + return EnvGetDeftemplateName(GetCurrentEnvironment(),theDeftemplate); + } + +globle const char *GetDeftemplatePPForm( + void *theDeftemplate) + { + return EnvGetDeftemplatePPForm(GetCurrentEnvironment(),theDeftemplate); + } + +globle void *GetNextDeftemplate( + void *deftemplatePtr) + { + return EnvGetNextDeftemplate(GetCurrentEnvironment(),deftemplatePtr); + } + +globle intBool IsDeftemplateDeletable( + void *vTheDeftemplate) + { + return EnvIsDeftemplateDeletable(GetCurrentEnvironment(),vTheDeftemplate); + } + +globle void *GetNextFactInTemplate( + void *theTemplate, + void *factPtr) + { + return EnvGetNextFactInTemplate(GetCurrentEnvironment(),theTemplate,factPtr); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/tmpltdef.h b/src/tmpltdef.h index 860c99c..5a91e39 100644 --- a/src/tmpltdef.h +++ b/src/tmpltdef.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.26 06/05/06 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFTEMPLATE HEADER FILE */ /*******************************************************/ @@ -13,14 +13,37 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* Corrected code to remove run-time program */ +/* compiler warnings. */ +/* */ +/* 6.30: Added code for deftemplate run time */ +/* initialization of hashed comparisons to */ +/* constants. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #ifndef _H_tmpltdef @@ -82,6 +105,7 @@ struct templateSlot unsigned int defaultDynamic : 1; CONSTRAINT_RECORD *constraints; struct expr *defaultList; + struct expr *facetList; struct templateSlot *next; }; @@ -93,7 +117,7 @@ struct deftemplateModule #define DEFTEMPLATE_DATA 5 struct deftemplateData - { + { struct construct *DeftemplateConstruct; int DeftemplateModuleIndex; struct entityRecord DeftemplatePtrRecord; @@ -108,9 +132,6 @@ struct deftemplateData #endif }; -#define EnvGetDeftemplateName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define EnvGetDeftemplatePPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define EnvDeftemplateModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) #define DeftemplateData(theEnv) ((struct deftemplateData *) GetEnvironmentData(theEnv,DEFTEMPLATE_DATA)) #ifdef LOCALE @@ -123,26 +144,9 @@ struct deftemplateData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define FindDeftemplate(theEnv,a) EnvFindDeftemplate(theEnv,a) -#define GetNextDeftemplate(theEnv,a) EnvGetNextDeftemplate(theEnv,a) -#define IsDeftemplateDeletable(theEnv,a) EnvIsDeftemplateDeletable(theEnv,a) -#define GetDeftemplateName(theEnv,x) GetConstructNameString((struct constructHeader *) x) -#define GetDeftemplatePPForm(theEnv,x) GetConstructPPForm(theEnv,(struct constructHeader *) x) -#define GetNextFactInTemplate(theEnv,a,b) EnvGetNextFactInTemplate(theEnv,a,b) -#define DeftemplateModule(theEnv,x) GetConstructModuleName((struct constructHeader *) x) -#else -#define FindDeftemplate(a) EnvFindDeftemplate(GetCurrentEnvironment(),a) -#define GetNextDeftemplate(a) EnvGetNextDeftemplate(GetCurrentEnvironment(),a) -#define IsDeftemplateDeletable(a) EnvIsDeftemplateDeletable(GetCurrentEnvironment(),a) -#define GetDeftemplateName(x) GetConstructNameString((struct constructHeader *) x) -#define GetDeftemplatePPForm(x) GetConstructPPForm(GetCurrentEnvironment(),(struct constructHeader *) x) -#define GetNextFactInTemplate(a,b) EnvGetNextFactInTemplate(GetCurrentEnvironment(),a,b) -#define DeftemplateModule(x) GetConstructModuleName((struct constructHeader *) x) -#endif - LOCALE void InitializeDeftemplates(void *); - LOCALE void *EnvFindDeftemplate(void *,char *); + LOCALE void *EnvFindDeftemplate(void *,const char *); + LOCALE void *EnvFindDeftemplateInModule(void *,const char *); LOCALE void *EnvGetNextDeftemplate(void *,void *); LOCALE intBool EnvIsDeftemplateDeletable(void *,void *); LOCALE void *EnvGetNextFactInTemplate(void *,void *,void *); @@ -150,7 +154,26 @@ struct deftemplateData LOCALE void ReturnSlots(void *,struct templateSlot *); LOCALE void IncrementDeftemplateBusyCount(void *,void *); LOCALE void DecrementDeftemplateBusyCount(void *,void *); - + LOCALE void *CreateDeftemplateScopeMap(void *,struct deftemplate *); +#if RUN_TIME + LOCALE void DeftemplateRunTimeInitialize(void *); #endif + LOCALE const char *EnvDeftemplateModule(void *,void *); + LOCALE const char *EnvGetDeftemplateName(void *,void *); + LOCALE const char *EnvGetDeftemplatePPForm(void *,void *); + +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE const char *DeftemplateModule(void *); + LOCALE void *FindDeftemplate(const char *); + LOCALE const char *GetDeftemplateName(void *); + LOCALE const char *GetDeftemplatePPForm(void *); + LOCALE void *GetNextDeftemplate(void *); + LOCALE intBool IsDeftemplateDeletable(void *); + LOCALE void *GetNextFactInTemplate(void *,void *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_tmpltdef */ diff --git a/src/tmpltfun.c b/src/tmpltfun.c index 5365150..44e9400 100644 --- a/src/tmpltfun.c +++ b/src/tmpltfun.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* DEFTEMPLATE FUNCTIONS MODULE */ /*******************************************************/ @@ -15,6 +15,7 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ /* */ /* 6.24: Added deftemplate-slot-names, */ @@ -30,6 +31,34 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for deftemplate slot facets. */ +/* */ +/* Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* Added deftemplate-slot-facet-existp and */ +/* deftemplate-slot-facet-value functions. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Support for modify callback function. */ +/* */ +/* Added additional argument to function */ +/* CheckDeftemplateAndSlotArguments to specify */ +/* the expected number of arguments. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ /*************************************************************/ #define _TMPLTFUN_SOURCE_ @@ -57,6 +86,7 @@ #include "factrhs.h" #include "modulutl.h" #include "reorder.h" +#include "sysdep.h" #include "tmpltdef.h" #include "tmpltlhs.h" #include "tmpltutl.h" @@ -69,10 +99,10 @@ /***************************************/ static void DuplicateModifyCommand(void *,int,DATA_OBJECT_PTR); - static SYMBOL_HN *CheckDeftemplateAndSlotArguments(void *,char *,struct deftemplate **); + static SYMBOL_HN *CheckDeftemplateAndSlotArguments(void *,const char *,struct deftemplate **,int); #if (! RUN_TIME) && (! BLOAD_ONLY) - static struct expr *ModAndDupParse(void *,struct expr *,char *,char *); + static struct expr *ModAndDupParse(void *,struct expr *,const char *,const char *); static SYMBOL_HN *FindTemplateForFactAddress(SYMBOL_HN *,struct lhsParseNode *); #endif @@ -108,6 +138,12 @@ globle void DeftemplateFunctions( EnvDefineFunction2(theEnv,"deftemplate-slot-defaultp",'w',PTIEF DeftemplateSlotDefaultPFunction, "DeftemplateSlotDefaultPFunction","22w"); + EnvDefineFunction2(theEnv,"deftemplate-slot-facet-existp",'b',PTIEF DeftemplateSlotFacetExistPFunction, + "DeftemplateSlotFacetExistPFunction","33w"); + + EnvDefineFunction2(theEnv,"deftemplate-slot-facet-value",'u',PTIEF DeftemplateSlotFacetValueFunction, + "DeftemplateSlotFacetValueFunction","33w"); + #if (! BLOAD_ONLY) AddFunctionParser(theEnv,"modify",ModifyParse); AddFunctionParser(theEnv,"duplicate",DuplicateParse); @@ -115,7 +151,7 @@ globle void DeftemplateFunctions( FuncSeqOvlFlags(theEnv,"modify",FALSE,FALSE); FuncSeqOvlFlags(theEnv,"duplicate",FALSE,FALSE); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -156,7 +192,7 @@ static void DuplicateModifyCommand( int retractIt, DATA_OBJECT_PTR returnValue) { - long int factNum; + long long factNum; struct fact *oldFact, *newFact, *theFact; struct expr *testPtr; DATA_OBJECT computeResult; @@ -177,7 +213,9 @@ static void DuplicateModifyCommand( /*==================================================*/ testPtr = GetFirstArgument(); + EnvIncrementClearReadyLocks(theEnv); EvaluateExpression(theEnv,testPtr,&computeResult); + EnvDecrementClearReadyLocks(theEnv); /*==============================================================*/ /* If an integer is supplied, then treat it as a fact-index and */ @@ -207,7 +245,7 @@ static void DuplicateModifyCommand( if (oldFact == NULL) { char tempBuffer[20]; - sprintf(tempBuffer,"f-%ld",factNum); + gensprintf(tempBuffer,"f-%lld",factNum); CantFindItemErrorMessage(theEnv,"fact",tempBuffer); return; } @@ -326,8 +364,10 @@ static void DuplicateModifyCommand( /* Evaluate the expression to be stored in the slot. */ /*===================================================*/ + EnvIncrementClearReadyLocks(theEnv); EvaluateExpression(theEnv,testPtr->argList,&computeResult); SetEvaluationError(theEnv,FALSE); + EnvDecrementClearReadyLocks(theEnv); /*====================================================*/ /* If the expression evaluated to a multifield value, */ @@ -362,8 +402,10 @@ static void DuplicateModifyCommand( /* Determine the new value of the slot. */ /*======================================*/ + EnvIncrementClearReadyLocks(theEnv); StoreInMultifield(theEnv,&computeResult,testPtr->argList,FALSE); SetEvaluationError(theEnv,FALSE); + EnvDecrementClearReadyLocks(theEnv); /*=============================*/ /* Store the value in the slot */ @@ -394,6 +436,56 @@ static void DuplicateModifyCommand( } } + /*================================================*/ + /* Call registered modify notification functions. */ + /*================================================*/ + + if (retractIt && + (FactData(theEnv)->ListOfModifyFunctions != NULL)) + { + struct callFunctionItemWithArg *theModifyFunction; + struct fact *replacement = newFact; + + /*==================================================================*/ + /* If the fact already exists, determine if it's the fact we're */ + /* modifying. If so it will be retracted and reasserted. If not, */ + /* it will just be retracted, so pass NULL as the replacement fact. */ + /*==================================================================*/ + + if (! FactWillBeAsserted(theEnv,newFact)) + { + if (! MultifieldsEqual(&oldFact->theProposition, + &newFact->theProposition)) + { replacement = NULL; } + } + + /*=========================================================*/ + /* Preassign the factIndex and timeTag so the notification */ + /* function will see the correct values. */ + /*=========================================================*/ + + if (replacement != NULL) + { + replacement->factIndex = FactData(theEnv)->NextFactIndex; + replacement->factHeader.timeTag = DefruleData(theEnv)->CurrentEntityTimeTag; + } + + /*=========================================*/ + /* Call each modify notification function. */ + /*=========================================*/ + + for (theModifyFunction = FactData(theEnv)->ListOfModifyFunctions; + theModifyFunction != NULL; + theModifyFunction = theModifyFunction->next) + { + SetEnvironmentCallbackContext(theEnv,theModifyFunction->context); + if (theModifyFunction->environmentAware) + { ((void (*)(void *,void *,void *))(*theModifyFunction->func))(theEnv,oldFact,replacement); } + else + { ((void (*)(void *,void *))(*theModifyFunction->func))(oldFact,replacement); } + } + } + /*======================================*/ /* Perform the duplicate/modify action. */ /*======================================*/ @@ -415,7 +507,7 @@ static void DuplicateModifyCommand( return; } - + /****************************************************/ /* DeftemplateSlotNamesFunction: H/L access routine */ /* for the deftemplate-slot-names function. */ @@ -424,7 +516,7 @@ globle void DeftemplateSlotNamesFunction( void *theEnv, DATA_OBJECT *returnValue) { - char *deftemplateName; + const char *deftemplateName; struct deftemplate *theDeftemplate; /*=============================================*/ @@ -538,23 +630,23 @@ globle void *DeftemplateSlotDefaultPFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-existp",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-existp",&theDeftemplate,2); if (slotName == NULL) { return(EnvFalseSymbol(theEnv)); } /*===============================*/ /* Does the slot have a default? */ /*===============================*/ - + defaultType = EnvDeftemplateSlotDefaultP(theEnv,theDeftemplate,ValueToString(slotName)); - + if (defaultType == STATIC_DEFAULT) { return(EnvAddSymbol(theEnv,"static")); } else if (defaultType == DYNAMIC_DEFAULT) { return(EnvAddSymbol(theEnv,"dynamic")); } - - return(EnvFalseSymbol(theEnv)); + + return(EnvFalseSymbol(theEnv)); } /*************************************************/ @@ -564,12 +656,12 @@ globle void *DeftemplateSlotDefaultPFunction( globle int EnvDeftemplateSlotDefaultP( void *theEnv, void *vTheDeftemplate, - char *slotName) + const char *slotName) { short position; struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; struct templateSlot *theSlot; - + /*==================================================*/ /* Make sure the slot exists (the symbol implied is */ /* used for the implied slot of an ordered fact). */ @@ -594,7 +686,7 @@ globle int EnvDeftemplateSlotDefaultP( /* Otherwise search for the slot name in the */ /* list of slots defined for the deftemplate. */ /*============================================*/ - + else if ((theSlot = FindSlot(theDeftemplate,(SYMBOL_HN *) EnvAddSymbol(theEnv,slotName),&position)) == NULL) { SetEvaluationError(theEnv,TRUE); @@ -602,16 +694,16 @@ globle int EnvDeftemplateSlotDefaultP( ValueToString(theDeftemplate->header.name),FALSE); return(NO_DEFAULT); } - + /*======================================*/ /* Return the default type of the slot. */ /*======================================*/ - + if (theSlot->noDefault) { return(NO_DEFAULT); } else if (theSlot->defaultDynamic) { return(DYNAMIC_DEFAULT); } - + return(STATIC_DEFAULT); } @@ -629,8 +721,8 @@ globle void DeftemplateSlotDefaultValueFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-default-value",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-default-value",&theDeftemplate,2); if (slotName == NULL) { theValue->type = SYMBOL; @@ -641,7 +733,7 @@ globle void DeftemplateSlotDefaultValueFunction( /*=========================================*/ /* Get the deftemplate slot default value. */ /*=========================================*/ - + EnvDeftemplateSlotDefaultValue(theEnv,theDeftemplate,ValueToString(slotName),theValue); } @@ -652,21 +744,21 @@ globle void DeftemplateSlotDefaultValueFunction( globle intBool EnvDeftemplateSlotDefaultValue( void *theEnv, void *vTheDeftemplate, - char *slotName, + const char *slotName, DATA_OBJECT_PTR theValue) { short position; struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; struct templateSlot *theSlot; DATA_OBJECT tempDO; - + /*=============================================*/ /* Set up the default return value for errors. */ /*=============================================*/ SetpType(theValue,SYMBOL); SetpValue(theValue,EnvFalseSymbol(theEnv)); - + /*==================================================*/ /* Make sure the slot exists (the symbol implied is */ /* used for the implied slot of an ordered fact). */ @@ -703,11 +795,11 @@ globle intBool EnvDeftemplateSlotDefaultValue( ValueToString(theDeftemplate->header.name),FALSE); return(FALSE); } - + /*=======================================*/ /* Return the default value of the slot. */ /*=======================================*/ - + if (theSlot->noDefault) { SetpType(theValue,SYMBOL); @@ -740,8 +832,8 @@ globle void DeftemplateSlotCardinalityFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-cardinality",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-cardinality",&theDeftemplate,2); if (slotName == NULL) { EnvSetMultifieldErrorValue(theEnv,theValue); @@ -751,7 +843,7 @@ globle void DeftemplateSlotCardinalityFunction( /*=======================================*/ /* Get the deftemplate slot cardinality. */ /*=======================================*/ - + EnvDeftemplateSlotCardinality(theEnv,theDeftemplate,ValueToString(slotName),theValue); } @@ -762,7 +854,7 @@ globle void DeftemplateSlotCardinalityFunction( globle void EnvDeftemplateSlotCardinality( void *theEnv, void *vTheDeftemplate, - char *slotName, + const char *slotName, DATA_OBJECT *result) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; @@ -789,7 +881,7 @@ globle void EnvDeftemplateSlotCardinality( return; } else - { + { EnvSetMultifieldErrorValue(theEnv,result); SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, @@ -811,22 +903,22 @@ globle void EnvDeftemplateSlotCardinality( ValueToString(theDeftemplate->header.name),FALSE); return; } - + /*=====================================*/ /* Return the cardinality of the slot. */ /*=====================================*/ - + if (theSlot->multislot == 0) { EnvSetMultifieldErrorValue(theEnv,result); return; } - + result->type = MULTIFIELD; result->begin = 0; result->end = 1; result->value = EnvCreateMultifield(theEnv,2L); - + if (theSlot->constraints != NULL) { SetMFType(result->value,1,theSlot->constraints->minFields->type); @@ -857,8 +949,8 @@ globle void DeftemplateSlotAllowedValuesFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-allowed-values",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-allowed-values",&theDeftemplate,2); if (slotName == NULL) { EnvSetMultifieldErrorValue(theEnv,theValue); @@ -868,7 +960,7 @@ globle void DeftemplateSlotAllowedValuesFunction( /*==========================================*/ /* Get the deftemplate slot allowed values. */ /*==========================================*/ - + EnvDeftemplateSlotAllowedValues(theEnv,theDeftemplate,ValueToString(slotName),theValue); } @@ -879,7 +971,7 @@ globle void DeftemplateSlotAllowedValuesFunction( globle void EnvDeftemplateSlotAllowedValues( void *theEnv, void *vTheDeftemplate, - char *slotName, + const char *slotName, DATA_OBJECT *result) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; @@ -902,7 +994,7 @@ globle void EnvDeftemplateSlotAllowedValues( return; } else - { + { EnvSetMultifieldErrorValue(theEnv,result); SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, @@ -924,24 +1016,24 @@ globle void EnvDeftemplateSlotAllowedValues( ValueToString(theDeftemplate->header.name),FALSE); return; } - + /*========================================*/ /* Return the allowed values of the slot. */ /*========================================*/ - + if ((theSlot->constraints != NULL) ? (theSlot->constraints->restrictionList == NULL) : TRUE) { result->type = SYMBOL; result->value = EnvFalseSymbol(theEnv); return; } - + result->type = MULTIFIELD; - result->begin = 0; + result->begin = 0; result->end = ExpressionSize(theSlot->constraints->restrictionList) - 1; result->value = EnvCreateMultifield(theEnv,(unsigned long) (result->end + 1)); i = 1; - + theExp = theSlot->constraints->restrictionList; while (theExp != NULL) { @@ -966,8 +1058,8 @@ globle void DeftemplateSlotRangeFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-range",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-range",&theDeftemplate,2); if (slotName == NULL) { EnvSetMultifieldErrorValue(theEnv,theValue); @@ -977,7 +1069,7 @@ globle void DeftemplateSlotRangeFunction( /*=================================*/ /* Get the deftemplate slot range. */ /*=================================*/ - + EnvDeftemplateSlotRange(theEnv,theDeftemplate,ValueToString(slotName),theValue); } @@ -988,7 +1080,7 @@ globle void DeftemplateSlotRangeFunction( globle void EnvDeftemplateSlotRange( void *theEnv, void *vTheDeftemplate, - char *slotName, + const char *slotName, DATA_OBJECT *result) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; @@ -1015,7 +1107,7 @@ globle void EnvDeftemplateSlotRange( return; } else - { + { EnvSetMultifieldErrorValue(theEnv,result); SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, @@ -1037,11 +1129,11 @@ globle void EnvDeftemplateSlotRange( ValueToString(theDeftemplate->header.name),FALSE); return; } - + /*===============================*/ /* Return the range of the slot. */ /*===============================*/ - + if ((theSlot->constraints == NULL) ? FALSE : (theSlot->constraints->anyAllowed || theSlot->constraints->floatsAllowed || theSlot->constraints->integersAllowed)) @@ -1062,7 +1154,7 @@ globle void EnvDeftemplateSlotRange( return; } } - + /****************************************************/ /* DeftemplateSlotTypesFunction: H/L access routine */ /* for the deftemplate-slot-types function. */ @@ -1077,8 +1169,8 @@ globle void DeftemplateSlotTypesFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-types",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-types",&theDeftemplate,2); if (slotName == NULL) { EnvSetMultifieldErrorValue(theEnv,theValue); @@ -1088,7 +1180,7 @@ globle void DeftemplateSlotTypesFunction( /*=================================*/ /* Get the deftemplate slot types. */ /*=================================*/ - + EnvDeftemplateSlotTypes(theEnv,theDeftemplate,ValueToString(slotName),theValue); } @@ -1099,7 +1191,7 @@ globle void DeftemplateSlotTypesFunction( globle void EnvDeftemplateSlotTypes( void *theEnv, void *vTheDeftemplate, - char *slotName, + const char *slotName, DATA_OBJECT *result) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; @@ -1115,7 +1207,7 @@ globle void EnvDeftemplateSlotTypes( if (theDeftemplate->implied) { if (strcmp(slotName,"implied") != 0) - { + { EnvSetMultifieldErrorValue(theEnv,result); SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, @@ -1143,7 +1235,7 @@ globle void EnvDeftemplateSlotTypes( /* there is no type restriction, then all types */ /* are allowed for the slot. */ /*==============================================*/ - + if ((theDeftemplate->implied) || ((theSlot->constraints != NULL) ? theSlot->constraints->anyAllowed : TRUE)) { @@ -1154,11 +1246,11 @@ globle void EnvDeftemplateSlotTypes( #endif allTypes = TRUE; } - + /*==============================================*/ /* Otherwise count the number of types allowed. */ /*==============================================*/ - + else { numTypes = theSlot->constraints->symbolsAllowed + @@ -1170,11 +1262,11 @@ globle void EnvDeftemplateSlotTypes( theSlot->constraints->externalAddressesAllowed + theSlot->constraints->factAddressesAllowed; } - + /*========================================*/ /* Return the allowed types for the slot. */ /*========================================*/ - + result->type = MULTIFIELD; result->begin = 0; result->end = numTypes - 1; @@ -1187,51 +1279,51 @@ globle void EnvDeftemplateSlotTypes( SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"FLOAT")); } - + if (allTypes || theSlot->constraints->integersAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"INTEGER")); } - + if (allTypes || theSlot->constraints->symbolsAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"SYMBOL")); } - + if (allTypes || theSlot->constraints->stringsAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"STRING")); } - + if (allTypes || theSlot->constraints->externalAddressesAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"EXTERNAL-ADDRESS")); } - + if (allTypes || theSlot->constraints->factAddressesAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"FACT-ADDRESS")); } - + #if OBJECT_SYSTEM if (allTypes || theSlot->constraints->instanceAddressesAllowed) { SetMFType(result->value,i,SYMBOL); SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"INSTANCE-ADDRESS")); } - + if (allTypes || theSlot->constraints->instanceNamesAllowed) - { + { SetMFType(result->value,i,SYMBOL); - SetMFValue(result->value,i++,EnvAddSymbol(theEnv,"INSTANCE-NAME")); + SetMFValue(result->value,i,EnvAddSymbol(theEnv,"INSTANCE-NAME")); } #endif - } + } /*****************************************************/ /* DeftemplateSlotMultiPFunction: H/L access routine */ @@ -1246,18 +1338,18 @@ globle int DeftemplateSlotMultiPFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-multip",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-multip",&theDeftemplate,2); if (slotName == NULL) { return(FALSE); } /*================================*/ /* Is the slot a multifield slot? */ /*================================*/ - + return EnvDeftemplateSlotMultiP(theEnv,theDeftemplate,ValueToString(slotName)); } - + /***********************************************/ /* EnvDeftemplateSlotMultiP: C access routine */ /* for the deftemplate-slot-multip function. */ @@ -1265,7 +1357,7 @@ globle int DeftemplateSlotMultiPFunction( globle int EnvDeftemplateSlotMultiP( void *theEnv, void *vTheDeftemplate, - char *slotName) + const char *slotName) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; short position; @@ -1285,7 +1377,7 @@ globle int EnvDeftemplateSlotMultiP( SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, ValueToString(theDeftemplate->header.name),FALSE); - return(FALSE); + return(FALSE); } } @@ -1295,7 +1387,7 @@ globle int EnvDeftemplateSlotMultiP( /*============================================*/ else if ((theSlot = FindSlot(theDeftemplate,(SYMBOL_HN *) EnvAddSymbol(theEnv,slotName),&position)) == NULL) - { + { SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, ValueToString(theDeftemplate->header.name),FALSE); @@ -1305,9 +1397,9 @@ globle int EnvDeftemplateSlotMultiP( /*================================*/ /* Is the slot a multifield slot? */ /*================================*/ - - return(theSlot->multislot); - } + + return(theSlot->multislot); + } /******************************************************/ /* DeftemplateSlotSinglePFunction: H/L access routine */ @@ -1322,15 +1414,15 @@ globle int DeftemplateSlotSinglePFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-singlep",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-singlep",&theDeftemplate,2); if (slotName == NULL) { return(FALSE); } /*==================================*/ /* Is the slot a single field slot? */ /*==================================*/ - + return EnvDeftemplateSlotSingleP(theEnv,theDeftemplate,ValueToString(slotName)); } @@ -1341,7 +1433,7 @@ globle int DeftemplateSlotSinglePFunction( globle int EnvDeftemplateSlotSingleP( void *theEnv, void *vTheDeftemplate, - char *slotName) + const char *slotName) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; short position; @@ -1361,7 +1453,7 @@ globle int EnvDeftemplateSlotSingleP( SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, ValueToString(theDeftemplate->header.name),FALSE); - return(FALSE); + return(FALSE); } } @@ -1375,15 +1467,15 @@ globle int EnvDeftemplateSlotSingleP( SetEvaluationError(theEnv,TRUE); InvalidDeftemplateSlotMessage(theEnv,slotName, ValueToString(theDeftemplate->header.name),FALSE); - return(FALSE); + return(FALSE); } /*==================================*/ /* Is the slot a single field slot? */ /*==================================*/ - return(! theSlot->multislot); - } + return(! theSlot->multislot); + } /*****************************************************/ /* DeftemplateSlotExistPFunction: H/L access routine */ @@ -1398,15 +1490,15 @@ globle int DeftemplateSlotExistPFunction( /*===================================================*/ /* Retrieve the deftemplate and slot name arguments. */ /*===================================================*/ - - slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-existp",&theDeftemplate); + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-existp",&theDeftemplate,2); if (slotName == NULL) { return(FALSE); } /*======================*/ /* Does the slot exist? */ /*======================*/ - + return EnvDeftemplateSlotExistP(theEnv,theDeftemplate,ValueToString(slotName)); } @@ -1417,7 +1509,7 @@ globle int DeftemplateSlotExistPFunction( globle int EnvDeftemplateSlotExistP( void *theEnv, void *vTheDeftemplate, - char *slotName) + const char *slotName) { struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; short position; @@ -1439,34 +1531,222 @@ globle int EnvDeftemplateSlotExistP( /* Otherwise search for the slot name in the */ /* list of slots defined for the deftemplate. */ /*============================================*/ - + else if (FindSlot(theDeftemplate,(SYMBOL_HN *) EnvAddSymbol(theEnv,slotName),&position) == NULL) { return(FALSE); } /*==================*/ /* The slot exists. */ /*==================*/ - - return(TRUE); - } - + + return(TRUE); + } + +/**********************************************************/ +/* DeftemplateSlotFacetExistPFunction: H/L access routine */ +/* for the deftemplate-slot-facet-existp function. */ +/**********************************************************/ +globle int DeftemplateSlotFacetExistPFunction( + void *theEnv) + { + struct deftemplate *theDeftemplate; + SYMBOL_HN *slotName; + DATA_OBJECT facetName; + + /*===================================================*/ + /* Retrieve the deftemplate and slot name arguments. */ + /*===================================================*/ + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-facet-existp",&theDeftemplate,3); + if (slotName == NULL) + { return(FALSE); } + + /*============================*/ + /* Get the name of the facet. */ + /*============================*/ + + if (EnvArgTypeCheck(theEnv,"deftemplate-slot-facet-existp",3,SYMBOL,&facetName) == FALSE) + { return(FALSE); } + + /*======================*/ + /* Does the slot exist? */ + /*======================*/ + + return EnvDeftemplateSlotFacetExistP(theEnv,theDeftemplate,ValueToString(slotName),DOToString(facetName)); + } + +/*****************************************************/ +/* EnvDeftemplateSlotFacetExistP: C access routine */ +/* for the deftemplate-slot-facet-existp function. */ +/*****************************************************/ +globle int EnvDeftemplateSlotFacetExistP( + void *theEnv, + void *vTheDeftemplate, + const char *slotName, + const char *facetName) + { + struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; + short position; + struct templateSlot *theSlot; + SYMBOL_HN *facetHN; + struct expr *tempFacet; + + /*=================================================*/ + /* An implied deftemplate doesn't have any facets. */ + /*=================================================*/ + + if (theDeftemplate->implied) + { return(FALSE); } + + /*============================================*/ + /* Otherwise search for the slot name in the */ + /* list of slots defined for the deftemplate. */ + /*============================================*/ + + else if ((theSlot = FindSlot(theDeftemplate,(SYMBOL_HN *) EnvAddSymbol(theEnv,slotName),&position)) == NULL) + { return(FALSE); } + + /*=======================*/ + /* Search for the facet. */ + /*=======================*/ + + facetHN = FindSymbolHN(theEnv,facetName); + for (tempFacet = theSlot->facetList; + tempFacet != NULL; + tempFacet = tempFacet->nextArg) + { + if (tempFacet->value == facetHN) + { return(TRUE); } + } + + /*===========================*/ + /* The facet does not exist. */ + /*===========================*/ + + return(FALSE); + } + +/*********************************************************/ +/* DeftemplateSlotFacetValueFunction: H/L access routine */ +/* for the deftemplate-slot-facet-value function. */ +/*********************************************************/ +globle void DeftemplateSlotFacetValueFunction( + void *theEnv, + DATA_OBJECT *returnValue) + { + struct deftemplate *theDeftemplate; + SYMBOL_HN *slotName; + DATA_OBJECT facetName; + + /*=============================================*/ + /* Set up the default return value for errors. */ + /*=============================================*/ + + returnValue->type = SYMBOL; + returnValue->value = EnvFalseSymbol(theEnv); + + /*===================================================*/ + /* Retrieve the deftemplate and slot name arguments. */ + /*===================================================*/ + + slotName = CheckDeftemplateAndSlotArguments(theEnv,"deftemplate-slot-facet-existp",&theDeftemplate,3); + if (slotName == NULL) + { return; } + + /*============================*/ + /* Get the name of the facet. */ + /*============================*/ + + if (EnvArgTypeCheck(theEnv,"deftemplate-slot-facet-existp",3,SYMBOL,&facetName) == FALSE) + { return; } + + /*===========================*/ + /* Retrieve the facet value. */ + /*===========================*/ + + EnvDeftemplateSlotFacetValue(theEnv,theDeftemplate,ValueToString(slotName),DOToString(facetName),returnValue); + } + +/****************************************************/ +/* EnvDeftemplateSlotFacetValue: C access routine */ +/* for the deftemplate-slot-facet-value function. */ +/****************************************************/ +globle int EnvDeftemplateSlotFacetValue( + void *theEnv, + void *vTheDeftemplate, + const char *slotName, + const char *facetName, + DATA_OBJECT *rv) + { + struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate; + short position; + struct templateSlot *theSlot; + SYMBOL_HN *facetHN; + struct expr *tempFacet; + + /*=================================================*/ + /* An implied deftemplate doesn't have any facets. */ + /*=================================================*/ + + if (theDeftemplate->implied) + { return(FALSE); } + + /*============================================*/ + /* Otherwise search for the slot name in the */ + /* list of slots defined for the deftemplate. */ + /*============================================*/ + + else if ((theSlot = FindSlot(theDeftemplate,(SYMBOL_HN *) EnvAddSymbol(theEnv,slotName),&position)) == NULL) + { return(FALSE); } + + /*=======================*/ + /* Search for the facet. */ + /*=======================*/ + + facetHN = FindSymbolHN(theEnv,facetName); + for (tempFacet = theSlot->facetList; + tempFacet != NULL; + tempFacet = tempFacet->nextArg) + { + if (tempFacet->value == facetHN) + { + EvaluateExpression(theEnv,tempFacet->argList,rv); + return(TRUE); + } + } + + /*===========================*/ + /* The facet does not exist. */ + /*===========================*/ + + return(FALSE); + } + /************************************************************/ /* CheckDeftemplateAndSlotArguments: Checks the deftemplate */ /* and slot arguments for various functions. */ /************************************************************/ -globle SYMBOL_HN *CheckDeftemplateAndSlotArguments( +static SYMBOL_HN *CheckDeftemplateAndSlotArguments( void *theEnv, - char *functionName, - struct deftemplate **theDeftemplate) + const char *functionName, + struct deftemplate **theDeftemplate, + int expectedArgs) { DATA_OBJECT tempDO; - char *deftemplateName; + const char *deftemplateName; /*============================================*/ /* Check for the correct number of arguments. */ /*============================================*/ - if (EnvArgCountCheck(theEnv,functionName,EXACTLY,2) == -1) + if (EnvArgCountCheck(theEnv,functionName,EXACTLY,expectedArgs) == -1) + { return(NULL); } + + /*=====================================*/ + /* There must be at least 2 arguments. */ + /*=====================================*/ + + if (EnvArgCountCheck(theEnv,functionName,AT_LEAST,2) == -1) { return(NULL); } /*=======================================*/ @@ -1480,7 +1760,7 @@ globle SYMBOL_HN *CheckDeftemplateAndSlotArguments( ExpectedTypeError1(theEnv,functionName,1,"deftemplate name"); return(NULL); } - + deftemplateName = DOToString(tempDO); *theDeftemplate = (struct deftemplate *) EnvFindDeftemplate(theEnv,deftemplateName); @@ -1496,10 +1776,10 @@ globle SYMBOL_HN *CheckDeftemplateAndSlotArguments( if (EnvArgTypeCheck(theEnv,functionName,2,SYMBOL,&tempDO) == FALSE) { return(NULL); } - + return((SYMBOL_HN *) GetValue(tempDO)); } - + #if (! RUN_TIME) && (! BLOAD_ONLY) /***************************************************************/ @@ -1515,7 +1795,7 @@ globle SYMBOL_HN *CheckDeftemplateAndSlotArguments( globle intBool UpdateModifyDuplicate( void *theEnv, struct expr *top, - char *name, + const char *name, void *vTheLHS) { struct expr *functionArgs, *tempArg; @@ -1609,7 +1889,7 @@ globle intBool UpdateModifyDuplicate( /*=============================================*/ tempArg->type = INTEGER; - tempArg->value = (void *) EnvAddLong(theEnv,(long) (FindSlotPosition(theDeftemplate,(SYMBOL_HN *) tempArg->value) - 1)); + tempArg->value = (void *) EnvAddLong(theEnv,(long long) (FindSlotPosition(theDeftemplate,(SYMBOL_HN *) tempArg->value) - 1)); tempArg = tempArg->nextArg; } @@ -1675,7 +1955,7 @@ static SYMBOL_HN *FindTemplateForFactAddress( globle struct expr *ModifyParse( void *theEnv, struct expr *top, - char *logicalName) + const char *logicalName) { return(ModAndDupParse(theEnv,top,logicalName,"modify")); } @@ -1686,7 +1966,7 @@ globle struct expr *ModifyParse( globle struct expr *DuplicateParse( void *theEnv, struct expr *top, - char *logicalName) + const char *logicalName) { return(ModAndDupParse(theEnv,top,logicalName,"duplicate")); } @@ -1697,8 +1977,8 @@ globle struct expr *DuplicateParse( static struct expr *ModAndDupParse( void *theEnv, struct expr *top, - char *logicalName, - char *name) + const char *logicalName, + const char *name) { int error = FALSE; struct token theToken; @@ -1861,5 +2141,88 @@ static struct expr *ModAndDupParse( #endif /* (! RUN_TIME) && (! BLOAD_ONLY) */ +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void DeftemplateSlotNames( + void *vTheDeftemplate, + DATA_OBJECT *returnValue) + { + EnvDeftemplateSlotNames(GetCurrentEnvironment(),vTheDeftemplate,returnValue); + } + +globle intBool DeftemplateSlotDefaultValue( + void *vTheDeftemplate, + const char *slotName, + DATA_OBJECT_PTR theValue) + { + return EnvDeftemplateSlotDefaultValue(GetCurrentEnvironment(),vTheDeftemplate,slotName,theValue); + } + +globle void DeftemplateSlotCardinality( + void *vTheDeftemplate, + const char *slotName, + DATA_OBJECT *result) + { + EnvDeftemplateSlotCardinality(GetCurrentEnvironment(),vTheDeftemplate,slotName,result); + } + +globle void DeftemplateSlotAllowedValues( + void *vTheDeftemplate, + const char *slotName, + DATA_OBJECT *result) + { + EnvDeftemplateSlotAllowedValues(GetCurrentEnvironment(),vTheDeftemplate,slotName,result); + } + +globle void DeftemplateSlotRange( + void *vTheDeftemplate, + const char *slotName, + DATA_OBJECT *result) + { + EnvDeftemplateSlotRange(GetCurrentEnvironment(),vTheDeftemplate,slotName,result); + } + +globle void DeftemplateSlotTypes( + void *vTheDeftemplate, + const char *slotName, + DATA_OBJECT *result) + { + EnvDeftemplateSlotTypes(GetCurrentEnvironment(),vTheDeftemplate,slotName,result); + } + +globle int DeftemplateSlotMultiP( + void *vTheDeftemplate, + const char *slotName) + { + return EnvDeftemplateSlotMultiP(GetCurrentEnvironment(),vTheDeftemplate,slotName); + } + +globle int DeftemplateSlotSingleP( + void *vTheDeftemplate, + const char *slotName) + { + return EnvDeftemplateSlotSingleP(GetCurrentEnvironment(),vTheDeftemplate,slotName); + } + +globle int DeftemplateSlotExistP( + void *vTheDeftemplate, + const char *slotName) + { + return EnvDeftemplateSlotExistP(GetCurrentEnvironment(),vTheDeftemplate,slotName); + } + +globle int DeftemplateSlotDefaultP( + void *vTheDeftemplate, + const char *slotName) + { + return EnvDeftemplateSlotDefaultP(GetCurrentEnvironment(),vTheDeftemplate,slotName); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/tmpltfun.h b/src/tmpltfun.h index dc4a8c3..f5714f8 100644 --- a/src/tmpltfun.h +++ b/src/tmpltfun.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 07/01/05 */ + /* CLIPS Version 6.30 08/20/14 */ /* */ /* DEFTEMPLATE FUNCTION HEADER FILE */ /*******************************************************/ @@ -15,6 +15,9 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ +/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */ +/* */ /* 6.24: Added deftemplate-slot-names, */ /* deftemplate-slot-default-value, */ /* deftemplate-slot-cardinality, */ @@ -28,6 +31,30 @@ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for deftemplate slot facets. */ +/* */ +/* Added deftemplate-slot-facet-existp and */ +/* deftemplate-slot-facet-value functions. */ +/* */ +/* Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Support for modify callback function. */ +/* */ +/* Added additional argument to function */ +/* CheckDeftemplateAndSlotArguments to specify */ +/* the expected number of arguments. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ +/* Added code to prevent a clear command from */ +/* being executed during fact assertions via */ +/* Increment/DecrementClearReadyLocks API. */ +/* */ /*************************************************************/ #ifndef _H_tmpltfun @@ -50,10 +77,6 @@ #include "tmpltdef.h" #endif -#define NO_DEFAULT 0 -#define STATIC_DEFAULT 1 -#define DYNAMIC_DEFAULT 2 - #ifdef LOCALE #undef LOCALE #endif @@ -64,58 +87,53 @@ #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DeftemplateSlotNames(theEnv,a,b) EnvDeftemplateSlotNames(theEnv,a,b) -#define DeftemplateSlotDefaultValue(theEnv,a,b,c) EnvDeftemplateSlotDefaultValue(theEnv,a,b,c) -#define DeftemplateSlotCardinality(theEnv,a,b,c) EnvDeftemplateSlotCardinality(theEnv,a,b,c) -#define DeftemplateSlotAllowedValues(theEnv,a,b,c) EnvDeftemplateSlotAllowedValues(theEnv,a,b,c) -#define DeftemplateSlotRange(theEnv,a,b,c) EnvDeftemplateSlotRange(theEnv,a,b,c) -#define DeftemplateSlotTypes(theEnv,a,b,c) EnvDeftemplateSlotTypes(theEnv,a,b,c) -#define DeftemplateSlotMultiP(theEnv,a,b) EnvDeftemplateSlotMultiP(theEnv,a,b) -#define DeftemplateSlotSingleP(theEnv,a,b) EnvDeftemplateSlotSingleP(theEnv,a,b) -#define DeftemplateSlotExistP(theEnv,a,b) EnvDeftemplateSlotExistP(theEnv,a,b) -#define DeftemplateSlotDefaultP(theEnv,a,b) EnvDeftemplateSlotDefaultP(theEnv,a,b) -#else -#define DeftemplateSlotNames(a,b) EnvDeftemplateSlotNames(GetCurrentEnvironment(),a,b) -#define DeftemplateSlotDefaultValue(a,b,c) EnvDeftemplateSlotDefaultValue(GetCurrentEnvironment(),a,b,c) -#define DeftemplateSlotCardinality(a,b,c) EnvDeftemplateSlotCardinality(GetCurrentEnvironment(),a,b,c) -#define DeftemplateSlotAllowedValues(a,b,c) EnvDeftemplateSlotAllowedValues(GetCurrentEnvironment(),a,b,c) -#define DeftemplateSlotRange(a,b,c) EnvDeftemplateSlotRange(GetCurrentEnvironment(),a,b,c) -#define DeftemplateSlotTypes(a,b,c) EnvDeftemplateSlotTypes(GetCurrentEnvironment(),a,b,c) -#define DeftemplateSlotMultiP(a,b) EnvDeftemplateSlotMultiP(GetCurrentEnvironment(),a,b) -#define DeftemplateSlotSingleP(a,b) EnvDeftemplateSlotSingleP(GetCurrentEnvironment(),a,b) -#define DeftemplateSlotExistP(a,b) EnvDeftemplateSlotExistP(GetCurrentEnvironment(),a,b) -#define DeftemplateSlotDefaultP(a,b) EnvDeftemplateSlotDefaultP(GetCurrentEnvironment(),a,b) -#endif - - LOCALE intBool UpdateModifyDuplicate(void *,struct expr *,char *,void *); - LOCALE struct expr *ModifyParse(void *,struct expr *,char *); - LOCALE struct expr *DuplicateParse(void *,struct expr *,char *); + LOCALE intBool UpdateModifyDuplicate(void *,struct expr *,const char *,void *); + LOCALE struct expr *ModifyParse(void *,struct expr *,const char *); + LOCALE struct expr *DuplicateParse(void *,struct expr *,const char *); LOCALE void DeftemplateFunctions( void *); LOCALE void ModifyCommand(void *,DATA_OBJECT_PTR); LOCALE void DuplicateCommand(void *,DATA_OBJECT_PTR); LOCALE void DeftemplateSlotNamesFunction(void *,DATA_OBJECT *); LOCALE void EnvDeftemplateSlotNames(void *,void *,DATA_OBJECT *); LOCALE void DeftemplateSlotDefaultValueFunction(void *,DATA_OBJECT *); - LOCALE intBool EnvDeftemplateSlotDefaultValue(void *,void *,char *,DATA_OBJECT *); + LOCALE intBool EnvDeftemplateSlotDefaultValue(void *,void *,const char *,DATA_OBJECT *); LOCALE void DeftemplateSlotCardinalityFunction(void *,DATA_OBJECT *); - LOCALE void EnvDeftemplateSlotCardinality(void *,void *,char *,DATA_OBJECT *); + LOCALE void EnvDeftemplateSlotCardinality(void *,void *,const char *,DATA_OBJECT *); LOCALE void DeftemplateSlotAllowedValuesFunction(void *,DATA_OBJECT *); - LOCALE void EnvDeftemplateSlotAllowedValues(void *,void *,char *,DATA_OBJECT *); + LOCALE void EnvDeftemplateSlotAllowedValues(void *,void *,const char *,DATA_OBJECT *); LOCALE void DeftemplateSlotRangeFunction(void *,DATA_OBJECT *); - LOCALE void EnvDeftemplateSlotRange(void *,void *,char *,DATA_OBJECT *); + LOCALE void EnvDeftemplateSlotRange(void *,void *,const char *,DATA_OBJECT *); LOCALE void DeftemplateSlotTypesFunction(void *,DATA_OBJECT *); - LOCALE void EnvDeftemplateSlotTypes(void *,void *,char *,DATA_OBJECT *); + LOCALE void EnvDeftemplateSlotTypes(void *,void *,const char *,DATA_OBJECT *); LOCALE int DeftemplateSlotMultiPFunction(void *); - LOCALE int EnvDeftemplateSlotMultiP(void *,void *,char *); + LOCALE int EnvDeftemplateSlotMultiP(void *,void *,const char *); LOCALE int DeftemplateSlotSinglePFunction(void *); - LOCALE int EnvDeftemplateSlotSingleP(void *,void *,char *); + LOCALE int EnvDeftemplateSlotSingleP(void *,void *,const char *); LOCALE int DeftemplateSlotExistPFunction(void *); - LOCALE int EnvDeftemplateSlotExistP(void *,void *,char *); + LOCALE int EnvDeftemplateSlotExistP(void *,void *,const char *); LOCALE void *DeftemplateSlotDefaultPFunction(void *); - LOCALE int EnvDeftemplateSlotDefaultP(void *,void *,char *); + LOCALE int EnvDeftemplateSlotDefaultP(void *,void *,const char *); + LOCALE int DeftemplateSlotFacetExistPFunction(void *); + LOCALE int EnvDeftemplateSlotFacetExistP(void *,void *,const char *,const char *); + LOCALE void DeftemplateSlotFacetValueFunction(void *,DATA_OBJECT *); + LOCALE int EnvDeftemplateSlotFacetValue(void *,void *,const char *,const char *,DATA_OBJECT *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void DeftemplateSlotNames(void *,DATA_OBJECT *); + LOCALE intBool DeftemplateSlotDefaultValue(void *,const char *,DATA_OBJECT_PTR); + LOCALE void DeftemplateSlotCardinality(void *,const char *,DATA_OBJECT *); + LOCALE void DeftemplateSlotAllowedValues(void *,const char *,DATA_OBJECT *); + LOCALE void DeftemplateSlotRange(void *,const char *,DATA_OBJECT *); + LOCALE void DeftemplateSlotTypes(void *,const char *,DATA_OBJECT *); + LOCALE int DeftemplateSlotMultiP(void *,const char *); + LOCALE int DeftemplateSlotSingleP(void *,const char *); + LOCALE int DeftemplateSlotExistP(void *,const char *); + LOCALE int DeftemplateSlotDefaultP(void *,const char *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_tmpltfun */ diff --git a/src/tmpltlhs.c b/src/tmpltlhs.c index a065162..79b4a0a 100644 --- a/src/tmpltlhs.c +++ b/src/tmpltlhs.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE LHS MODULE */ /*******************************************************/ @@ -18,6 +18,11 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Support for rete network exists node. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _TMPLTLHS_SOURCE_ @@ -52,8 +57,8 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct lhsParseNode *GetLHSSlots(void *,char *,struct token *,struct deftemplate *,int *); - static struct lhsParseNode *GetSingleLHSSlot(void *,char *,struct token *, + static struct lhsParseNode *GetLHSSlots(void *,const char *,struct token *,struct deftemplate *,int *); + static struct lhsParseNode *GetSingleLHSSlot(void *,const char *,struct token *, struct templateSlot *,int *,short); static intBool MultiplyDefinedLHSSlots(void *,struct lhsParseNode *,SYMBOL_HN *); @@ -63,13 +68,13 @@ /*********************************************/ globle struct lhsParseNode *DeftemplateLHSParse( void *theEnv, - char *readSource, + const char *readSource, struct deftemplate *theDeftemplate) { struct lhsParseNode *head, *firstSlot; struct token theToken; int error; - + /*===============================================================*/ /* Make sure the deftemplate name is not connected to subfields. */ /*===============================================================*/ @@ -88,11 +93,13 @@ globle struct lhsParseNode *DeftemplateLHSParse( head = GetLHSParseNode(theEnv); head->type = SF_WILDCARD; head->negated = FALSE; + head->exists = FALSE; head->index = 0; head->slotNumber = 1; head->bottom = GetLHSParseNode(theEnv); head->bottom->type = SYMBOL; head->bottom->negated = FALSE; + head->bottom->exists = FALSE; head->bottom->value = (void *) theDeftemplate->header.name; /*==========================================*/ @@ -122,7 +129,7 @@ globle struct lhsParseNode *DeftemplateLHSParse( /******************************************/ static struct lhsParseNode *GetLHSSlots( void *theEnv, - char *readSource, + const char *readSource, struct token *tempToken, struct deftemplate *theDeftemplate, int *error) @@ -236,7 +243,7 @@ static struct lhsParseNode *GetLHSSlots( /*****************************************************/ static struct lhsParseNode *GetSingleLHSSlot( void *theEnv, - char *readSource, + const char *readSource, struct token *tempToken, struct templateSlot *slotPtr, int *error, diff --git a/src/tmpltlhs.h b/src/tmpltlhs.h index 6ecb4fc..a6daa4f 100644 --- a/src/tmpltlhs.h +++ b/src/tmpltlhs.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE LHS HEADER FILE */ /*******************************************************/ @@ -16,6 +16,13 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Renamed BOOLEAN macro type to intBool. */ +/* */ +/* 6.30: Support for rete network exists node. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_tmpltlhs @@ -39,9 +46,9 @@ #define LOCALE extern #endif - LOCALE struct lhsParseNode *DeftemplateLHSParse(void *,char *,struct deftemplate *); + LOCALE struct lhsParseNode *DeftemplateLHSParse(void *,const char *,struct deftemplate *); -#endif +#endif /* _H_tmpltlhs */ diff --git a/src/tmpltpsr.c b/src/tmpltpsr.c index b1027c6..dc0af78 100644 --- a/src/tmpltpsr.c +++ b/src/tmpltpsr.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.23 01/31/05 */ + /* CLIPS Version 6.30 01/25/15 */ /* */ /* DEFTEMPLATE PARSER MODULE */ /*******************************************************/ @@ -15,9 +15,25 @@ /* Contributing Programmer(s): */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Changed find construct functionality so that */ +/* imported modules are search when locating a */ +/* named construct. */ +/* */ /*************************************************************/ #define _TMPLTPSR_SOURCE_ @@ -60,9 +76,10 @@ /***************************************/ #if (! RUN_TIME) && (! BLOAD_ONLY) - static struct templateSlot *SlotDeclarations(void *,char *,struct token *); - static struct templateSlot *ParseSlot(void *,char *,struct token *,struct templateSlot *); - static struct templateSlot *DefinedSlots(void *,char *,SYMBOL_HN *,int,struct token *); + static struct templateSlot *SlotDeclarations(void *,const char *,struct token *); + static struct templateSlot *ParseSlot(void *,const char *,struct token *,struct templateSlot *); + static struct templateSlot *DefinedSlots(void *,const char *,SYMBOL_HN *,int,struct token *); + static intBool ParseFacetAttribute(void *,const char *,struct templateSlot *,intBool); #endif /*******************************************************/ @@ -70,12 +87,8 @@ /*******************************************************/ globle int ParseDeftemplate( void *theEnv, - char *readSource) + const char *readSource) { -#if (MAC_MCW || IBM_MCW) && (RUN_TIME || BLOAD_ONLY) -#pragma unused(readSource) -#endif - #if (! RUN_TIME) && (! BLOAD_ONLY) SYMBOL_HN *deftemplateName; struct deftemplate *newDeftemplate; @@ -112,8 +125,8 @@ globle int ParseDeftemplate( #endif deftemplateName = GetConstructNameAndComment(theEnv,readSource,&inputToken,"deftemplate", - EnvFindDeftemplate,EnvUndeftemplate,"%", - TRUE,TRUE,TRUE); + EnvFindDeftemplateInModule,EnvUndeftemplate,"%", + TRUE,TRUE,TRUE,FALSE); if (deftemplateName == NULL) return(TRUE); if (ReservedPatternSymbol(theEnv,ValueToString(deftemplateName),"deftemplate")) @@ -197,7 +210,7 @@ globle int ParseDeftemplate( InstallDeftemplate(theEnv,newDeftemplate); #else -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif #endif @@ -229,6 +242,9 @@ globle void InstallDeftemplate( tempExpr = AddHashedExpression(theEnv,slotPtr->defaultList); ReturnExpression(theEnv,slotPtr->defaultList); slotPtr->defaultList = tempExpr; + tempExpr = AddHashedExpression(theEnv,slotPtr->facetList); + ReturnExpression(theEnv,slotPtr->facetList); + slotPtr->facetList = tempExpr; slotPtr->constraints = AddConstraint(theEnv,slotPtr->constraints); } } @@ -238,7 +254,7 @@ globle void InstallDeftemplate( /********************************************************************/ static struct templateSlot *SlotDeclarations( void *theEnv, - char *readSource, + const char *readSource, struct token *inputToken) { struct templateSlot *newSlot, *slotList = NULL, *lastSlot = NULL; @@ -322,7 +338,7 @@ static struct templateSlot *SlotDeclarations( /*****************************************************/ static struct templateSlot *ParseSlot( void *theEnv, - char *readSource, + const char *readSource, struct token *inputToken, struct templateSlot *slotList) { @@ -415,7 +431,7 @@ static struct templateSlot *ParseSlot( if ((rv != NO_VIOLATION) && EnvGetStaticConstraintChecking(theEnv)) { - char *temp; + const char *temp; if (newSlot->defaultDynamic) temp = "the default-dynamic attribute"; else temp = "the default attribute"; ConstraintViolationErrorMessage(theEnv,"An expression",temp,FALSE,0, @@ -437,7 +453,7 @@ static struct templateSlot *ParseSlot( /**************************************************************/ static struct templateSlot *DefinedSlots( void *theEnv, - char *readSource, + const char *readSource, SYMBOL_HN *slotName, int multifieldSlot, struct token *inputToken) @@ -455,6 +471,7 @@ static struct templateSlot *DefinedSlots( newSlot = get_struct(theEnv,templateSlot); newSlot->slotName = slotName; newSlot->defaultList = NULL; + newSlot->facetList = NULL; newSlot->constraints = GetConstraintRecord(theEnv); if (multifieldSlot) { newSlot->constraints->multifieldsAllowed = TRUE; } @@ -581,6 +598,30 @@ static struct templateSlot *DefinedSlots( newSlot->defaultList = defaultList; } + /*===============================================*/ + /* else if the attribute is the facet attribute. */ + /*===============================================*/ + + else if (strcmp(ValueToString(inputToken->value),"facet") == 0) + { + if (! ParseFacetAttribute(theEnv,readSource,newSlot,FALSE)) + { + ReturnSlots(theEnv,newSlot); + DeftemplateData(theEnv)->DeftemplateError = TRUE; + return(NULL); + } + } + + else if (strcmp(ValueToString(inputToken->value),"multifacet") == 0) + { + if (! ParseFacetAttribute(theEnv,readSource,newSlot,TRUE)) + { + ReturnSlots(theEnv,newSlot); + DeftemplateData(theEnv)->DeftemplateError = TRUE; + return(NULL); + } + } + /*============================================*/ /* Otherwise the attribute is an invalid one. */ /*============================================*/ @@ -607,6 +648,157 @@ static struct templateSlot *DefinedSlots( return(newSlot); } +/***************************************************/ +/* ParseFacetAttribute: Parses the type attribute. */ +/***************************************************/ +static intBool ParseFacetAttribute( + void *theEnv, + const char *readSource, + struct templateSlot *theSlot, + intBool multifacet) + { + struct token inputToken; + SYMBOL_HN *facetName; + struct expr *facetPair, *tempFacet, *facetValue = NULL, *lastValue = NULL; + + /*==============================*/ + /* Parse the name of the facet. */ + /*==============================*/ + + SavePPBuffer(theEnv," "); + GetToken(theEnv,readSource,&inputToken); + + /*==================================*/ + /* The facet name must be a symbol. */ + /*==================================*/ + + if (inputToken.type != SYMBOL) + { + if (multifacet) SyntaxErrorMessage(theEnv,"multifacet attribute"); + else SyntaxErrorMessage(theEnv,"facet attribute"); + return(FALSE); + } + + facetName = (SYMBOL_HN *) inputToken.value; + + /*===================================*/ + /* Don't allow facets with the same */ + /* name as a predefined CLIPS facet. */ + /*===================================*/ + + /*====================================*/ + /* Has the facet already been parsed? */ + /*====================================*/ + + for (tempFacet = theSlot->facetList; + tempFacet != NULL; + tempFacet = tempFacet->nextArg) + { + if (tempFacet->value == facetName) + { + if (multifacet) AlreadyParsedErrorMessage(theEnv,"multifacet ",ValueToString(facetName)); + else AlreadyParsedErrorMessage(theEnv,"facet ",ValueToString(facetName)); + return(FALSE); + } + } + + /*===============================*/ + /* Parse the value of the facet. */ + /*===============================*/ + + SavePPBuffer(theEnv," "); + GetToken(theEnv,readSource,&inputToken); + + while (inputToken.type != RPAREN) + { + /*=====================================*/ + /* The facet value must be a constant. */ + /*=====================================*/ + + if (! ConstantType(inputToken.type)) + { + if (multifacet) SyntaxErrorMessage(theEnv,"multifacet attribute"); + else SyntaxErrorMessage(theEnv,"facet attribute"); + ReturnExpression(theEnv,facetValue); + return(FALSE); + } + + /*======================================*/ + /* Add the value to the list of values. */ + /*======================================*/ + + if (lastValue == NULL) + { + facetValue = GenConstant(theEnv,inputToken.type,inputToken.value); + lastValue = facetValue; + } + else + { + lastValue->nextArg = GenConstant(theEnv,inputToken.type,inputToken.value); + lastValue = lastValue->nextArg; + } + + /*=====================*/ + /* Get the next token. */ + /*=====================*/ + + SavePPBuffer(theEnv," "); + GetToken(theEnv,readSource,&inputToken); + + /*===============================================*/ + /* A facet can't contain more than one constant. */ + /*===============================================*/ + + if ((! multifacet) && (inputToken.type != RPAREN)) + { + SyntaxErrorMessage(theEnv,"facet attribute"); + ReturnExpression(theEnv,facetValue); + return(FALSE); + } + } + + /*========================================================*/ + /* Remove the space before the closing right parenthesis. */ + /*========================================================*/ + + PPBackup(theEnv); + PPBackup(theEnv); + SavePPBuffer(theEnv,")"); + + /*====================================*/ + /* A facet must contain one constant. */ + /*====================================*/ + + if ((! multifacet) && (facetValue == NULL)) + { + SyntaxErrorMessage(theEnv,"facet attribute"); + return(FALSE); + } + + /*=================================================*/ + /* Add the facet to the list of the slot's facets. */ + /*=================================================*/ + + facetPair = GenConstant(theEnv,SYMBOL,facetName); + + if (multifacet) + { + facetPair->argList = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"create$")); + facetPair->argList->argList = facetValue; + } + else + { facetPair->argList = facetValue; } + + facetPair->nextArg = theSlot->facetList; + theSlot->facetList = facetPair; + + /*===============================================*/ + /* The facet/multifacet was successfully parsed. */ + /*===============================================*/ + + return(TRUE); + } + #endif /* (! RUN_TIME) && (! BLOAD_ONLY) */ #endif /* DEFTEMPLATE_CONSTRUCT */ diff --git a/src/tmpltpsr.h b/src/tmpltpsr.h index 3481276..9f76be0 100644 --- a/src/tmpltpsr.h +++ b/src/tmpltpsr.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE PARSER HEADER FILE */ /*******************************************************/ @@ -16,6 +16,20 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Added support for templates maintaining their */ +/* own list of facts. */ +/* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW and */ +/* MAC_MCW). */ +/* */ +/* GetConstructNameAndComment API change. */ +/* */ +/* Support for deftemplate slot facets. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_tmpltpsr @@ -39,10 +53,10 @@ #define LOCALE extern #endif - LOCALE int ParseDeftemplate(void *,char *); + LOCALE int ParseDeftemplate(void *,const char *); LOCALE void InstallDeftemplate(void *,struct deftemplate *); -#endif +#endif /* _H_tmpltpsr */ diff --git a/src/tmpltrhs.c b/src/tmpltrhs.c index d206647..d25176e 100644 --- a/src/tmpltrhs.c +++ b/src/tmpltrhs.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 07/25/14 */ /* */ /* DEFTEMPLATE RHS PARSING HEADER FILE */ /*******************************************************/ @@ -23,6 +23,9 @@ /* Added additional argument required for */ /* InvalidDeftemplateSlotMessage. */ /* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _TMPLTRHS_SOURCE_ @@ -52,11 +55,11 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct expr *ParseAssertSlotValues(void *,char *,struct token *,struct templateSlot *,int *,int); + static struct expr *ParseAssertSlotValues(void *,const char *,struct token *,struct templateSlot *,int *,int); static struct expr *ReorderAssertSlotValues(void *,struct templateSlot *,struct expr *,int *); static struct expr *GetSlotAssertValues(void *,struct templateSlot *,struct expr *,int *); static struct expr *FindAssertSlotItem(struct templateSlot *,struct expr *); - static struct templateSlot *ParseSlotLabel(void *,char *,struct token *,struct deftemplate *,int *,int); + static struct templateSlot *ParseSlotLabel(void *,const char *,struct token *,struct deftemplate *,int *,int); /******************************************************************/ /* ParseAssertTemplate: Parses and builds the list of values that */ @@ -64,7 +67,7 @@ /******************************************************************/ globle struct expr *ParseAssertTemplate( void *theEnv, - char *readSource, + const char *readSource, struct token *theToken, int *error, int endType, @@ -169,7 +172,7 @@ globle struct expr *ParseAssertTemplate( /****************************************************************/ static struct templateSlot *ParseSlotLabel( void *theEnv, - char *inputSource, + const char *inputSource, struct token *tempToken, struct deftemplate *theDeftemplate, int *error, @@ -249,7 +252,7 @@ static struct templateSlot *ParseSlotLabel( /**************************************************************************/ static struct expr *ParseAssertSlotValues( void *theEnv, - char *inputSource, + const char *inputSource, struct token *tempToken, struct templateSlot *slotPtr, int *error, @@ -466,6 +469,7 @@ static struct expr *GetSlotAssertValues( struct expr *slotItem; struct expr *newArg, *tempArg; DATA_OBJECT theDefault; + const char *nullBitMap = "\0"; /*==================================================*/ /* Determine if the slot is assigned in the assert. */ @@ -536,7 +540,7 @@ static struct expr *GetSlotAssertValues( if (slotPtr->multislot) { - tempArg = GenConstant(theEnv,FACT_STORE_MULTIFIELD,AddBitMap(theEnv,(void *) "\0",1)); + tempArg = GenConstant(theEnv,FACT_STORE_MULTIFIELD,EnvAddBitMap(theEnv,(void *) nullBitMap,1)); tempArg->argList = newArg; newArg = tempArg; } diff --git a/src/tmpltrhs.h b/src/tmpltrhs.h index 31f1d79..ba8293c 100644 --- a/src/tmpltrhs.h +++ b/src/tmpltrhs.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE RHS PARSING HEADER FILE */ /*******************************************************/ @@ -16,6 +16,15 @@ /* */ /* Revision History: */ /* */ +/* 6.24: Added additional argument required for */ +/* DeriveDefaultFromConstraints. */ +/* */ +/* Added additional argument required for */ +/* InvalidDeftemplateSlotMessage. */ +/* */ +/* 6.30: Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_tmpltrhs @@ -42,10 +51,10 @@ #define LOCALE extern #endif - LOCALE struct expr *ParseAssertTemplate(void *,char *,struct token *,int *, + LOCALE struct expr *ParseAssertTemplate(void *,const char *,struct token *,int *, int,int,struct deftemplate *); -#endif +#endif /* _H_tmpltrhs */ diff --git a/src/tmpltutl.c b/src/tmpltutl.c index 31c1537..07bce73 100644 --- a/src/tmpltutl.c +++ b/src/tmpltutl.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE UTILITIES MODULE */ /*******************************************************/ @@ -13,9 +13,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian L. Donnell */ +/* Brian L. Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Added support for templates maintaining their */ /* own list of facts. */ /* */ @@ -27,6 +28,13 @@ /* Added additional arguments to */ /* PrintTemplateFact function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #define _TMPLTUTL_SOURCE_ @@ -52,6 +60,7 @@ #include "tmpltpsr.h" #include "modulutl.h" #include "watch.h" +#include "sysdep.h" #include "tmpltbsc.h" #include "tmpltdef.h" @@ -64,8 +73,8 @@ /********************************************************/ globle void InvalidDeftemplateSlotMessage( void *theEnv, - char *slotName, - char *deftemplateName, + const char *slotName, + const char *deftemplateName, int printCR) { PrintErrorID(theEnv,"TMPLTDEF",1,printCR); @@ -83,7 +92,7 @@ globle void InvalidDeftemplateSlotMessage( /**********************************************************/ globle void SingleFieldSlotCardinalityError( void *theEnv, - char *slotName) + const char *slotName) { PrintErrorID(theEnv,"TMPLTDEF",2,TRUE); EnvPrintRouter(theEnv,WERROR,"The single field slot "); @@ -180,7 +189,7 @@ globle void CheckTemplateFact( rv = ConstraintCheckDataObject(theEnv,&theData,slotPtr->constraints); if (rv != NO_VIOLATION) { - sprintf(thePlace,"fact f-%-5ld ",theFact->factIndex); + gensprintf(thePlace,"fact f-%-5lld ",theFact->factIndex); PrintErrorID(theEnv,"CSTRNCHK",1,TRUE); EnvPrintRouter(theEnv,WERROR,"Slot value "); @@ -205,10 +214,10 @@ globle intBool CheckRHSSlotTypes( void *theEnv, struct expr *rhsSlots, struct templateSlot *slotPtr, - char *thePlace) + const char *thePlace) { int rv; - char *theName; + const char *theName; if (EnvGetStaticConstraintChecking(theEnv) == FALSE) return(TRUE); rv = ConstraintCheckExpressionChain(theEnv,rhsSlots,slotPtr->constraints); @@ -275,7 +284,7 @@ globle int FindSlotPosition( /*******************************************************************/ globle void PrintTemplateFact( void *theEnv, - char *logicalName, + const char *logicalName, struct fact *theFact, int seperateLines, int ignoreDefaults) @@ -286,7 +295,7 @@ globle void PrintTemplateFact( struct templateSlot *slotPtr; DATA_OBJECT tempDO; int slotPrinted = FALSE; - + /*==============================*/ /* Initialize some information. */ /*==============================*/ @@ -309,22 +318,22 @@ globle void PrintTemplateFact( i = 0; while (slotPtr != NULL) - { + { /*=================================================*/ /* If we're ignoring slots with their original */ /* default value, check to see if the fact's slot */ /* value differs from the deftemplate default. */ /*=================================================*/ - + if (ignoreDefaults && (slotPtr->defaultDynamic == FALSE)) { DeftemplateSlotDefault(theEnv,theDeftemplate,slotPtr,&tempDO,TRUE); - + if (slotPtr->multislot == FALSE) { if ((GetType(tempDO) == sublist[i].type) && (GetValue(tempDO) == sublist[i].value)) - { + { i++; slotPtr = slotPtr->next; continue; @@ -338,16 +347,16 @@ globle void PrintTemplateFact( continue; } } - + /*===========================================*/ /* Print the opening parenthesis of the slot */ /* and the slot name. */ /*===========================================*/ - - if (! slotPrinted) - { + + if (! slotPrinted) + { slotPrinted = TRUE; - EnvPrintRouter(theEnv,logicalName," "); + EnvPrintRouter(theEnv,logicalName," "); } if (seperateLines) diff --git a/src/tmpltutl.h b/src/tmpltutl.h index ccfaa46..a25d702 100644 --- a/src/tmpltutl.h +++ b/src/tmpltutl.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* DEFTEMPLATE UTILITIES HEADER FILE */ /*******************************************************/ @@ -16,6 +16,9 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Added support for templates maintaining their */ +/* own list of facts. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ /* Added additional arguments to */ @@ -24,6 +27,13 @@ /* Added additional arguments to */ /* PrintTemplateFact function. */ /* */ +/* 6.30: Support for long long integers. */ +/* */ +/* Used gensprintf instead of sprintf. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ /*************************************************************/ #ifndef _H_tmpltutl @@ -56,19 +66,19 @@ #define LOCALE extern #endif - LOCALE void InvalidDeftemplateSlotMessage(void *,char *,char *,int); - LOCALE void SingleFieldSlotCardinalityError(void *,char *); + LOCALE void InvalidDeftemplateSlotMessage(void *,const char *,const char *,int); + LOCALE void SingleFieldSlotCardinalityError(void *,const char *); LOCALE void MultiIntoSingleFieldSlotError(void *,struct templateSlot *,struct deftemplate *); LOCALE void CheckTemplateFact(void *,struct fact *); - LOCALE intBool CheckRHSSlotTypes(void *,struct expr *,struct templateSlot *,char *); + LOCALE intBool CheckRHSSlotTypes(void *,struct expr *,struct templateSlot *,const char *); LOCALE struct templateSlot *GetNthSlot(struct deftemplate *,int); LOCALE int FindSlotPosition(struct deftemplate *,struct symbolHashNode *); - LOCALE void PrintTemplateFact(void *,char *,struct fact *,int,int); + LOCALE void PrintTemplateFact(void *,const char *,struct fact *,int,int); LOCALE void UpdateDeftemplateScope(void *); LOCALE struct templateSlot *FindSlot(struct deftemplate *,struct symbolHashNode *,short *); LOCALE struct deftemplate *CreateImpliedDeftemplate(void *,SYMBOL_HN *,int); -#endif +#endif /* _H_tmpltutl */ diff --git a/src/userdata.c b/src/userdata.c index acd3c5b..432f442 100644 --- a/src/userdata.c +++ b/src/userdata.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* USER DATA MODULE */ /*******************************************************/ @@ -50,7 +50,7 @@ globle unsigned char InstallUserDataRecord( UserDataData(theEnv)->UserDataRecordArray[UserDataData(theEnv)->UserDataRecordCount] = theRecord; return(UserDataData(theEnv)->UserDataRecordCount++); } - + /*****************************************************/ /* FetchUserData: Searches for user data information */ /* from a list of user data structures. A new user */ @@ -70,13 +70,13 @@ globle struct userData *FetchUserData( if (theData->dataID == userDataID) { return(theData); } } - + theData = (struct userData *) (*UserDataData(theEnv)->UserDataRecordArray[userDataID]->createUserData)(theEnv); theData->dataID = userDataID; theData->next = *theList; *theList = theData; - - return(theData); + + return(theData); } /*****************************************************/ @@ -90,7 +90,7 @@ globle struct userData *TestUserData( struct userData *theList) { struct userData *theData; - + for (theData = theList; theData != NULL; theData = theData->next) @@ -98,8 +98,8 @@ globle struct userData *TestUserData( if (theData->dataID == userDataID) { return(theData); } } - - return(NULL); + + return(NULL); } /***************************************************************/ @@ -110,7 +110,7 @@ globle void ClearUserDataList( struct userData *theList) { struct userData *nextData; - + while (theList != NULL) { nextData = theList->next; @@ -118,7 +118,7 @@ globle void ClearUserDataList( theList = nextData; } } - + /*************************************************/ /* DeleteUserData: Removes user data information */ /* from a list of user data structures. */ @@ -129,25 +129,25 @@ globle struct userData *DeleteUserData( struct userData *theList) { struct userData *theData, *lastData = NULL; - + for (theData = theList; theData != NULL; theData = theData->next) { if (theData->dataID == userDataID) - { + { if (lastData == NULL) { theList = theData->next; } else { lastData->next = theData->next; } - + (*UserDataData(theEnv)->UserDataRecordArray[userDataID]->deleteUserData)(theEnv,theData); return(theList); } - + lastData = theData; } - - return(theList); + + return(theList); } diff --git a/src/userdata.h b/src/userdata.h index 029b7d5..58f4d1e 100644 --- a/src/userdata.h +++ b/src/userdata.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.20 01/31/02 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* USER DATA HEADER FILE */ /*******************************************************/ @@ -38,14 +38,14 @@ struct userData typedef struct userData USER_DATA; typedef struct userData * USER_DATA_PTR; - + struct userDataRecord { unsigned char dataID; void *(*createUserData)(void *); void (*deleteUserData)(void *,void *); }; - + typedef struct userDataRecord USER_DATA_RECORD; typedef struct userDataRecord * USER_DATA_RECORD_PTR; @@ -54,7 +54,7 @@ typedef struct userDataRecord * USER_DATA_RECORD_PTR; #define USER_DATA_DATA 56 struct userDataData - { + { struct userDataRecord *UserDataRecordArray[MAXIMUM_USER_DATA_RECORDS]; unsigned char UserDataRecordCount; }; diff --git a/src/userfunctions.c b/src/userfunctions.c index 21b64ec..0c9b91c 100644 --- a/src/userfunctions.c +++ b/src/userfunctions.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 04/21/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* USER FUNCTIONS MODULE */ /*******************************************************/ @@ -19,6 +19,10 @@ /* 6.24: Created file to seperate UserFunctions and */ /* EnvUserFunctions from main.c. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ /*************************************************************/ /***************************************************************************/ @@ -41,12 +45,11 @@ /* */ /***************************************************************************/ -#include "setup.h" -#include "extnfunc.h" +#include "clips.h" void UserFunctions(void); void EnvUserFunctions(void *); - + /*********************************************************/ /* UserFunctions: Informs the expert system environment */ /* of any user defined functions. In the default case, */ @@ -57,9 +60,11 @@ void EnvUserFunctions(void *); /* included in another file. */ /*********************************************************/ void UserFunctions() - { + { + // Use of UserFunctions is deprecated. + // Use EnvUserFunctions instead. } - + /***********************************************************/ /* EnvUserFunctions: Informs the expert system environment */ /* of any user defined functions. In the default case, */ @@ -69,14 +74,11 @@ void UserFunctions() /* this function can be deleted from this file and */ /* included in another file. */ /***********************************************************/ -#if IBM_TBC -#pragma argsused -#endif void EnvUserFunctions( - void *theEnv) + void *environment) { -#if MAC_MCW || IBM_MCW || MAC_XCD -#pragma unused(theEnv) +#if MAC_XCD +#pragma unused(environment) #endif } diff --git a/src/usrsetup.h b/src/usrsetup.h index 8b13789..e69de29 100644 --- a/src/usrsetup.h +++ b/src/usrsetup.h @@ -1 +0,0 @@ - diff --git a/src/utility.c b/src/utility.c index ec0373d..951fac5 100644 --- a/src/utility.c +++ b/src/utility.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 02/03/15 */ /* */ /* UTILITY MODULE */ /*******************************************************/ @@ -16,12 +16,36 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ +/* Jeff Bezanson */ +/* www.cprogramming.com/tutorial/unicode.html */ /* */ /* Revision History: */ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added CopyString, DeleteString, */ +/* InsertInString,and EnlargeString functions. */ +/* */ +/* Used genstrncpy function instead of strncpy */ +/* function. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* Support for tracked memory (allows memory to */ +/* be freed if CLIPS is exited while executing). */ +/* */ +/* Added UTF-8 routines. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _UTILITY_SOURCE_ @@ -35,12 +59,14 @@ #define _STDIO_INCLUDED_ #include <string.h> +#include "commline.h" #include "envrnmnt.h" #include "evaluatn.h" #include "facthsh.h" #include "memalloc.h" #include "multifld.h" #include "prntutil.h" +#include "sysdep.h" #include "utility.h" @@ -53,9 +79,6 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static intBool AddCPFunction(void *,char *,void (*)(void *), - int,struct cleanupFunction **,intBool); - static intBool RemoveCPFunction(void *,char *,struct cleanupFunction **); static void DeallocateUtilityData(void *); /************************************************/ @@ -67,14 +90,12 @@ globle void InitializeUtilityData( { AllocateEnvironmentData(theEnv,UTILITY_DATA,sizeof(struct utilityData),DeallocateUtilityData); + UtilityData(theEnv)->CurrentGarbageFrame = &UtilityData(theEnv)->MasterGarbageFrame; + UtilityData(theEnv)->CurrentGarbageFrame->topLevel = TRUE; + UtilityData(theEnv)->GarbageCollectionLocks = 0; - UtilityData(theEnv)->GarbageCollectionHeuristicsEnabled = TRUE; UtilityData(theEnv)->PeriodicFunctionsEnabled = TRUE; UtilityData(theEnv)->YieldFunctionEnabled = TRUE; - - UtilityData(theEnv)->CurrentEphemeralCountMax = MAX_EPHEMERAL_COUNT; - UtilityData(theEnv)->CurrentEphemeralSizeMax = MAX_EPHEMERAL_SIZE; - UtilityData(theEnv)->LastEvaluationDepth = -1; } /**************************************************/ @@ -84,13 +105,34 @@ globle void InitializeUtilityData( static void DeallocateUtilityData( void *theEnv) { - struct cleanupFunction *tmpPtr, *nextPtr; + struct callFunctionItem *tmpPtr, *nextPtr; + struct trackedMemory *tmpTM, *nextTM; + struct garbageFrame *theGarbageFrame; + struct ephemeron *edPtr, *nextEDPtr; + struct multifield *tmpMFPtr, *nextMFPtr; + + /*======================*/ + /* Free tracked memory. */ + /*======================*/ + + tmpTM = UtilityData(theEnv)->trackList; + while (tmpTM != NULL) + { + nextTM = tmpTM->next; + genfree(theEnv,tmpTM->theMemory,tmpTM->memSize); + rtn_struct(theEnv,trackedMemory,tmpTM); + tmpTM = nextTM; + } + + /*==========================*/ + /* Free callback functions. */ + /*==========================*/ tmpPtr = UtilityData(theEnv)->ListOfPeriodicFunctions; while (tmpPtr != NULL) { nextPtr = tmpPtr->next; - rtn_struct(theEnv,cleanupFunction,tmpPtr); + rtn_struct(theEnv,callFunctionItem,tmpPtr); tmpPtr = nextPtr; } @@ -98,147 +140,191 @@ static void DeallocateUtilityData( while (tmpPtr != NULL) { nextPtr = tmpPtr->next; - rtn_struct(theEnv,cleanupFunction,tmpPtr); + rtn_struct(theEnv,callFunctionItem,tmpPtr); tmpPtr = nextPtr; } - } -/*************************************************************/ -/* PeriodicCleanup: Returns garbage created during execution */ -/* that has not been returned to the memory pool yet. The */ -/* cleanup is normally deferred so that an executing rule */ -/* can still access these data structures. Always calls a */ -/* series of functions that should be called periodically. */ -/* Usually used by interfaces to update displays. */ -/*************************************************************/ -globle void PeriodicCleanup( - void *theEnv, - intBool cleanupAllDepths, - intBool useHeuristics) - { - int oldDepth = -1; - struct cleanupFunction *cleanupPtr,*periodPtr; + /*=========================================*/ + /* Free the ephemerons tracking data which */ + /* needs to be garbage collected. */ + /*=========================================*/ - /*===================================*/ - /* Don't use heuristics if disabled. */ - /*===================================*/ + while (UtilityData(theEnv)->CurrentGarbageFrame != NULL) + { + theGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; - if (! UtilityData(theEnv)->GarbageCollectionHeuristicsEnabled) - { useHeuristics = FALSE; } + edPtr = theGarbageFrame->ephemeralSymbolList; - /*=============================================*/ - /* Call functions for handling periodic tasks. */ - /*=============================================*/ + while (edPtr != NULL) + { + nextEDPtr = edPtr->next; + rtn_struct(theEnv,ephemeron,edPtr); + edPtr = nextEDPtr; + } - if (UtilityData(theEnv)->PeriodicFunctionsEnabled) - { - for (periodPtr = UtilityData(theEnv)->ListOfPeriodicFunctions; - periodPtr != NULL; - periodPtr = periodPtr->next) + edPtr = theGarbageFrame->ephemeralFloatList; + + while (edPtr != NULL) { - if (periodPtr->environmentAware) - { (*periodPtr->ip)(theEnv); } - else - { (* (void (*)(void)) periodPtr->ip)(); } + nextEDPtr = edPtr->next; + rtn_struct(theEnv,ephemeron,edPtr); + edPtr = nextEDPtr; } - } - /*===================================================*/ - /* If the last level we performed cleanup was deeper */ - /* than the current level, reset the values used by */ - /* the heuristics to determine if garbage collection */ - /* should be performed. If the heuristic values had */ - /* to be incremented because there was no garbage */ - /* that could be cleaned up, we don't want to keep */ - /* those same high values permanently so we reset */ - /* them when we go back to a lower evaluation depth. */ - /*===================================================*/ - - if (UtilityData(theEnv)->LastEvaluationDepth > EvaluationData(theEnv)->CurrentEvaluationDepth) - { - UtilityData(theEnv)->LastEvaluationDepth = EvaluationData(theEnv)->CurrentEvaluationDepth; - UtilityData(theEnv)->CurrentEphemeralCountMax = MAX_EPHEMERAL_COUNT; - UtilityData(theEnv)->CurrentEphemeralSizeMax = MAX_EPHEMERAL_SIZE; - } + edPtr = theGarbageFrame->ephemeralIntegerList; - /*======================================================*/ - /* If we're using heuristics to determine if garbage */ - /* collection to occur, then check to see if enough */ - /* garbage has been created to make cleanup worthwhile. */ - /*======================================================*/ + while (edPtr != NULL) + { + nextEDPtr = edPtr->next; + rtn_struct(theEnv,ephemeron,edPtr); + edPtr = nextEDPtr; + } - if (UtilityData(theEnv)->GarbageCollectionLocks > 0) return; + edPtr = theGarbageFrame->ephemeralBitMapList; - if (useHeuristics && - (UtilityData(theEnv)->EphemeralItemCount < UtilityData(theEnv)->CurrentEphemeralCountMax) && - (UtilityData(theEnv)->EphemeralItemSize < UtilityData(theEnv)->CurrentEphemeralSizeMax)) - { return; } + while (edPtr != NULL) + { + nextEDPtr = edPtr->next; + rtn_struct(theEnv,ephemeron,edPtr); + edPtr = nextEDPtr; + } - /*==========================================================*/ - /* If cleanup is being performed at all depths, rather than */ - /* just the current evaluation depth, then temporarily set */ - /* the evaluation depth to a level that will force cleanup */ - /* at all depths. */ - /*==========================================================*/ + edPtr = theGarbageFrame->ephemeralExternalAddressList; - if (cleanupAllDepths) - { - oldDepth = EvaluationData(theEnv)->CurrentEvaluationDepth; - EvaluationData(theEnv)->CurrentEvaluationDepth = -1; + while (edPtr != NULL) + { + nextEDPtr = edPtr->next; + rtn_struct(theEnv,ephemeron,edPtr); + edPtr = nextEDPtr; + } + + /*==========================*/ + /* Free up multifield data. */ + /*==========================*/ + + tmpMFPtr = theGarbageFrame->ListOfMultifields; + while (tmpMFPtr != NULL) + { + nextMFPtr = tmpMFPtr->next; + ReturnMultifield(theEnv,tmpMFPtr); + tmpMFPtr = nextMFPtr; + } + + UtilityData(theEnv)->CurrentGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame->priorFrame; } + } + +/*****************************/ +/* CleanCurrentGarbageFrame: */ +/*****************************/ +globle void CleanCurrentGarbageFrame( + void *theEnv, + DATA_OBJECT *returnValue) + { + struct garbageFrame *currentGarbageFrame; + + currentGarbageFrame = UtilityData(theEnv)->CurrentGarbageFrame; + + if (! currentGarbageFrame->dirty) return; - /*=============================================*/ - /* Free up multifield values no longer in use. */ - /*=============================================*/ + if (returnValue != NULL) + { ValueInstall(theEnv,returnValue); } + CallCleanupFunctions(theEnv); + RemoveEphemeralAtoms(theEnv); FlushMultifields(theEnv); - /*=====================================*/ - /* Call the list of cleanup functions. */ - /*=====================================*/ + if (returnValue != NULL) + { ValueDeinstall(theEnv,returnValue); } - for (cleanupPtr = UtilityData(theEnv)->ListOfCleanupFunctions; - cleanupPtr != NULL; - cleanupPtr = cleanupPtr->next) + if ((currentGarbageFrame->ephemeralFloatList == NULL) && + (currentGarbageFrame->ephemeralIntegerList == NULL) && + (currentGarbageFrame->ephemeralSymbolList == NULL) && + (currentGarbageFrame->ephemeralBitMapList == NULL) && + (currentGarbageFrame->ephemeralExternalAddressList == NULL) && + (currentGarbageFrame->LastMultifield == NULL)) + { currentGarbageFrame->dirty = FALSE; } + } + +/*****************************/ +/* RestorePriorGarbageFrame: */ +/*****************************/ +globle void RestorePriorGarbageFrame( + void *theEnv, + struct garbageFrame *newGarbageFrame, + struct garbageFrame *oldGarbageFrame, + DATA_OBJECT *returnValue) + { + if (newGarbageFrame->dirty) { - if (cleanupPtr->environmentAware) - { (*cleanupPtr->ip)(theEnv); } - else - { (* (void (*)(void)) cleanupPtr->ip)(); } - } + if (returnValue != NULL) ValueInstall(theEnv,returnValue); + CallCleanupFunctions(theEnv); + RemoveEphemeralAtoms(theEnv); + FlushMultifields(theEnv); + } - /*================================================*/ - /* Free up atomic values that are no longer used. */ - /*================================================*/ + UtilityData(theEnv)->CurrentGarbageFrame = oldGarbageFrame; - RemoveEphemeralAtoms(theEnv); + if (newGarbageFrame->dirty) + { + if (newGarbageFrame->ListOfMultifields != NULL) + { + if (oldGarbageFrame->ListOfMultifields == NULL) + { oldGarbageFrame->ListOfMultifields = newGarbageFrame->ListOfMultifields; } + else + { oldGarbageFrame->LastMultifield->next = newGarbageFrame->ListOfMultifields; } - /*=========================================*/ - /* Restore the evaluation depth if cleanup */ - /* was performed on all depths. */ - /*=========================================*/ + oldGarbageFrame->LastMultifield = newGarbageFrame->LastMultifield; + oldGarbageFrame->dirty = TRUE; + } - if (cleanupAllDepths) EvaluationData(theEnv)->CurrentEvaluationDepth = oldDepth; + if (returnValue != NULL) ValueDeinstall(theEnv,returnValue); + } - /*============================================================*/ - /* If very little memory was freed up, then increment the */ - /* values used by the heuristics so that we don't continually */ - /* try to free up memory that isn't being released. */ - /*============================================================*/ + if (returnValue != NULL) + { EphemerateValue(theEnv,returnValue->type,returnValue->value); } + } - if ((UtilityData(theEnv)->EphemeralItemCount + COUNT_INCREMENT) > UtilityData(theEnv)->CurrentEphemeralCountMax) - { UtilityData(theEnv)->CurrentEphemeralCountMax = UtilityData(theEnv)->EphemeralItemCount + COUNT_INCREMENT; } +/*************************/ +/* CallCleanupFunctions: */ +/*************************/ +globle void CallCleanupFunctions( + void *theEnv) + { + struct callFunctionItem *cleanupPtr; - if ((UtilityData(theEnv)->EphemeralItemSize + SIZE_INCREMENT) > UtilityData(theEnv)->CurrentEphemeralSizeMax) - { UtilityData(theEnv)->CurrentEphemeralSizeMax = UtilityData(theEnv)->EphemeralItemSize + SIZE_INCREMENT; } + for (cleanupPtr = UtilityData(theEnv)->ListOfCleanupFunctions; + cleanupPtr != NULL; + cleanupPtr = cleanupPtr->next) + { + if (cleanupPtr->environmentAware) + { (*cleanupPtr->func)(theEnv); } + else + { (* (void (*)(void)) cleanupPtr->func)(); } + } + } - /*===============================================================*/ - /* Remember the evaluation depth at which garbage collection was */ - /* last performed. This information is used for resetting the */ - /* ephemeral count and size numbers used by the heuristics. */ - /*===============================================================*/ +/**************************************************/ +/* CallPeriodicTasks: Calls the list of functions */ +/* for handling periodic tasks. */ +/**************************************************/ +globle void CallPeriodicTasks( + void *theEnv) + { + struct callFunctionItem *periodPtr; - UtilityData(theEnv)->LastEvaluationDepth = EvaluationData(theEnv)->CurrentEvaluationDepth; + if (UtilityData(theEnv)->PeriodicFunctionsEnabled) + { + for (periodPtr = UtilityData(theEnv)->ListOfPeriodicFunctions; + periodPtr != NULL; + periodPtr = periodPtr->next) + { + if (periodPtr->environmentAware) + { (*periodPtr->func)(theEnv); } + else + { (* (void (*)(void)) periodPtr->func)(); } + } + } } /***************************************************/ @@ -248,20 +334,24 @@ globle void PeriodicCleanup( /***************************************************/ globle intBool AddCleanupFunction( void *theEnv, - char *name, + const char *name, void (*theFunction)(void *), int priority) { - return(AddCPFunction(theEnv,name,theFunction,priority,&UtilityData(theEnv)->ListOfCleanupFunctions,TRUE)); + UtilityData(theEnv)->ListOfCleanupFunctions = + AddFunctionToCallList(theEnv,name,priority, + (void (*)(void *)) theFunction, + UtilityData(theEnv)->ListOfCleanupFunctions,TRUE); + return(1); } -#if (! ENVIRONMENT_API_ONLY) && ALLOW_ENVIRONMENT_GLOBALS +#if ALLOW_ENVIRONMENT_GLOBALS /****************************************************/ /* AddPeriodicFunction: Adds a function to the list */ /* of functions called to handle periodic tasks. */ /****************************************************/ globle intBool AddPeriodicFunction( - char *name, + const char *name, void (*theFunction)(void), int priority) { @@ -269,8 +359,12 @@ globle intBool AddPeriodicFunction( theEnv = GetCurrentEnvironment(); - return(AddCPFunction(theEnv,name,(void (*)(void *)) theFunction,priority, - &UtilityData(theEnv)->ListOfPeriodicFunctions,FALSE)); + UtilityData(theEnv)->ListOfPeriodicFunctions = + AddFunctionToCallList(theEnv,name,priority, + (void (*)(void *)) theFunction, + UtilityData(theEnv)->ListOfPeriodicFunctions,FALSE); + + return(1); } #endif @@ -280,59 +374,14 @@ globle intBool AddPeriodicFunction( /*******************************************************/ globle intBool EnvAddPeriodicFunction( void *theEnv, - char *name, + const char *name, void (*theFunction)(void *), int priority) { - return(AddCPFunction(theEnv,name,theFunction,priority,&UtilityData(theEnv)->ListOfPeriodicFunctions,TRUE)); - } - -/**********************************/ -/* AddCPFunction: Adds a function */ -/* to a list of functions. */ -/**********************************/ -static intBool AddCPFunction( - void *theEnv, - char *name, - void (*theFunction)(void *), - int priority, - struct cleanupFunction **head, - intBool environmentAware) - { - struct cleanupFunction *newPtr, *currentPtr, *lastPtr = NULL; - - newPtr = get_struct(theEnv,cleanupFunction); - - newPtr->name = name; - newPtr->ip = theFunction; - newPtr->priority = priority; - newPtr->environmentAware = (short) environmentAware; - - if (*head == NULL) - { - newPtr->next = NULL; - *head = newPtr; - return(1); - } - - currentPtr = *head; - while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) - { - lastPtr = currentPtr; - currentPtr = currentPtr->next; - } - - if (lastPtr == NULL) - { - newPtr->next = *head; - *head = newPtr; - } - else - { - newPtr->next = currentPtr; - lastPtr->next = newPtr; - } - + UtilityData(theEnv)->ListOfPeriodicFunctions = + AddFunctionToCallList(theEnv,name,priority, + (void (*)(void *)) theFunction, + UtilityData(theEnv)->ListOfPeriodicFunctions,TRUE); return(1); } @@ -343,9 +392,14 @@ static intBool AddCPFunction( /*******************************************************/ globle intBool RemoveCleanupFunction( void *theEnv, - char *name) + const char *name) { - return(RemoveCPFunction(theEnv,name,&UtilityData(theEnv)->ListOfCleanupFunctions)); + intBool found; + + UtilityData(theEnv)->ListOfCleanupFunctions = + RemoveFunctionFromCallList(theEnv,name,UtilityData(theEnv)->ListOfCleanupFunctions,&found); + + return found; } /**********************************************************/ @@ -354,53 +408,27 @@ globle intBool RemoveCleanupFunction( /**********************************************************/ globle intBool EnvRemovePeriodicFunction( void *theEnv, - char *name) - { - return(RemoveCPFunction(theEnv,name,&UtilityData(theEnv)->ListOfPeriodicFunctions)); - } - -/****************************************/ -/* RemoveCPFunction: Removes a function */ -/* from a list of functions. */ -/****************************************/ -static intBool RemoveCPFunction( - void *theEnv, - char *name, - struct cleanupFunction **head) + const char *name) { - struct cleanupFunction *currentPtr, *lastPtr; - - lastPtr = NULL; - currentPtr = *head; + intBool found; - while (currentPtr != NULL) - { - if (strcmp(name,currentPtr->name) == 0) - { - if (lastPtr == NULL) - { *head = currentPtr->next; } - else - { lastPtr->next = currentPtr->next; } - rtn_struct(theEnv,cleanupFunction,currentPtr); - return(TRUE); - } - lastPtr = currentPtr; - currentPtr = currentPtr->next; - } + UtilityData(theEnv)->ListOfPeriodicFunctions = + RemoveFunctionFromCallList(theEnv,name,UtilityData(theEnv)->ListOfPeriodicFunctions,&found); - return(FALSE); + return found; } /*****************************************************/ /* StringPrintForm: Generates printed representation */ /* of a string. Replaces / with // and " with /". */ /*****************************************************/ -globle char *StringPrintForm( +globle const char *StringPrintForm( void *theEnv, - char *str) + const char *str) { - int i = 0, pos = 0; - unsigned max = 0; + int i = 0; + size_t pos = 0; + size_t max = 0; char *theString = NULL; void *thePtr; @@ -424,18 +452,47 @@ globle char *StringPrintForm( return(ValueToString(thePtr)); } +/**************************************************************/ +/* CopyString: Copies a string using CLIPS memory management. */ +/**************************************************************/ +globle char *CopyString( + void *theEnv, + const char *theString) + { + char *stringCopy = NULL; + + if (theString != NULL) + { + stringCopy = (char *) genalloc(theEnv,strlen(theString) + 1); + genstrcpy(stringCopy,theString); + } + + return stringCopy; + } + +/*****************************************************************/ +/* DeleteString: Deletes a string using CLIPS memory management. */ +/*****************************************************************/ +globle void DeleteString( + void *theEnv, + char *theString) + { + if (theString != NULL) + { genfree(theEnv,theString,strlen(theString) + 1); } + } + /***********************************************************/ /* AppendStrings: Appends two strings together. The string */ /* created is added to the SymbolTable, so it is not */ /* necessary to deallocate the string returned. */ /***********************************************************/ -globle char *AppendStrings( +globle const char *AppendStrings( void *theEnv, - char *str1, - char *str2) + const char *str1, + const char *str2) { - int pos = 0; - unsigned max = 0; + size_t pos = 0; + size_t max = 0; char *theString = NULL; void *thePtr; @@ -453,10 +510,10 @@ globle char *AppendStrings( /******************************************************/ globle char *AppendToString( void *theEnv, - char *appendStr, + const char *appendStr, char *oldStr, - int *oldPos, - unsigned *oldMax) + size_t *oldPos, + size_t *oldMax) { size_t length; @@ -466,23 +523,66 @@ globle char *AppendToString( /*=========================================*/ length = strlen(appendStr); - if (length + *oldPos + 1 > *oldMax) - { - oldStr = (char *) genrealloc(theEnv,oldStr,(unsigned) *oldMax,(unsigned) length + *oldPos + 1); - *oldMax = length + *oldPos + 1; - } /*==============================================================*/ /* Return NULL if the old string was not successfully expanded. */ /*==============================================================*/ - if (oldStr == NULL) { return(NULL); } + if ((oldStr = EnlargeString(theEnv,length,oldStr,oldPos,oldMax)) == NULL) { return(NULL); } /*===============================================*/ /* Append the new string to the expanded string. */ /*===============================================*/ - strcpy(&oldStr[*oldPos],appendStr); + genstrcpy(&oldStr[*oldPos],appendStr); + *oldPos += (int) length; + + /*============================================================*/ + /* Return the expanded string containing the appended string. */ + /*============================================================*/ + + return(oldStr); + } + +/**********************************************************/ +/* InsertInString: Inserts a string within another string */ +/* (expanding the other string if necessary). */ +/**********************************************************/ +globle char *InsertInString( + void *theEnv, + const char *insertStr, + size_t position, + char *oldStr, + size_t *oldPos, + size_t *oldMax) + { + size_t length; + + /*=========================================*/ + /* Expand the old string so it can contain */ + /* the new string (if necessary). */ + /*=========================================*/ + + length = strlen(insertStr); + + /*==============================================================*/ + /* Return NULL if the old string was not successfully expanded. */ + /*==============================================================*/ + + if ((oldStr = EnlargeString(theEnv,length,oldStr,oldPos,oldMax)) == NULL) { return(NULL); } + + /*================================================================*/ + /* Shift the contents to the right of insertion point so that the */ + /* new text does not overwrite what is currently in the string. */ + /*================================================================*/ + + memmove(&oldStr[position],&oldStr[position+length],*oldPos - position); + + /*===============================================*/ + /* Insert the new string in the expanded string. */ + /*===============================================*/ + + genstrncpy(&oldStr[*oldPos],insertStr,length); *oldPos += (int) length; /*============================================================*/ @@ -492,6 +592,36 @@ globle char *AppendToString( return(oldStr); } +/*******************************************************************/ +/* EnlargeString: Enlarges a string by the specified amount. */ +/*******************************************************************/ +globle char *EnlargeString( + void *theEnv, + size_t length, + char *oldStr, + size_t *oldPos, + size_t *oldMax) + { + /*=========================================*/ + /* Expand the old string so it can contain */ + /* the new string (if necessary). */ + /*=========================================*/ + + if (length + *oldPos + 1 > *oldMax) + { + oldStr = (char *) genrealloc(theEnv,oldStr,*oldMax,length + *oldPos + 1); + *oldMax = length + *oldPos + 1; + } + + /*==============================================================*/ + /* Return NULL if the old string was not successfully expanded. */ + /*==============================================================*/ + + if (oldStr == NULL) { return(NULL); } + + return(oldStr); + } + /*******************************************************/ /* AppendNToString: Appends a string to another string */ /* (expanding the other string if necessary). Only a */ @@ -500,13 +630,13 @@ globle char *AppendToString( /*******************************************************/ globle char *AppendNToString( void *theEnv, - char *appendStr, + const char *appendStr, char *oldStr, - unsigned length, - int *oldPos, - unsigned *oldMax) + size_t length, + size_t *oldPos, + size_t *oldMax) { - unsigned lengthWithEOS; + size_t lengthWithEOS; /*====================================*/ /* Determine the number of characters */ @@ -523,8 +653,8 @@ globle char *AppendNToString( if (lengthWithEOS + *oldPos > *oldMax) { - oldStr = (char *) genrealloc(theEnv,oldStr,(unsigned) *oldMax,(unsigned) *oldPos + lengthWithEOS); - *oldMax = (unsigned) *oldPos + lengthWithEOS; + oldStr = (char *) genrealloc(theEnv,oldStr,*oldMax,*oldPos + lengthWithEOS); + *oldMax = *oldPos + lengthWithEOS; } /*==============================================================*/ @@ -538,8 +668,8 @@ globle char *AppendNToString( /* string to the expanded string. */ /*==================================*/ - strncpy(&oldStr[*oldPos],appendStr,(STD_SIZE) length); - *oldPos += (int) (lengthWithEOS - 1); + genstrncpy(&oldStr[*oldPos],appendStr,length); + *oldPos += (lengthWithEOS - 1); oldStr[*oldPos] = '\0'; /*============================================================*/ @@ -560,11 +690,11 @@ globle char *ExpandStringWithChar( void *theEnv, int inchar, char *str, - int *pos, - unsigned *max, - unsigned newSize) + size_t *pos, + size_t *max, + size_t newSize) { - if ((*pos + 1) >= (int) *max) + if ((*pos + 1) >= *max) { str = (char *) genrealloc(theEnv,str,*max,newSize); *max = newSize; @@ -578,6 +708,17 @@ globle char *ExpandStringWithChar( } else { + /*===========================================================*/ + /* First delete any UTF-8 multibyte continuation characters. */ + /*===========================================================*/ + + while ((*pos > 1) && IsUTF8MultiByteContinuation(str[*pos - 1])) + { (*pos)--; } + + /*===================================================*/ + /* Now delete the first byte of the UTF-8 character. */ + /*===================================================*/ + if (*pos > 0) (*pos)--; str[*pos] = '\0'; } @@ -592,12 +733,29 @@ globle char *ExpandStringWithChar( /*****************************************************************/ globle struct callFunctionItem *AddFunctionToCallList( void *theEnv, - char *name, + const char *name, int priority, void (*func)(void *), struct callFunctionItem *head, intBool environmentAware) { + return AddFunctionToCallListWithContext(theEnv,name,priority,func,head,environmentAware,NULL); + } + +/***********************************************************/ +/* AddFunctionToCallListWithContext: Adds a function to a */ +/* list of functions which are called to perform certain */ +/* operations (e.g. clear, reset, and bload functions). */ +/***********************************************************/ +globle struct callFunctionItem *AddFunctionToCallListWithContext( + void *theEnv, + const char *name, + int priority, + void (*func)(void *), + struct callFunctionItem *head, + intBool environmentAware, + void *context) + { struct callFunctionItem *newPtr, *currentPtr, *lastPtr = NULL; newPtr = get_struct(theEnv,callFunctionItem); @@ -606,6 +764,7 @@ globle struct callFunctionItem *AddFunctionToCallList( newPtr->func = func; newPtr->priority = priority; newPtr->environmentAware = (short) environmentAware; + newPtr->context = context; if (head == NULL) { @@ -641,7 +800,7 @@ globle struct callFunctionItem *AddFunctionToCallList( /*****************************************************************/ globle struct callFunctionItem *RemoveFunctionFromCallList( void *theEnv, - char *name, + const char *name, struct callFunctionItem *head, int *found) { @@ -692,16 +851,147 @@ globle void DeallocateCallList( } } +/***************************************************************/ +/* AddFunctionToCallListWithArg: Adds a function to a list of */ +/* functions which are called to perform certain operations */ +/* (e.g. clear,reset, and bload functions). */ +/***************************************************************/ +globle struct callFunctionItemWithArg *AddFunctionToCallListWithArg( + void *theEnv, + const char *name, + int priority, + void (*func)(void *, void *), + struct callFunctionItemWithArg *head, + intBool environmentAware) + { + return AddFunctionToCallListWithArgWithContext(theEnv,name,priority,func,head,environmentAware,NULL); + } + +/***************************************************************/ +/* AddFunctionToCallListWithArgWithContext: Adds a function to */ +/* a list of functions which are called to perform certain */ +/* operations (e.g. clear, reset, and bload functions). */ +/***************************************************************/ +globle struct callFunctionItemWithArg *AddFunctionToCallListWithArgWithContext( + void *theEnv, + const char *name, + int priority, + void (*func)(void *, void *), + struct callFunctionItemWithArg *head, + intBool environmentAware, + void *context) + { + struct callFunctionItemWithArg *newPtr, *currentPtr, *lastPtr = NULL; + + newPtr = get_struct(theEnv,callFunctionItemWithArg); + + newPtr->name = name; + newPtr->func = func; + newPtr->priority = priority; + newPtr->environmentAware = (short) environmentAware; + newPtr->context = context; + + if (head == NULL) + { + newPtr->next = NULL; + return(newPtr); + } + + currentPtr = head; + while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) + { + lastPtr = currentPtr; + currentPtr = currentPtr->next; + } + + if (lastPtr == NULL) + { + newPtr->next = head; + head = newPtr; + } + else + { + newPtr->next = currentPtr; + lastPtr->next = newPtr; + } + + return(head); + } + +/**************************************************************/ +/* RemoveFunctionFromCallListWithArg: Removes a function from */ +/* a list of functions which are called to perform certain */ +/* operations (e.g. clear, reset, and bload functions). */ +/**************************************************************/ +globle struct callFunctionItemWithArg *RemoveFunctionFromCallListWithArg( + void *theEnv, + const char *name, + struct callFunctionItemWithArg *head, + int *found) + { + struct callFunctionItemWithArg *currentPtr, *lastPtr; + + *found = FALSE; + lastPtr = NULL; + currentPtr = head; + + while (currentPtr != NULL) + { + if (strcmp(name,currentPtr->name) == 0) + { + *found = TRUE; + if (lastPtr == NULL) + { head = currentPtr->next; } + else + { lastPtr->next = currentPtr->next; } + + rtn_struct(theEnv,callFunctionItemWithArg,currentPtr); + return(head); + } + + lastPtr = currentPtr; + currentPtr = currentPtr->next; + } + + return(head); + } + +/**************************************************************/ +/* DeallocateCallListWithArg: Removes all functions from a list of */ +/* functions which are called to perform certain operations */ +/* (e.g. clear, reset, and bload functions). */ +/**************************************************************/ +globle void DeallocateCallListWithArg( + void *theEnv, + struct callFunctionItemWithArg *theList) + { + struct callFunctionItemWithArg *tmpPtr, *nextPtr; + + tmpPtr = theList; + while (tmpPtr != NULL) + { + nextPtr = tmpPtr->next; + rtn_struct(theEnv,callFunctionItemWithArg,tmpPtr); + tmpPtr = nextPtr; + } + } + /*****************************************/ /* ItemHashValue: Returns the hash value */ /* for the specified value. */ /*****************************************/ -globle unsigned ItemHashValue( +globle unsigned long ItemHashValue( void *theEnv, unsigned short theType, void *theValue, - unsigned theRange) + unsigned long theRange) { + union + { + void *vv; + unsigned uv; + } fis; + switch(theType) { case FLOAT: @@ -722,17 +1012,18 @@ globle unsigned ItemHashValue( #if DEFTEMPLATE_CONSTRUCT case FACT_ADDRESS: - return(HashFact((struct fact *) theValue) % theRange); + return(((struct fact *) theValue)->hashValue % theRange); #endif case EXTERNAL_ADDRESS: + return(HashExternalAddress(ValueToExternalAddress(theValue),theRange)); + #if OBJECT_SYSTEM case INSTANCE_ADDRESS: #endif - return(((unsigned) theValue) % theRange); - - default: - break; + fis.uv = 0; + fis.vv = theValue; + return(fis.uv % theRange); } SystemError(theEnv,"UTILITY",1); @@ -745,29 +1036,13 @@ globle unsigned ItemHashValue( /* application responsiveness when CLIPS */ /* is running in the background. */ /********************************************/ -void YieldTime( +globle void YieldTime( void *theEnv) { if ((UtilityData(theEnv)->YieldTimeFunction != NULL) && UtilityData(theEnv)->YieldFunctionEnabled) { (*UtilityData(theEnv)->YieldTimeFunction)(); } } -/********************************************/ -/* SetGarbageCollectionHeuristics: */ -/********************************************/ -short SetGarbageCollectionHeuristics( - void *theEnv, - short newValue) - { - short oldValue; - - oldValue = UtilityData(theEnv)->GarbageCollectionHeuristicsEnabled; - - UtilityData(theEnv)->GarbageCollectionHeuristicsEnabled = newValue; - - return(oldValue); - } - /**********************************************/ /* EnvIncrementGCLocks: Increments the number */ /* of garbage collection locks. */ @@ -787,12 +1062,19 @@ globle void EnvDecrementGCLocks( { if (UtilityData(theEnv)->GarbageCollectionLocks > 0) { UtilityData(theEnv)->GarbageCollectionLocks--; } + + if ((UtilityData(theEnv)->CurrentGarbageFrame->topLevel) && (! CommandLineData(theEnv)->EvaluatingTopLevelCommand) && + (EvaluationData(theEnv)->CurrentExpression == NULL) && (UtilityData(theEnv)->GarbageCollectionLocks == 0)) + { + CleanCurrentGarbageFrame(theEnv,NULL); + CallPeriodicTasks(theEnv); + } } /********************************************/ /* EnablePeriodicFunctions: */ /********************************************/ -short EnablePeriodicFunctions( +globle short EnablePeriodicFunctions( void *theEnv, short value) { @@ -805,10 +1087,10 @@ short EnablePeriodicFunctions( return(oldValue); } -/********************************************/ -/* EnableYieldFunction: */ -/********************************************/ -short EnableYieldFunction( +/************************/ +/* EnableYieldFunction: */ +/************************/ +globle short EnableYieldFunction( void *theEnv, short value) { @@ -820,3 +1102,149 @@ short EnableYieldFunction( return(oldValue); } + +/*************************************************************************/ +/* AddTrackedMemory: Tracked memory is memory allocated by CLIPS that's */ +/* referenced by a variable on the stack, but not by any environment */ +/* data structure. An example would be the storage for local variables */ +/* allocated when a deffunction is executed. Tracking this memory */ +/* allows it to be removed later when using longjmp as the code that */ +/* would normally deallocate the memory would be bypassed. */ +/*************************************************************************/ +globle struct trackedMemory *AddTrackedMemory( + void *theEnv, + void *theMemory, + size_t theSize) + { + struct trackedMemory *newPtr; + + newPtr = get_struct(theEnv,trackedMemory); + + newPtr->prev = NULL; + newPtr->theMemory = theMemory; + newPtr->memSize = theSize; + newPtr->next = UtilityData(theEnv)->trackList; + UtilityData(theEnv)->trackList = newPtr; + + return newPtr; + } + +/************************/ +/* RemoveTrackedMemory: */ +/************************/ +globle void RemoveTrackedMemory( + void *theEnv, + struct trackedMemory *theTracker) + { + if (theTracker->prev == NULL) + { UtilityData(theEnv)->trackList = theTracker->next; } + else + { theTracker->prev->next = theTracker->next; } + + if (theTracker->next != NULL) + { theTracker->next->prev = theTracker->prev; } + + rtn_struct(theEnv,trackedMemory,theTracker); + } + +/******************************************/ +/* UTF8Length: Returns the logical number */ +/* of characters in a UTF8 string. */ +/******************************************/ +globle size_t UTF8Length( + const char *s) + { + size_t i = 0, length = 0; + + while (s[i] != '\0') + { + UTF8Increment(s,&i); + length++; + } + + return(length); + } + +/*********************************************/ +/* UTF8Increment: Finds the beginning of the */ +/* next character in a UTF8 string. */ +/*********************************************/ +globle void UTF8Increment( + const char *s, + size_t *i) + { + (void) (IsUTF8Start(s[++(*i)]) || + IsUTF8Start(s[++(*i)]) || + IsUTF8Start(s[++(*i)]) || + ++(*i)); + } + +/****************************************************/ +/* UTF8Offset: Converts the logical character index */ +/* in a UTF8 string to the actual byte offset. */ +/****************************************************/ +globle size_t UTF8Offset( + const char *str, + size_t charnum) + { + size_t offs = 0; + + while ((charnum > 0) && (str[offs])) + { + (void) (IsUTF8Start(str[++offs]) || + IsUTF8Start(str[++offs]) || + IsUTF8Start(str[++offs]) || + ++offs); + + charnum--; + } + + return offs; + } + +/*************************************************/ +/* UTF8CharNum: Converts the UTF8 character byte */ +/* offset to the logical character index. */ +/*************************************************/ +globle size_t UTF8CharNum( + const char *s, + size_t offset) + { + size_t charnum = 0, offs=0; + + while ((offs < offset) && (s[offs])) + { + (void) (IsUTF8Start(s[++offs]) || + IsUTF8Start(s[++offs]) || + IsUTF8Start(s[++offs]) || + ++offs); + + charnum++; + } + + return charnum; + } + +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle void IncrementGCLocks() + { + EnvIncrementGCLocks(GetCurrentEnvironment()); + } + +globle void DecrementGCLocks() + { + EnvDecrementGCLocks(GetCurrentEnvironment()); + } + +globle intBool RemovePeriodicFunction( + const char *name) + { + return EnvRemovePeriodicFunction(GetCurrentEnvironment(),name); + } + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ diff --git a/src/utility.h b/src/utility.h index 21f6196..897bf9b 100644 --- a/src/utility.h +++ b/src/utility.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* UTILITY HEADER FILE */ /*******************************************************/ @@ -21,96 +21,168 @@ /* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ +/* 6.30: Changed integer type/precision. */ +/* */ +/* Changed garbage collection algorithm. */ +/* */ +/* Added CopyString, DeleteString, */ +/* InsertInString,and EnlargeString functions. */ +/* */ +/* Used genstrncpy function instead of strncpy */ +/* function. */ +/* */ +/* Support for typed EXTERNAL_ADDRESS. */ +/* */ +/* Support for tracked memory (allows memory to */ +/* be freed if CLIPS is exited while executing). */ +/* */ +/* Added UTF-8 routines. */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_utility #define _H_utility +#ifndef _H_evaluatn +#include "evaluatn.h" +#endif + #ifdef LOCALE #undef LOCALE #endif -struct cleanupFunction +struct callFunctionItem { - char *name; - void (*ip)(void *); + const char *name; + void (*func)(void *); int priority; - struct cleanupFunction *next; + struct callFunctionItem *next; short int environmentAware; + void *context; }; -struct callFunctionItem +struct callFunctionItemWithArg { - char *name; - void (*func)(void *); + const char *name; + void (*func)(void *,void *); int priority; - struct callFunctionItem *next; + struct callFunctionItemWithArg *next; short int environmentAware; + void *context; }; - + +struct trackedMemory + { + void *theMemory; + struct trackedMemory *next; + struct trackedMemory *prev; + size_t memSize; + }; + +struct garbageFrame + { + short dirty; + short topLevel; + struct garbageFrame *priorFrame; + struct ephemeron *ephemeralSymbolList; + struct ephemeron *ephemeralFloatList; + struct ephemeron *ephemeralIntegerList; + struct ephemeron *ephemeralBitMapList; + struct ephemeron *ephemeralExternalAddressList; + struct multifield *ListOfMultifields; + struct multifield *LastMultifield; + }; + #define UTILITY_DATA 55 struct utilityData - { - struct cleanupFunction *ListOfCleanupFunctions; - struct cleanupFunction *ListOfPeriodicFunctions; + { + struct callFunctionItem *ListOfCleanupFunctions; + struct callFunctionItem *ListOfPeriodicFunctions; short GarbageCollectionLocks; - short GarbageCollectionHeuristicsEnabled; short PeriodicFunctionsEnabled; short YieldFunctionEnabled; - unsigned long EphemeralItemCount; - unsigned long EphemeralItemSize; - unsigned long CurrentEphemeralCountMax; - unsigned long CurrentEphemeralSizeMax; void (*YieldTimeFunction)(void); - int LastEvaluationDepth ; + struct trackedMemory *trackList; + struct garbageFrame MasterGarbageFrame; + struct garbageFrame *CurrentGarbageFrame; }; #define UtilityData(theEnv) ((struct utilityData *) GetEnvironmentData(theEnv,UTILITY_DATA)) - + + /* Is c the start of a utf8 sequence? */ +#define IsUTF8Start(ch) (((ch) & 0xC0) != 0x80) +#define IsUTF8MultiByteStart(ch) ((((unsigned char) ch) >= 0xC0) && (((unsigned char) ch) <= 0xF7)) +#define IsUTF8MultiByteContinuation(ch) ((((unsigned char) ch) >= 0x80) && (((unsigned char) ch) <= 0xBF)) + #ifdef _UTILITY_SOURCE_ #define LOCALE #else #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define DecrementGCLocks(theEnv) EnvDecrementGCLocks(theEnv) -#define IncrementGCLocks(theEnv) EnvIncrementGCLocks(theEnv) -#define RemovePeriodicFunction(theEnv,a) EnvRemovePeriodicFunction(theEnv,a) -#else -#define DecrementGCLocks() EnvDecrementGCLocks(GetCurrentEnvironment()) -#define IncrementGCLocks() EnvIncrementGCLocks(GetCurrentEnvironment()) -#define RemovePeriodicFunction(a) EnvRemovePeriodicFunction(GetCurrentEnvironment(),a) -#endif - LOCALE void InitializeUtilityData(void *); - LOCALE void PeriodicCleanup(void *,intBool,intBool); - LOCALE intBool AddCleanupFunction(void *,char *,void (*)(void *),int); - LOCALE intBool EnvAddPeriodicFunction(void *,char *,void (*)(void *),int); - LOCALE intBool AddPeriodicFunction(char *,void (*)(void),int); - LOCALE intBool RemoveCleanupFunction(void *,char *); - LOCALE intBool EnvRemovePeriodicFunction(void *,char *); - LOCALE char *AppendStrings(void *,char *,char *); - LOCALE char *StringPrintForm(void *,char *); - LOCALE char *AppendToString(void *,char *,char *,int *,unsigned *); - LOCALE char *AppendNToString(void *,char *,char *,unsigned,int *,unsigned *); - LOCALE char *ExpandStringWithChar(void *,int,char *,int *,unsigned *,unsigned); - LOCALE struct callFunctionItem *AddFunctionToCallList(void *,char *,int,void (*)(void *), + LOCALE intBool AddCleanupFunction(void *,const char *,void (*)(void *),int); + LOCALE intBool EnvAddPeriodicFunction(void *,const char *,void (*)(void *),int); + LOCALE intBool AddPeriodicFunction(const char *,void (*)(void),int); + LOCALE intBool RemoveCleanupFunction(void *,const char *); + LOCALE intBool EnvRemovePeriodicFunction(void *,const char *); + LOCALE char *CopyString(void *,const char *); + LOCALE void DeleteString(void *,char *); + LOCALE const char *AppendStrings(void *,const char *,const char *); + LOCALE const char *StringPrintForm(void *,const char *); + LOCALE char *AppendToString(void *,const char *,char *,size_t *,size_t *); + LOCALE char *InsertInString(void *,const char *,size_t,char *,size_t *,size_t *); + LOCALE char *AppendNToString(void *,const char *,char *,size_t,size_t *,size_t *); + LOCALE char *EnlargeString(void *,size_t,char *,size_t *,size_t *); + LOCALE char *ExpandStringWithChar(void *,int,char *,size_t *,size_t *,size_t); + LOCALE struct callFunctionItem *AddFunctionToCallList(void *,const char *,int,void (*)(void *), struct callFunctionItem *,intBool); - LOCALE struct callFunctionItem *RemoveFunctionFromCallList(void *,char *, + LOCALE struct callFunctionItem *AddFunctionToCallListWithContext(void *,const char *,int,void (*)(void *), + struct callFunctionItem *,intBool,void *); + LOCALE struct callFunctionItem *RemoveFunctionFromCallList(void *,const char *, struct callFunctionItem *, int *); LOCALE void DeallocateCallList(void *,struct callFunctionItem *); - LOCALE unsigned ItemHashValue(void *,unsigned short,void *,unsigned); + LOCALE struct callFunctionItemWithArg *AddFunctionToCallListWithArg(void *,const char *,int,void (*)(void *, void *), + struct callFunctionItemWithArg *,intBool); + LOCALE struct callFunctionItemWithArg *AddFunctionToCallListWithArgWithContext(void *,const char *,int,void (*)(void *, void *), + struct callFunctionItemWithArg *,intBool,void *); + LOCALE struct callFunctionItemWithArg *RemoveFunctionFromCallListWithArg(void *,const char *, + struct callFunctionItemWithArg *, + int *); + LOCALE void DeallocateCallListWithArg(void *,struct callFunctionItemWithArg *); + LOCALE unsigned long ItemHashValue(void *,unsigned short,void *,unsigned long); LOCALE void YieldTime(void *); - LOCALE short SetGarbageCollectionHeuristics(void *,short); LOCALE void EnvIncrementGCLocks(void *); LOCALE void EnvDecrementGCLocks(void *); LOCALE short EnablePeriodicFunctions(void *,short); LOCALE short EnableYieldFunction(void *,short); + LOCALE struct trackedMemory *AddTrackedMemory(void *,void *,size_t); + LOCALE void RemoveTrackedMemory(void *,struct trackedMemory *); + LOCALE void UTF8Increment(const char *,size_t *); + LOCALE size_t UTF8Offset(const char *,size_t); + LOCALE size_t UTF8Length(const char *); + LOCALE size_t UTF8CharNum(const char *,size_t); + LOCALE void RestorePriorGarbageFrame(void *,struct garbageFrame *,struct garbageFrame *,struct dataObject *); + LOCALE void CallCleanupFunctions(void *); + LOCALE void CallPeriodicTasks(void *); + LOCALE void CleanCurrentGarbageFrame(void *,struct dataObject *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE void IncrementGCLocks(void); + LOCALE void DecrementGCLocks(void); + LOCALE intBool RemovePeriodicFunction(const char *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_utility */ diff --git a/src/watch.c b/src/watch.c index 32dbbc5..46d96e2 100644 --- a/src/watch.c +++ b/src/watch.c @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/22/14 */ /* */ /* WATCH MODULE */ /*******************************************************/ @@ -15,9 +15,10 @@ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ -/* Brian Donnell */ +/* Brian Dantes */ /* */ /* Revision History: */ +/* */ /* 6.23: Changed name of variable log to logName */ /* because of Unix compiler warnings of shadowed */ /* definitions. */ @@ -26,6 +27,15 @@ /* */ /* Added EnvSetWatchItem function. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #define _WATCH_SOURCE_ @@ -50,9 +60,9 @@ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ - static struct watchItem *ValidWatchItem(void *,char *,int *); - static intBool RecognizeWatchRouters(void *,char *); - static int CaptureWatchPrints(void *,char *,char *); + static struct watchItem *ValidWatchItem(void *,const char *,int *); + static intBool RecognizeWatchRouters(void *,const char *); + static int CaptureWatchPrints(void *,const char *,const char *); static void DeallocateWatchData(void *); /**********************************************/ @@ -64,7 +74,7 @@ globle void InitializeWatchData( { AllocateEnvironmentData(theEnv,WATCH_DATA,sizeof(struct watchData),DeallocateWatchData); } - + /************************************************/ /* DeallocateWatchData: Deallocates environment */ /* data for watch items. */ @@ -91,12 +101,12 @@ static void DeallocateWatchData( /*************************************************************/ globle intBool AddWatchItem( void *theEnv, - char *name, + const char *name, int code, unsigned *flag, int priority, unsigned (*accessFunc)(void *,int,unsigned,struct expr *), - unsigned (*printFunc)(void *,char *,int,struct expr *)) + unsigned (*printFunc)(void *,const char *,int,struct expr *)) { struct watchItem *newPtr, *currentPtr, *lastPtr; @@ -152,7 +162,7 @@ globle intBool AddWatchItem( /*****************************************************/ globle intBool EnvWatch( void *theEnv, - char *itemName) + const char *itemName) { return(EnvSetWatchItem(theEnv,itemName,ON,NULL)); } @@ -162,7 +172,7 @@ globle intBool EnvWatch( /*********************************************************/ globle intBool EnvUnwatch( void *theEnv, - char *itemName) + const char *itemName) { return(EnvSetWatchItem(theEnv,itemName,OFF,NULL)); } @@ -173,7 +183,7 @@ globle intBool EnvUnwatch( /***********************************************************************/ globle int EnvSetWatchItem( void *theEnv, - char *itemName, + const char *itemName, unsigned newState, struct expr *argExprs) { @@ -264,13 +274,13 @@ globle int EnvSetWatchItem( /******************************************************************/ globle int EnvGetWatchItem( void *theEnv, - char *itemName) + const char *itemName) { struct watchItem *wPtr; for (wPtr = WatchData(theEnv)->ListOfWatchItems; wPtr != NULL; wPtr = wPtr->next) - { - if (strcmp(itemName,wPtr->name) == 0) + { + if (strcmp(itemName,wPtr->name) == 0) { return((int) *(wPtr->flag)); } } @@ -283,7 +293,7 @@ globle int EnvGetWatchItem( /****************************************************************/ static struct watchItem *ValidWatchItem( void *theEnv, - char *itemName, + const char *itemName, int *recognized) { struct watchItem *wPtr; @@ -304,7 +314,7 @@ static struct watchItem *ValidWatchItem( /* item in the list of watchable items. If the nth item */ /* does not exist, then NULL is returned. */ /*************************************************************/ -globle char *GetNthWatchName( +globle const char *GetNthWatchName( void *theEnv, int whichItem) { @@ -347,7 +357,7 @@ globle void WatchCommand( void *theEnv) { DATA_OBJECT theValue; - char *argument; + const char *argument; int recognized; struct watchItem *wPtr; @@ -394,7 +404,7 @@ globle void UnwatchCommand( void *theEnv) { DATA_OBJECT theValue; - char *argument; + const char *argument; int recognized; struct watchItem *wPtr; @@ -512,7 +522,7 @@ globle int GetWatchItemCommand( void *theEnv) { DATA_OBJECT theValue; - char *argument; + const char *argument; int recognized; /*============================================*/ @@ -569,14 +579,11 @@ globle void WatchFunctionDefinitions( /**************************************************/ /* RecognizeWatchRouters: Looks for WTRACE prints */ /**************************************************/ -#if IBM_TBC -#pragma argsused -#endif static intBool RecognizeWatchRouters( void *theEnv, - char *logName) + const char *logName) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(theEnv) #endif @@ -588,15 +595,12 @@ static intBool RecognizeWatchRouters( /**************************************************/ /* CaptureWatchPrints: Suppresses WTRACE messages */ /**************************************************/ -#if IBM_TBC -#pragma argsused -#endif static int CaptureWatchPrints( void *theEnv, - char *logName, - char *str) + const char *logName, + const char *str) { -#if MAC_MCW || IBM_MCW || MAC_XCD +#if MAC_XCD #pragma unused(logName) #pragma unused(str) #pragma unused(theEnv) @@ -604,5 +608,39 @@ static int CaptureWatchPrints( return(1); } +/*#####################################*/ +/* ALLOW_ENVIRONMENT_GLOBALS Functions */ +/*#####################################*/ + +#if ALLOW_ENVIRONMENT_GLOBALS + +globle intBool Watch( + const char *itemName) + { + return(EnvWatch(GetCurrentEnvironment(),itemName)); + } + +globle intBool Unwatch( + const char *itemName) + { + return(EnvUnwatch(GetCurrentEnvironment(),itemName)); + } + +globle int GetWatchItem( + const char *itemName) + { + return EnvGetWatchItem(GetCurrentEnvironment(),itemName); + } + +globle int SetWatchItem( + const char *itemName, + unsigned newState, + struct expr *argExprs) + { + return EnvSetWatchItem(GetCurrentEnvironment(),itemName,newState,argExprs); + } + +#endif + #endif /* DEBUGGING_FUNCTIONS */ diff --git a/src/watch.h b/src/watch.h index 168a83d..8e3679e 100644 --- a/src/watch.h +++ b/src/watch.h @@ -1,7 +1,7 @@ /*******************************************************/ /* "C" Language Integrated Production System */ /* */ - /* CLIPS Version 6.24 06/05/06 */ + /* CLIPS Version 6.30 08/16/14 */ /* */ /* WATCH HEADER FILE */ /*******************************************************/ @@ -17,10 +17,23 @@ /* */ /* Revision History: */ /* */ +/* 6.23: Changed name of variable log to logName */ +/* because of Unix compiler warnings of shadowed */ +/* definitions. */ +/* */ /* 6.24: Renamed BOOLEAN macro type to intBool. */ /* */ /* Added EnvSetWatchItem function. */ /* */ +/* 6.30: Removed conditional code for unsupported */ +/* compilers/operating systems (IBM_MCW, */ +/* MAC_MCW, and IBM_TBC). */ +/* */ +/* Added const qualifiers to remove C++ */ +/* deprecation warnings. */ +/* */ +/* Converted API macros to function calls. */ +/* */ /*************************************************************/ #ifndef _H_watch @@ -34,16 +47,16 @@ struct watchItem { - char *name; + const char *name; unsigned *flag; int code,priority; unsigned (*accessFunc)(void *,int,unsigned,struct expr *); - unsigned (*printFunc)(void *,char *,int,struct expr *); + unsigned (*printFunc)(void *,const char *,int,struct expr *); struct watchItem *next; }; struct watchData - { + { struct watchItem *ListOfWatchItems; }; @@ -59,35 +72,32 @@ struct watchData #define LOCALE extern #endif -#if ENVIRONMENT_API_ONLY -#define GetWatchItem(theEnv,a) EnvGetWatchItem(theEnv,a) -#define SetWatchItem(theEnv,a,b) EnvSetWatchItem(theEnv,a,b) -#define Watch(theEnv,a) EnvWatch(theEnv,a) -#define Unwatch(theEnv,a) EnvUnwatch(theEnv,a) -#else -#define GetWatchItem(a) EnvGetWatchItem(GetCurrentEnvironment(),a) -#define SetWatchItem(a,b) EnvSetWatchItem(GetCurrentEnvironment(),a,b) -#define Watch(a) EnvWatch(GetCurrentEnvironment(),a) -#define Unwatch(a) EnvUnwatch(GetCurrentEnvironment(),a) -#endif - - LOCALE void InitializeWatchData(void *); - LOCALE int EnvSetWatchItem(void *,char *,unsigned,struct expr *); - LOCALE int EnvGetWatchItem(void *,char *); - LOCALE intBool AddWatchItem(void *,char *,int,unsigned *,int, + LOCALE intBool EnvWatch(void *,const char *); + LOCALE intBool EnvUnwatch(void *,const char *); + LOCALE void InitializeWatchData(void *); + LOCALE int EnvSetWatchItem(void *,const char *,unsigned,struct expr *); + LOCALE int EnvGetWatchItem(void *,const char *); + LOCALE intBool AddWatchItem(void *,const char *,int,unsigned *,int, unsigned (*)(void *,int,unsigned,struct expr *), - unsigned (*)(void *,char *,int,struct expr *)); - LOCALE char *GetNthWatchName(void *,int); + unsigned (*)(void *,const char *,int,struct expr *)); + LOCALE const char *GetNthWatchName(void *,int); LOCALE int GetNthWatchValue(void *,int); LOCALE void WatchCommand(void *); LOCALE void UnwatchCommand(void *); LOCALE void ListWatchItemsCommand(void *); LOCALE void WatchFunctionDefinitions(void *); - LOCALE intBool EnvWatch(void *,char *); - LOCALE intBool EnvUnwatch(void *,char *); LOCALE int GetWatchItemCommand(void *); -#endif +#if ALLOW_ENVIRONMENT_GLOBALS + + LOCALE intBool Watch(const char *); + LOCALE intBool Unwatch(const char *); + LOCALE int GetWatchItem(const char *); + LOCALE int SetWatchItem(const char *,unsigned,struct expr *); + +#endif /* ALLOW_ENVIRONMENT_GLOBALS */ + +#endif /* _H_watch */ |