Beispiel #1
0
void DefruleRunTimeInitialize(
  Environment *theEnv,
  struct joinLink *rightPrime,
  struct joinLink *leftPrime)
  {
   Defmodule *theModule;
   Defrule *theRule, *theDisjunct;

   DefruleData(theEnv)->RightPrimeJoins = rightPrime;
   DefruleData(theEnv)->LeftPrimeJoins = leftPrime;

   SaveCurrentModule(theEnv);

   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      SetCurrentModule(theEnv,theModule);
      for (theRule = GetNextDefrule(theEnv,NULL);
           theRule != NULL;
           theRule = GetNextDefrule(theEnv,theRule))
        {
         for (theDisjunct = theRule;
              theDisjunct != NULL;
              theDisjunct = theDisjunct->disjunct)
           {
            theDisjunct->header.env = theEnv;
            AddBetaMemoriesToRule(theEnv,theDisjunct->lastJoin);
           }
        }
     }

   RestoreCurrentModule(theEnv);
  }
Beispiel #2
0
static void BsaveExpressions(
  FILE *fp)
  {
   struct defrule *theDefrule, *theDisjunct;
   struct defmodule *theModule;

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*======================================================*/
      /* Set the current module to the module being examined. */
      /*======================================================*/

      SetCurrentModule((void *) theModule);

      /*==================================================*/
      /* Loop through each defrule in the current module. */
      /*==================================================*/

      for (theDefrule = (struct defrule *) GetNextDefrule(NULL);
           theDefrule != NULL;
           theDefrule = (struct defrule *) GetNextDefrule(theDefrule))
        {
         /*===========================================*/
         /* Save the dynamic salience of the defrule. */
         /*===========================================*/

#if DYNAMIC_SALIENCE
         BsaveExpression(theDefrule->dynamicSalience,fp);
#endif

#if CERTAINTY_FACTORS 
         BsaveExpression(theDefrule->dynamicCF,fp);
#endif

         /*===================================*/
         /* Loop through each disjunct of the */
         /* defrule and save its RHS actions. */
         /*===================================*/

         for (theDisjunct = theDefrule;
              theDisjunct != NULL;
              theDisjunct = theDisjunct->disjunct)
           { BsaveExpression(theDisjunct->actions,fp); }
        }
     }

   /*==============================*/
   /* Set the marked flag for each */
   /* join in the join network.    */
   /*==============================*/

   MarkRuleNetwork(1);
  }
Beispiel #3
0
globle void TagRuleNetwork(
  long int *moduleCount,
  long int *ruleCount,
  long int *joinCount)
  {
   struct defmodule *modulePtr;
   struct defrule *rulePtr;
   struct joinNode *joinPtr;

   *moduleCount = 0;
   *ruleCount = 0;
   *joinCount = 0;

   MarkRuleNetwork(0);

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (modulePtr = (struct defmodule *) GetNextDefmodule(NULL);
        modulePtr != NULL;
        modulePtr = (struct defmodule *) GetNextDefmodule(modulePtr))
     {
      (*moduleCount)++;
      SetCurrentModule((void *) modulePtr);

      /*=========================*/
      /* Loop through each rule. */
      /*=========================*/

      rulePtr = (struct defrule *) GetNextDefrule(NULL);

      while (rulePtr != NULL)
        {
         rulePtr->header.bsaveID = *ruleCount;
         (*ruleCount)++;

         /*=========================*/
         /* Loop through each join. */
         /*=========================*/

         for (joinPtr = rulePtr->lastJoin;
              joinPtr != NULL;
              joinPtr = GetPreviousJoin(joinPtr))
           {
            if (joinPtr->marked == 0)
              {
               joinPtr->marked = 1;
               joinPtr->bsaveID = *joinCount;
               (*joinCount)++;
              }
           }

         if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct;
         else rulePtr = (struct defrule *) GetNextDefrule(rulePtr);
        }
     }
  }
Beispiel #4
0
static void BsaveFind()
  {
   struct defglobal *defglobalPtr;
   struct defmodule *theModule;

   /*=======================================================*/
   /* If a binary image is already loaded, then temporarily */
   /* save the count values since these will be overwritten */
   /* in the process of saving the binary image.            */
   /*=======================================================*/

   if (Bloaded())
     {
      SaveBloadCount(NumberOfDefglobalModules);
      SaveBloadCount(NumberOfDefglobals);
     }

   /*============================================*/
   /* Set the count of defglobals and defglobals */
   /* module data structures to zero.            */
   /*============================================*/

   NumberOfDefglobals = 0;
   NumberOfDefglobalModules = 0;

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*================================================*/
      /* Set the current module to the module being     */
      /* examined and increment the number of defglobal */
      /* modules encountered.                           */
      /*================================================*/

      SetCurrentModule((void *) theModule);
      NumberOfDefglobalModules++;

      /*====================================================*/
      /* Loop through each defglobal in the current module. */
      /*====================================================*/

      for (defglobalPtr = (struct defglobal *) GetNextDefglobal(NULL);
           defglobalPtr != NULL;
           defglobalPtr = (struct defglobal *) GetNextDefglobal(defglobalPtr))
        {
         /*======================================================*/
         /* Initialize the construct header for the binary save. */
         /*======================================================*/

         MarkConstructHeaderNeededItems(&defglobalPtr->header,NumberOfDefglobals++);
        }
     }
  }
Beispiel #5
0
static void BloadBinaryItem()
  {
   unsigned long int space;

   GenRead(&space,(unsigned long) sizeof(unsigned long int));
   if (NumberOfDefmodules == 0) return;

   BloadandRefresh(NumberOfDefmodules,(unsigned) sizeof(struct bsaveDefmodule),UpdateDefmodule);
   BloadandRefresh(NumberOfPortItems,(unsigned) sizeof(struct bsavePortItem),UpdatePortItem);

   SetListOfDefmodules((void *) DefmoduleArray);
   SetCurrentModule((void *) GetNextDefmodule(NULL));
  }
Beispiel #6
0
globle void MarkRuleNetwork(
  int value)
  {
   struct defrule *rulePtr;
   struct joinNode *joinPtr;
   struct defmodule *modulePtr;

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   SaveCurrentModule();
   for (modulePtr = (struct defmodule *) GetNextDefmodule(NULL);
        modulePtr != NULL;
        modulePtr = (struct defmodule *) GetNextDefmodule(modulePtr))
     {
      SetCurrentModule((void *) modulePtr);

      /*=========================*/
      /* Loop through each rule. */
      /*=========================*/

      rulePtr = (struct defrule *) GetNextDefrule(NULL);
      while (rulePtr != NULL)
        {
         /*=============================*/
         /* Mark each join for the rule */
         /* with the specified value.   */
         /*=============================*/

         joinPtr = rulePtr->lastJoin;
         while (joinPtr != NULL)
           {
            joinPtr->marked = value;
            joinPtr = GetPreviousJoin(joinPtr);
           }

         /*=================================*/
         /* Move on to the next rule or the */
         /* next disjunct for this rule.    */
         /*=================================*/

         if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct;
         else rulePtr = (struct defrule *) GetNextDefrule(rulePtr);
        }

     }

   RestoreCurrentModule();
  }
Beispiel #7
0
void SetCurrentModuleCommand(
  Environment *theEnv,
  UDFContext *context,
  UDFValue *returnValue)
  {
   UDFValue theArg;
   const char *argument;
   Defmodule *theModule;
   CLIPSLexeme *oldModuleName;

   /*=======================*/
   /* Set the return value. */
   /*=======================*/

   theModule = GetCurrentModule(theEnv);
   if (theModule == NULL)
     {
      returnValue->lexemeValue = FalseSymbol(theEnv);
      return;
     }

   oldModuleName = theModule->header.name;
   returnValue->value = oldModuleName;

   /*=====================================================*/
   /* Check for the correct number and type of arguments. */
   /*=====================================================*/

   if (! UDFFirstArgument(context,SYMBOL_BIT,&theArg))
     { return; }

   argument = theArg.lexemeValue->contents;

   /*================================================*/
   /* Set the current module to the specified value. */
   /*================================================*/

   theModule = FindDefmodule(theEnv,argument);

   if (theModule == NULL)
     {
      CantFindItemErrorMessage(theEnv,"defmodule",argument,true);
      return;
     }

   SetCurrentModule(theEnv,theModule);
  }
Beispiel #8
0
static void BeforePatternNetworkToCode()
  {
   int whichPattern = 0;
   int whichDeftemplate = 0;
   struct defmodule *theModule;
   struct deftemplate *theDeftemplate;
   struct factPatternNode *thePattern;

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*=========================*/
      /* Set the current module. */
      /*=========================*/

      SetCurrentModule((void *) theModule);

      /*======================================================*/
      /* Loop through each deftemplate in the current module. */
      /*======================================================*/

      for (theDeftemplate = (struct deftemplate *) GetNextDeftemplate(NULL);
           theDeftemplate != NULL;
           theDeftemplate = (struct deftemplate *) GetNextDeftemplate(theDeftemplate))
        {
         /*=================================================*/
         /* Assign each pattern node in the pattern network */
         /* for the deftemplate a unique integer ID.        */
         /*=================================================*/

         theDeftemplate->header.bsaveID = whichDeftemplate++;
         for (thePattern = theDeftemplate->patternNetwork;
              thePattern != NULL;
              thePattern = GetNextPatternNode(thePattern))
           { thePattern->bsaveID = whichPattern++; }
        }
     }
  }
Beispiel #9
0
static void BsaveJoins(
  FILE *fp)
  {
   struct defrule *rulePtr;
   struct joinNode *joinPtr;
   struct defmodule *theModule;

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      SetCurrentModule((void *) theModule);

      /*===========================================*/
      /* Loop through each rule and its disjuncts. */
      /*===========================================*/

      rulePtr = (struct defrule *) GetNextDefrule(NULL);
      while (rulePtr != NULL)
        {
         /*=========================================*/
         /* Loop through each join of the disjunct. */
         /*=========================================*/

         for (joinPtr = rulePtr->lastJoin;
              joinPtr != NULL;
              joinPtr = GetPreviousJoin(joinPtr))
           { if (joinPtr->marked) BsaveJoin(fp,joinPtr); }

         /*=======================================*/
         /* Move on to the next rule or disjunct. */
         /*=======================================*/

         if (rulePtr->disjunct != NULL) rulePtr = rulePtr->disjunct;
         else rulePtr = (struct defrule *) GetNextDefrule(rulePtr);
        }
     }
  }
Beispiel #10
0
static int PatternNetworkToCode(
  char *fileName,
  int fileID,
  FILE *headerFP,
  int imageID,
  int maxIndices)
  {
   int fileCount = 1;
   struct defmodule *theModule;
   struct deftemplate *theTemplate;
   struct factPatternNode *thePatternNode;
   int networkArrayCount = 0, networkArrayVersion = 1;
   FILE *networkFile = NULL;

   /*===========================================================*/
   /* Include the appropriate fact pattern network header file. */
   /*===========================================================*/

   fprintf(headerFP,"#include \"factbld.h\"\n");

   /*===============================*/
   /* Loop through all the modules. */
   /*===============================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*=========================*/
      /* Set the current module. */
      /*=========================*/

      SetCurrentModule((void *) theModule);

      /*======================================*/
      /* Loop through all of the deftemplates */
      /* in the current module.               */
      /*======================================*/

      for (theTemplate = (struct deftemplate *) GetNextDeftemplate(NULL);
           theTemplate != NULL;
           theTemplate = (struct deftemplate *) GetNextDeftemplate(theTemplate))
        {
         /*======================================================*/
         /* Loop through each pattern node in the deftemplate's  */
         /* pattern network writing its C code representation to */
         /* the file as it is traversed.                         */
         /*======================================================*/

         for (thePatternNode = theTemplate->patternNetwork;
              thePatternNode != NULL;
              thePatternNode = GetNextPatternNode(thePatternNode))
           {
            networkFile = OpenFileIfNeeded(networkFile,fileName,fileID,imageID,&fileCount,
                                         networkArrayVersion,headerFP,
                                         "struct factPatternNode",FactPrefix(),FALSE,NULL);
            if (networkFile == NULL)
              {
               CloseNetworkFiles(networkFile,maxIndices);
               return(0);
              }

            PatternNodeToCode(networkFile,thePatternNode,imageID,maxIndices);
            networkArrayCount++;
            networkFile = CloseFileIfNeeded(networkFile,&networkArrayCount,
                                            &networkArrayVersion,maxIndices,NULL,NULL);
           }
        }
     }

   /*==============================*/
   /* Close any C files left open. */
   /*==============================*/

   CloseNetworkFiles(networkFile,maxIndices);

   /*===============================*/
   /* Return TRUE to indicate the C */
   /* code was successfully saved.  */
   /*===============================*/

   return(TRUE);
  }
Beispiel #11
0
static int FindMultiImportConflict(
  struct defmodule *theModule)
  {
   struct defmodule *testModule;
   int count;
   struct portConstructItem *thePCItem;
   struct construct *theConstruct;
   void *theCItem;

   /*==========================*/
   /* Save the current module. */
   /*==========================*/

   SaveCurrentModule();

   /*============================*/
   /* Loop through every module. */
   /*============================*/

   for (testModule = (struct defmodule *) GetNextDefmodule(NULL);
        testModule != NULL;
        testModule = (struct defmodule *) GetNextDefmodule(testModule))
     {
      /*========================================*/
      /* Loop through every construct type that */
      /* can be imported/exported by a module.  */
      /*========================================*/

      for (thePCItem = ListOfPortConstructItems;
           thePCItem != NULL;
           thePCItem = thePCItem->next)
        {
         SetCurrentModule((void *) testModule);

         /*=====================================================*/
         /* Loop through every construct of the specified type. */
         /*=====================================================*/

         theConstruct = FindConstruct(thePCItem->constructName);

         for (theCItem = (*theConstruct->getNextItemFunction)(NULL);
              theCItem != NULL;
              theCItem = (*theConstruct->getNextItemFunction)(theCItem))
            {
             /*===============================================*/
             /* Check to see if the specific construct in the */
             /* module can be imported with more than one     */
             /* reference into the module we're examining for */
             /* ambiguous import  specifications.             */
             /*===============================================*/

             SetCurrentModule((void *) theModule);
             FindImportedConstruct(thePCItem->constructName,NULL,
                                   ValueToString((*theConstruct->getConstructNameFunction)
                                                 ((struct constructHeader *) theCItem)),
                                   &count,FALSE,NULL);
             if (count > 1)
               {
                ImportExportConflictMessage("defmodule",GetDefmoduleName(theModule),
                                            thePCItem->constructName,
                                            ValueToString((*theConstruct->getConstructNameFunction)
                                                          ((struct constructHeader *) theCItem)));
                RestoreCurrentModule();
                return(TRUE);
               }

             SetCurrentModule((void *) testModule);
            }
        }
     }

   /*=============================*/
   /* Restore the current module. */
   /*=============================*/

   RestoreCurrentModule();

   /*=======================================*/
   /* Return FALSE to indicate no ambiguous */
   /* references were found.                */
   /*=======================================*/

   return(FALSE);
  }
Beispiel #12
0
static int ConstructToCode(
  char *fileName,
  int fileID,
  FILE *headerFP,
  int imageID,
  int maxIndices)
  {
   int fileCount = 1;
   struct defmodule *theModule;
   struct defrule *theDefrule;
   struct joinNode *theJoin;
   int joinArrayCount = 0, joinArrayVersion = 1;
   int moduleCount = 0, moduleArrayCount = 0, moduleArrayVersion = 1;
   int defruleArrayCount = 0, defruleArrayVersion = 1;
   FILE *joinFile = NULL, *moduleFile = NULL, *defruleFile = NULL;
#if FUZZY_DEFTEMPLATES  
   struct fzSlotLocator *thePatternFv;
   int patternFvArrayCount = 0, patternFvArrayVersion = 1;
   FILE *patternFvFile = NULL;
#endif

   /*==============================================*/
   /* Include the appropriate defrule header file. */
   /*==============================================*/

   fprintf(headerFP,"#include \"ruledef.h\"\n");

   /*=========================================================*/
   /* Loop through all the modules, all the defrules, and all */
   /* the join nodes writing their C code representation to   */
   /* the file as they are traversed.                         */
   /*=========================================================*/
#if FUZZY_DEFTEMPLATES  
   /*=========================================================*/
   /* ALSO write the patternFv arrays as required if Fuzzy    */
   /*=========================================================*/
#endif

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*=========================*/
      /* Set the current module. */
      /*=========================*/

      SetCurrentModule((void *) theModule);

      /*==========================*/
      /* Save the defrule module. */
      /*==========================*/

      moduleFile = OpenFileIfNeeded(moduleFile,fileName,fileID,imageID,&fileCount,
                                    moduleArrayVersion,headerFP,
                                    "struct defruleModule",ModulePrefix(DefruleCodeItem),
                                    FALSE,NULL);

      if (moduleFile == NULL)
        {
#if FUZZY_DEFTEMPLATES  
         CloseDefruleFiles(moduleFile,defruleFile,joinFile,patternFvFile,maxIndices);
#else
         CloseDefruleFiles(moduleFile,defruleFile,joinFile,maxIndices);
#endif
         return(0);
        }

      DefruleModuleToCode(moduleFile,theModule,imageID,maxIndices,moduleCount);
      moduleFile = CloseFileIfNeeded(moduleFile,&moduleArrayCount,&moduleArrayVersion,
                                     maxIndices,NULL,NULL);

      /*=========================================*/
      /* Loop through all of the defrules (and   */
      /* their disjuncts) in the current module. */
      /*=========================================*/

      theDefrule = (struct defrule *) GetNextDefrule(NULL);

      while (theDefrule != NULL)
        {
         /*===================================*/
         /* Save the defrule data structures. */
         /*===================================*/

         defruleFile = OpenFileIfNeeded(defruleFile,fileName,fileID,imageID,&fileCount,
                                        defruleArrayVersion,headerFP,
                                        "struct defrule",ConstructPrefix(DefruleCodeItem),
                                        FALSE,NULL);
         if (defruleFile == NULL)
           {
#if FUZZY_DEFTEMPLATES 
            CloseDefruleFiles(moduleFile,defruleFile,joinFile,patternFvFile,maxIndices);
#else
            CloseDefruleFiles(moduleFile,defruleFile,joinFile,maxIndices);
#endif
            return(0);
           }

#if FUZZY_DEFTEMPLATES 
         DefruleToCode(defruleFile,theDefrule,imageID,maxIndices,
                        moduleCount, patternFvArrayCount, patternFvArrayVersion);
#else
         DefruleToCode(defruleFile,theDefrule,imageID,maxIndices,
                        moduleCount);
#endif
         defruleArrayCount++;
         defruleFile = CloseFileIfNeeded(defruleFile,&defruleArrayCount,&defruleArrayVersion,
                                         maxIndices,NULL,NULL);

#if FUZZY_DEFTEMPLATES  
         /* write out the patternFv array of fzSlotLocator structs */
         thePatternFv = theDefrule->pattern_fv_arrayPtr;
         if (thePatternFv != NULL)
           {
             int i;
             int numFzSlots = theDefrule->numberOfFuzzySlots;

             patternFvFile = OpenFileIfNeeded(patternFvFile,fileName,fileID,imageID,&fileCount,
                                      patternFvArrayVersion,headerFP,
                                      "struct fzSlotLocator",PatternFvPrefix(),FALSE,NULL);
             if (patternFvFile == NULL)
               {
                 CloseDefruleFiles(moduleFile,defruleFile,joinFile,patternFvFile,maxIndices);
                 return(0);
                }

             for (i=0; i< numFzSlots; i++)
                {
                  fprintf(patternFvFile, "{%d, %d, ",
                          thePatternFv[i].patternNum, thePatternFv[i].slotNum);
                  PrintFuzzyValueReference(patternFvFile,thePatternFv[i].fvhnPtr);

                  fprintf(patternFvFile, "}");

                  if (i != numFzSlots-1)
                     fprintf(patternFvFile, ",");
                }

             patternFvArrayCount += numFzSlots;
             patternFvFile = CloseFileIfNeeded(patternFvFile,&patternFvArrayCount,&patternFvArrayVersion,
                                            maxIndices,NULL,NULL);
           }
#endif

         /*================================*/
         /* Save the join data structures. */
         /*================================*/

         for (theJoin = theDefrule->lastJoin;
              theJoin != NULL;
              theJoin = GetPreviousJoin(theJoin))
           {
            if (theJoin->marked)
              {
               joinFile = OpenFileIfNeeded(joinFile,fileName,fileID,imageID,&fileCount,
                                        joinArrayVersion,headerFP,
                                       "struct joinNode",JoinPrefix(),FALSE,NULL);
               if (joinFile == NULL)
                 {
#if FUZZY_DEFTEMPLATES   
                  CloseDefruleFiles(moduleFile,defruleFile,joinFile,patternFvFile,maxIndices);
#else
                  CloseDefruleFiles(moduleFile,defruleFile,joinFile,maxIndices);
#endif
                  return(0);
                 }

               JoinToCode(joinFile,theJoin,imageID,maxIndices);
               joinArrayCount++;
               joinFile = CloseFileIfNeeded(joinFile,&joinArrayCount,&joinArrayVersion,
                                            maxIndices,NULL,NULL);
              }
           }

         /*==========================================*/
         /* Move on to the next disjunct or defrule. */
         /*==========================================*/

         if (theDefrule->disjunct != NULL) theDefrule = theDefrule->disjunct;
         else theDefrule = (struct defrule *) GetNextDefrule(theDefrule);
        }

      moduleCount++;
      moduleArrayCount++;
     }
#if FUZZY_DEFTEMPLATES  
   CloseDefruleFiles(moduleFile,defruleFile,joinFile,patternFvFile,maxIndices);
#else
   CloseDefruleFiles(moduleFile,defruleFile,joinFile,maxIndices);
#endif

   return(1);
  }
Beispiel #13
0
static int ParseImportSpec(
  char *readSource,
  struct token *theToken,
  struct defmodule *newModule)
  {
   struct defmodule *theModule;
   struct portItem *thePort, *oldImportSpec;
   int found, count;

   /*===========================*/
   /* Look for the module name. */
   /*===========================*/

   SavePPBuffer(" ");

   GetToken(readSource,theToken);

   if (theToken->type != SYMBOL)
     {
      SyntaxErrorMessage("defmodule import specification");
      return(TRUE);
     }

   /*=====================================*/
   /* Verify the existence of the module. */
   /*=====================================*/

   if ((theModule = (struct defmodule *)
                    FindDefmodule(ValueToString(theToken->value))) == NULL)
     {
      CantFindItemErrorMessage("defmodule",ValueToString(theToken->value));
      return(TRUE);
     }

   /*========================================*/
   /* If the specified module doesn't export */
   /* any constructs, then the import        */
   /* specification is meaningless.          */
   /*========================================*/

   if (theModule->exportList == NULL)
     {
      NotExportedErrorMessage(GetDefmoduleName(theModule),NULL,NULL);
      return(TRUE);
     }

   /*==============================================*/
   /* Parse the remaining portion of the import    */
   /* specification and return if an error occurs. */
   /*==============================================*/

   oldImportSpec = newModule->importList;
   if (ParseExportSpec(readSource,theToken,newModule,theModule)) return(TRUE);

   /*========================================================*/
   /* If the ?NONE keyword was used with the import spec,    */
   /* then no constructs were actually imported and the      */
   /* import spec does not need to be checked for conflicts. */
   /*========================================================*/

   if (newModule->importList == oldImportSpec) return(FALSE);

   /*======================================================*/
   /* Check to see if the construct being imported can be  */
   /* by the specified module. This check exported doesn't */
   /* guarantee that a specific named construct actually   */
   /* exists. It just checks that it could be exported if  */
   /* it does exists.                                      */
   /*======================================================*/

   if (newModule->importList->constructType != NULL)
     {
      /*=============================*/
      /* Look for the construct in   */
      /* the module that exports it. */
      /*=============================*/

      found = FALSE;
      for (thePort = theModule->exportList;
           (thePort != NULL) && (! found);
           thePort = thePort->next)
        {
         if (thePort->constructType == NULL) found = TRUE;
         else if (thePort->constructType == newModule->importList->constructType)
           {
            if (newModule->importList->constructName == NULL) found = TRUE;
            else if (thePort->constructName == NULL) found = TRUE;
            else if (thePort->constructName == newModule->importList->constructName)
              { found = TRUE; }
           }
        }

      /*=======================================*/
      /* If it's not exported by the specified */
      /* module, print an error message.       */
      /*=======================================*/

      if (! found)
        {
         if (newModule->importList->constructName == NULL)
           {
            NotExportedErrorMessage(GetDefmoduleName(theModule),
                                    ValueToString(newModule->importList->constructType),
                                    NULL);
           }
         else
           {
            NotExportedErrorMessage(GetDefmoduleName(theModule),
                                    ValueToString(newModule->importList->constructType),
                                    ValueToString(newModule->importList->constructName));
           }
         return(TRUE);
        }
     }

   /*======================================================*/
   /* Verify that specific named constructs actually exist */
   /* and can be seen from the module importing them.      */
   /*======================================================*/

   SaveCurrentModule();
   SetCurrentModule((void *) newModule);

   for (thePort = newModule->importList;
        thePort != NULL;
        thePort = thePort->next)
     {
      if ((thePort->constructType == NULL) || (thePort->constructName == NULL))
        { continue; }

      theModule = (struct defmodule *)
                  FindDefmodule(ValueToString(thePort->moduleName));
      SetCurrentModule(theModule);
      if (FindImportedConstruct(ValueToString(thePort->constructType),NULL,
                                ValueToString(thePort->constructName),&count,
                                TRUE,FALSE) == NULL)
        {
         NotExportedErrorMessage(GetDefmoduleName(theModule),
                                 ValueToString(thePort->constructType),
                                 ValueToString(thePort->constructName));
         RestoreCurrentModule();
         return(TRUE);
        }
     }

   RestoreCurrentModule();

   /*===============================================*/
   /* The import list has been successfully parsed. */
   /*===============================================*/

   return(FALSE);
  }
Beispiel #14
0
/*******************************************************
  NAME         : DefgenericsToCode
  DESCRIPTION  : Writes out static array code for
                   generic functions, methods, etc.
  INPUTS       : 1) The base name of the construct set
                 2) The base id for this construct
                 3) The file pointer for the header file
                 4) The base id for the construct set
                 5) The max number of indices allowed
                    in an array
  RETURNS      : -1 if no generic functions, 0 on errors,
                  1 if generic functions written
  SIDE EFFECTS : Code written to files
  NOTES        : None
 *******************************************************/
static int DefgenericsToCode(
  char *fileName,
  int fileID,
  FILE *headerFP,
  int imageID,
  int maxIndices)
  {
   int fileCount = 1;
   struct defmodule *theModule;
   DEFGENERIC *theDefgeneric;
   DEFMETHOD *theMethod;
   RESTRICTION *theRestriction;
   register unsigned i,j,k;
   int moduleCount = 0;
   int itemArrayCounts[SAVE_ITEMS];
   int itemArrayVersions[SAVE_ITEMS];
   FILE *itemFiles[SAVE_ITEMS];
   int itemReopenFlags[SAVE_ITEMS];
   struct CodeGeneratorFile itemCodeFiles[SAVE_ITEMS];

   for (i = 0 ; i < SAVE_ITEMS ; i++)
     {
      itemArrayCounts[i] = 0;
      itemArrayVersions[i] = 1;
      itemFiles[i] = NULL;
      itemReopenFlags[i] = FALSE;
      itemCodeFiles[i].filePrefix = NULL;
     }

   /* ===========================================
      Include the appropriate generic header file
      =========================================== */
   fprintf(headerFP,"#include \"genrcfun.h\"\n");

   /* =============================================================
      Loop through all the modules and all the defgenerics writing
      their C code representation to the file as they are traversed
      ============================================================= */
   theModule = (struct defmodule *) GetNextDefmodule(NULL);

   while (theModule != NULL)
     {
      SetCurrentModule((void *) theModule);

      itemFiles[MODULEI] =
         OpenFileIfNeeded(itemFiles[MODULEI],fileName,fileID,imageID,&fileCount,
                          itemArrayVersions[MODULEI],headerFP,
                          "DEFGENERIC_MODULE",ModulePrefix(DefgenericCodeItem),
                          itemReopenFlags[MODULEI],&itemCodeFiles[MODULEI]);
      if (itemFiles[MODULEI] == NULL)
        goto GenericCodeError;

      DefgenericModuleToCode(itemFiles[MODULEI],theModule,imageID,maxIndices);
      itemFiles[MODULEI] =
          CloseFileIfNeeded(itemFiles[MODULEI],&itemArrayCounts[MODULEI],
                            &itemArrayVersions[MODULEI],maxIndices,
                            &itemReopenFlags[MODULEI],&itemCodeFiles[MODULEI]);

      theDefgeneric = (DEFGENERIC *) GetNextDefgeneric(NULL);

      while (theDefgeneric != NULL)
        {
         itemFiles[GENERICI] =
            OpenFileIfNeeded(itemFiles[GENERICI],fileName,fileID,imageID,&fileCount,
                             itemArrayVersions[GENERICI],headerFP,
                             "DEFGENERIC",ConstructPrefix(DefgenericCodeItem),
                             itemReopenFlags[GENERICI],&itemCodeFiles[GENERICI]);
         if (itemFiles[GENERICI] == NULL)
           goto GenericCodeError;

         SingleDefgenericToCode(itemFiles[GENERICI],imageID,maxIndices,theDefgeneric,
                                moduleCount,itemArrayVersions[METHODI],
                                itemArrayCounts[METHODI]);
         itemArrayCounts[GENERICI]++;
         itemFiles[GENERICI] =
           CloseFileIfNeeded(itemFiles[GENERICI],&itemArrayCounts[GENERICI],
                             &itemArrayVersions[GENERICI],maxIndices,
                             &itemReopenFlags[GENERICI],&itemCodeFiles[GENERICI]);
         if (theDefgeneric->mcnt > 0)
           {

            /* ===========================================
               Make sure that all methods for a particular
               generic function go into the same array
               =========================================== */
            itemFiles[METHODI] =
                OpenFileIfNeeded(itemFiles[METHODI],fileName,fileID,imageID,&fileCount,
                                 itemArrayVersions[METHODI],headerFP,
                                 "DEFMETHOD",MethodPrefix(),
                                 itemReopenFlags[METHODI],&itemCodeFiles[METHODI]);
            if (itemFiles[METHODI] == NULL)
              goto GenericCodeError;

            for (i = 0 ; i < theDefgeneric->mcnt ; i++)
              {
               theMethod = &theDefgeneric->methods[i];
               if (i > 0)
                 fprintf(itemFiles[METHODI],",\n");
               MethodToCode(itemFiles[METHODI],imageID,theMethod,
                            itemArrayVersions[RESTRICTIONI],itemArrayCounts[RESTRICTIONI]);
               if (theMethod->restrictionCount > 0)
                 {
                  /* ========================================
                     Make sure that all restrictions for a
                     particular method go into the same array
                     ======================================== */
                  itemFiles[RESTRICTIONI] =
                     OpenFileIfNeeded(itemFiles[RESTRICTIONI],fileName,fileID,
                                      imageID,&fileCount,
                                      itemArrayVersions[RESTRICTIONI],headerFP,
                                      "RESTRICTION",RestrictionPrefix(),
                                      itemReopenFlags[RESTRICTIONI],&itemCodeFiles[RESTRICTIONI]);
                  if (itemFiles[RESTRICTIONI] == NULL)
                    goto GenericCodeError;
                  for (j = 0 ; j < theMethod->restrictionCount ; j++)
                    {
                     theRestriction = &theMethod->restrictions[j];
                     if (j > 0)
                       fprintf(itemFiles[RESTRICTIONI],",\n");
                     RestrictionToCode(itemFiles[RESTRICTIONI],imageID,theRestriction,
                                       itemArrayVersions[TYPEI],itemArrayCounts[TYPEI]);

                     if (theRestriction->tcnt > 0)
                       {
                        /* =========================================
                           Make sure that all types for a particular
                           restriction go into the same array
                           ========================================= */
                        itemFiles[TYPEI] =
                           OpenFileIfNeeded(itemFiles[TYPEI],fileName,fileID,
                                            imageID,&fileCount,
                                            itemArrayVersions[TYPEI],headerFP,
                                            "void *",TypePrefix(),
                                            itemReopenFlags[TYPEI],&itemCodeFiles[TYPEI]);
                        if (itemFiles[TYPEI] == NULL)
                          goto GenericCodeError;
                        for (k = 0 ; k < theRestriction->tcnt ; k++)
                          {
                           if (k > 0)
                             fprintf(itemFiles[TYPEI],",\n");
                           TypeToCode(itemFiles[TYPEI],imageID,
                                      theRestriction->types[k],maxIndices);
                          }
                        itemArrayCounts[TYPEI] += theRestriction->tcnt;
                        itemFiles[TYPEI] =
                           CloseFileIfNeeded(itemFiles[TYPEI],&itemArrayCounts[TYPEI],
                                             &itemArrayVersions[TYPEI],maxIndices,
                                             &itemReopenFlags[TYPEI],&itemCodeFiles[TYPEI]);
                       }
                    }
                  itemArrayCounts[RESTRICTIONI] += theMethod->restrictionCount;
                  itemFiles[RESTRICTIONI] =
                     CloseFileIfNeeded(itemFiles[RESTRICTIONI],&itemArrayCounts[RESTRICTIONI],
                                       &itemArrayVersions[RESTRICTIONI],maxIndices,
                                       &itemReopenFlags[RESTRICTIONI],&itemCodeFiles[RESTRICTIONI]);
                 }
              }
            itemArrayCounts[METHODI] += theDefgeneric->mcnt;
            itemFiles[METHODI] =
               CloseFileIfNeeded(itemFiles[METHODI],&itemArrayCounts[METHODI],
                                 &itemArrayVersions[METHODI],maxIndices,
                                 &itemReopenFlags[METHODI],&itemCodeFiles[METHODI]);
           }
         theDefgeneric = (DEFGENERIC *) GetNextDefgeneric(theDefgeneric);
        }

      theModule = (struct defmodule *) GetNextDefmodule(theModule);
      moduleCount++;
      itemArrayCounts[MODULEI]++;
     }
   CloseDefgenericFiles(itemFiles,itemReopenFlags,itemCodeFiles,maxIndices);
   return(1);

GenericCodeError:
   CloseDefgenericFiles(itemFiles,itemReopenFlags,itemCodeFiles,maxIndices);
   return(0);
  }
Beispiel #15
0
static void BsaveFind(
  Environment *theEnv)
  {
   Deftemplate *theDeftemplate;
   struct templateSlot *theSlot;
   Defmodule *theModule;

   /*=======================================================*/
   /* If a binary image is already loaded, then temporarily */
   /* save the count values since these will be overwritten */
   /* in the process of saving the binary image.            */
   /*=======================================================*/

   SaveBloadCount(theEnv,DeftemplateBinaryData(theEnv)->NumberOfDeftemplates);
   SaveBloadCount(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots);
   SaveBloadCount(theEnv,DeftemplateBinaryData(theEnv)->NumberOfTemplateModules);

   /*==================================================*/
   /* Set the count of deftemplates, deftemplate slots */
   /* and deftemplate module data structures to zero.  */
   /*==================================================*/

   DeftemplateBinaryData(theEnv)->NumberOfDeftemplates = 0;
   DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots = 0;
   DeftemplateBinaryData(theEnv)->NumberOfTemplateModules = 0;

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      /*============================================*/
      /* Set the current module to the module being */
      /* examined and increment the number of       */
      /* deftemplate modules encountered.           */
      /*============================================*/

      SetCurrentModule(theEnv,theModule);
      DeftemplateBinaryData(theEnv)->NumberOfTemplateModules++;

      /*======================================================*/
      /* Loop through each deftemplate in the current module. */
      /*======================================================*/

      for (theDeftemplate = GetNextDeftemplate(theEnv,NULL);
           theDeftemplate != NULL;
           theDeftemplate = GetNextDeftemplate(theEnv,theDeftemplate))
        {
         /*======================================================*/
         /* Initialize the construct header for the binary save. */
         /*======================================================*/

         MarkConstructHeaderNeededItems(&theDeftemplate->header,
                                        DeftemplateBinaryData(theEnv)->NumberOfDeftemplates++);

         /*=============================================================*/
         /* Loop through each slot in the deftemplate, incrementing the */
         /* slot count and marking the slot names as needed symbols.    */
         /*=============================================================*/

         for (theSlot = theDeftemplate->slotList;
              theSlot != NULL;
              theSlot = theSlot->next)
           {
            DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots++;
            theSlot->slotName->neededSymbol = true;
           }
        }

     }
  }
Beispiel #16
0
/*******************************************************
  NAME         : DefmessageHandlerWatchSupport
  DESCRIPTION  : Sets or displays handlers specified
  INPUTS       : 1) The calling function name
                 2) The logical output name for displays
                    (can be NULL)
                 4) The new set state (can be -1)
                 5) The print function (can be NULL)
                 6) The trace function (can be NULL)
                 7) The handlers expression list
  RETURNS      : TRUE if all OK,
                 FALSE otherwise
  SIDE EFFECTS : Handler trace flags set or displayed
  NOTES        : None
 *******************************************************/
static BOOLEAN DefmessageHandlerWatchSupport(
  char *funcName,
  char *log,
  int newState,
  void (*printFunc)(char *,void *,unsigned),
  void (*traceFunc)(int,void *,unsigned),
  EXPRESSION *argExprs)
  {
   struct defmodule *theModule;
   void *theClass;
   char *theHandlerStr;
   int theType;
   int argIndex = 2;
   DATA_OBJECT tmpData;

   /* ===============================
      If no handlers are specified,
      show the trace for all handlers
      in all handlers
      =============================== */
   if (argExprs == NULL)
     {
      SaveCurrentModule();
      theModule = (struct defmodule *) GetNextDefmodule(NULL);
      while (theModule != NULL)
        {
         SetCurrentModule((void *) theModule);
         if (traceFunc == NULL)
           {
            PrintRouter(log,GetDefmoduleName((void *) theModule));
            PrintRouter(log,":\n");
           }
         theClass = GetNextDefclass(NULL);
         while (theClass != NULL)
            {
             if (WatchClassHandlers(theClass,NULL,-1,log,newState,
                                    TRUE,printFunc,traceFunc) == FALSE)
                 return(FALSE);
             theClass = GetNextDefclass(theClass);
            }
          theModule = (struct defmodule *) GetNextDefmodule((void *) theModule);
         }
      RestoreCurrentModule();
      return(TRUE);
     }

   /* ================================================
      Set or show the traces for the specified handler
      ================================================ */
   while (argExprs != NULL)
     {
      if (EvaluateExpression(argExprs,&tmpData))
        return(FALSE);
      if (tmpData.type != SYMBOL)
        {
         ExpectedTypeError1(funcName,argIndex,"class name");
         return(FALSE);
        }
      theClass = (void *) LookupDefclassByMdlOrScope(DOToString(tmpData));
      if (theClass == NULL)
        {
         ExpectedTypeError1(funcName,argIndex,"class name");
         return(FALSE);
        }
      if (GetNextArgument(argExprs) != NULL)
        {
         argExprs = GetNextArgument(argExprs);
         argIndex++;
         if (EvaluateExpression(argExprs,&tmpData))
           return(FALSE);
         if (tmpData.type != SYMBOL)
           {
            ExpectedTypeError1(funcName,argIndex,"handler name");
            return(FALSE);
           }
         theHandlerStr = DOToString(tmpData);
         if (GetNextArgument(argExprs) != NULL)
           {
            argExprs = GetNextArgument(argExprs);
            argIndex++;
            if (EvaluateExpression(argExprs,&tmpData))
              return(FALSE);
            if (tmpData.type != SYMBOL)
              {
               ExpectedTypeError1(funcName,argIndex,"handler type");
               return(FALSE);
              }
            if ((theType = HandlerType(funcName,DOToString(tmpData))) == MERROR)
              return(FALSE);
           }
         else
           theType = -1;
        }
      else
        {
         theHandlerStr = NULL;
         theType = -1;
        }
      if (WatchClassHandlers(theClass,theHandlerStr,theType,log,
                             newState,FALSE,printFunc,traceFunc) == FALSE)
        {
         ExpectedTypeError1(funcName,argIndex,"handler");
         return(FALSE);
        }
      argIndex++;
      argExprs = GetNextArgument(argExprs);
     }
   return(TRUE);
  }
Beispiel #17
0
int main(int argc, char **argv) {
	   InitializeEnvironment();
       IncrementGCLocks();
       Load("src/main.clp");
       void * module = FindDefmodule("Hypnotoad");
       SetCurrentModule(module);

       zmq = zmq_init(1);
       pub = zmq_socket(zmq, ZMQ_PUB);
       zmq_bind(pub, "tcp://*:5554");

       void * sub = zmq_socket(zmq, ZMQ_SUB);
       zmq_bind(sub, "tcp://*:5555");
       zmq_setsockopt(sub, ZMQ_SUBSCRIBE, "", 0);

	   while (1) {
            char * msg, * topic;
            int topic_size;
            char * remote_filename;
		    zmq_msg_t request;

		    zmq_msg_init (&request);
		    zmq_recv (sub, &request, 0);
		    topic = zmq_msg_data (&request);
            topic_size = zmq_msg_size(&request);

            int fact = !strncmp(topic, "fact", 4);
            if (!fact) {
              remote_filename = (char *) malloc(topic_size + 1);
              strncpy(remote_filename, topic, topic_size);
            }

		    zmq_msg_close (&request);

		    zmq_msg_init (&request);
		    zmq_recv (sub, &request, 0);
		    msg = zmq_msg_data (&request);

            if (fact) {
              LoadFactsFromString(msg, zmq_msg_size(&request));
              Focus(module);
              Run(-1);
            } else {
              char * filename = tmpnam(0);

              /* dump file */
              FILE * f = fopen(filename,"w+");
              fwrite(msg, zmq_msg_size(&request), 1, f);
              fclose(f);

              char * fact = (char *) malloc(1024);
              sprintf(fact, "(remote-file \"%s\" \"%s\")\n",remote_filename,filename);

              /* load file mapping */
              Focus(module);
              LoadFactsFromString(fact, -1);

              Focus(module);
              Run(-1);

#if 0
              DATA_OBJECT res;
              Eval("(facts)",&res);
              fflush(0);
#endif              
              /* cleanup */
              free(fact);
              free(remote_filename);
              unlink(filename);
              free(filename);
            }
		    zmq_msg_close (&request);
	   }

       zmq_close(pub);
       zmq_close(sub);
       zmq_term(zmq);

       DecrementGCLocks();
}
Beispiel #18
0
static int ConstructToCode(
  char *fileName,
  int fileID,
  FILE *headerFP,
  int imageID,
  int maxIndices)
  {
   int fileCount = 1;
   struct defmodule *theModule;
   struct deftemplate *theTemplate;
   struct templateSlot *slotPtr;
   int slotCount = 0, slotArrayCount = 0, slotArrayVersion = 1;
   int moduleCount = 0, moduleArrayCount = 0, moduleArrayVersion = 1;
   int templateArrayCount = 0, templateArrayVersion = 1;
   FILE *slotFile = NULL, *moduleFile = NULL, *templateFile = NULL;

   /*==================================================*/
   /* Include the appropriate deftemplate header file. */
   /*==================================================*/

   fprintf(headerFP,"#include \"tmpltdef.h\"\n");

   /*=============================================================*/
   /* Loop through all the modules, all the deftemplates, and all */
   /* the deftemplate slots writing their C code representation   */
   /* to the file as they are traversed.                          */
   /*=============================================================*/

   theModule = (struct defmodule *) GetNextDefmodule(NULL);

   while (theModule != NULL)
     {
      SetCurrentModule((void *) theModule);

      moduleFile = OpenFileIfNeeded(moduleFile,fileName,fileID,imageID,&fileCount,
                                    moduleArrayVersion,headerFP,
                                    "struct deftemplateModule",ModulePrefix(DeftemplateCodeItem),
                                    FALSE,NULL);

      if (moduleFile == NULL)
        {
         CloseDeftemplateFiles(moduleFile,templateFile,slotFile,maxIndices);
         return(0);
        }

      DeftemplateModuleToCode(moduleFile,theModule,imageID,maxIndices,moduleCount);
      moduleFile = CloseFileIfNeeded(moduleFile,&moduleArrayCount,&moduleArrayVersion,
                                     maxIndices,NULL,NULL);

      /*=======================================================*/
      /* Loop through each of the deftemplates in this module. */
      /*=======================================================*/

      theTemplate = (struct deftemplate *) GetNextDeftemplate(NULL);

      while (theTemplate != NULL)
        {
         templateFile = OpenFileIfNeeded(templateFile,fileName,fileID,imageID,&fileCount,
                                         templateArrayVersion,headerFP,
                                         "struct deftemplate",ConstructPrefix(DeftemplateCodeItem),
                                         FALSE,NULL);
         if (templateFile == NULL)
           {
            CloseDeftemplateFiles(moduleFile,templateFile,slotFile,maxIndices);
            return(0);
           }

         DeftemplateToCode(templateFile,theTemplate,imageID,maxIndices,
                        moduleCount,slotCount);
         templateArrayCount++;
         templateFile = CloseFileIfNeeded(templateFile,&templateArrayCount,&templateArrayVersion,
                                          maxIndices,NULL,NULL);

         /*======================================================*/
         /* Loop through each of the slots for this deftemplate. */
         /*======================================================*/

         slotPtr = theTemplate->slotList;
         while (slotPtr != NULL)
           {
            slotFile = OpenFileIfNeeded(slotFile,fileName,fileID,imageID,&fileCount,
                                        slotArrayVersion,headerFP,
                                       "struct templateSlot",SlotPrefix(),FALSE,NULL);
            if (slotFile == NULL)
              {
               CloseDeftemplateFiles(moduleFile,templateFile,slotFile,maxIndices);
               return(0);
              }

            SlotToCode(slotFile,slotPtr,imageID,maxIndices,slotCount);
            slotCount++;
            slotArrayCount++;
            slotFile = CloseFileIfNeeded(slotFile,&slotArrayCount,&slotArrayVersion,
                                         maxIndices,NULL,NULL);
            slotPtr = slotPtr->next;
           }

         theTemplate = (struct deftemplate *) GetNextDeftemplate(theTemplate);
        }

      theModule = (struct defmodule *) GetNextDefmodule(theModule);
      moduleCount++;
      moduleArrayCount++;

     }

   CloseDeftemplateFiles(moduleFile,templateFile,slotFile,maxIndices);

   return(1);
  }
Beispiel #19
0
globle void Reset()
  {
   struct callFunctionItem *resetPtr;

   /*=====================================*/
   /* The reset command can't be executed */
   /* while a reset is in progress.       */
   /*=====================================*/

   if (ResetInProgress) return;

   ResetInProgress = TRUE;
   ResetReadyInProgress = TRUE;

   /*================================================*/
   /* If the reset is performed from the top level   */
   /* command prompt, reset the halt execution flag. */
   /*================================================*/

   if (CurrentEvaluationDepth == 0) SetHaltExecution(FALSE);

   /*=======================================================*/
   /* Call the before reset function to determine if the    */
   /* reset should continue. [Used by the some of the       */
   /* windowed interfaces to query the user whether a       */
   /* reset should proceed with activations on the agenda.] */
   /*=======================================================*/

   if ((BeforeResetFunction != NULL) ? ((*BeforeResetFunction)() == FALSE) :
                                       FALSE)
     {
      ResetReadyInProgress = FALSE;
      ResetInProgress = FALSE;
      return;
     }
   ResetReadyInProgress = FALSE;

   /*===========================*/
   /* Call each reset function. */
   /*===========================*/

   for (resetPtr = ListOfResetFunctions;
        (resetPtr != NULL) && (GetHaltExecution() == FALSE);
        resetPtr = resetPtr->next)
     { (*resetPtr->func)(); }

   /*============================================*/
   /* Set the current module to the MAIN module. */
   /*============================================*/

   SetCurrentModule((void *) FindDefmodule("MAIN"));

   /*===========================================*/
   /* Perform periodic cleanup if the reset was */
   /* issued from an embedded controller.       */
   /*===========================================*/

   if ((CurrentEvaluationDepth == 0) && (! EvaluatingTopLevelCommand) &&
       (CurrentExpression == NULL))
     { PeriodicCleanup(TRUE,FALSE); }

   /*===================================*/
   /* A reset is no longer in progress. */
   /*===================================*/

   ResetInProgress = FALSE;
  }
Beispiel #20
0
void CreateMainModule(
  Environment *theEnv,
  void *context)
  {
   Defmodule *newDefmodule;
   struct moduleItem *theItem;
   unsigned int i;
   struct defmoduleItemHeader *theHeader;

   /*=======================================*/
   /* Allocate the defmodule data structure */
   /* and name it the MAIN module.          */
   /*=======================================*/

   newDefmodule = get_struct(theEnv,defmodule);
   newDefmodule->header.name = CreateSymbol(theEnv,"MAIN");
   IncrementLexemeCount(newDefmodule->header.name);
   newDefmodule->header.whichModule = NULL;
   newDefmodule->header.next = NULL;
   newDefmodule->header.ppForm = NULL;
   newDefmodule->importList = NULL;
   newDefmodule->exportList = NULL;
   newDefmodule->header.bsaveID = 0L;
   newDefmodule->header.usrData = NULL;
   newDefmodule->header.constructType = DEFMODULE;
   newDefmodule->header.env = theEnv;

   /*==================================*/
   /* Initialize the array for storing */
   /* the module's construct lists.    */
   /*==================================*/

   if (DefmoduleData(theEnv)->NumberOfModuleItems == 0) newDefmodule->itemsArray = NULL;
   else
     {
      newDefmodule->itemsArray = (struct defmoduleItemHeader **)
                                 gm2(theEnv,sizeof(void *) * DefmoduleData(theEnv)->NumberOfModuleItems);
      for (i = 0, theItem = DefmoduleData(theEnv)->ListOfModuleItems;
           (i < DefmoduleData(theEnv)->NumberOfModuleItems) && (theItem != NULL);
           i++, theItem = theItem->next)
        {
         if (theItem->allocateFunction == NULL)
           { newDefmodule->itemsArray[i] = NULL; }
         else
           {
            newDefmodule->itemsArray[i] = (struct defmoduleItemHeader *)
                                          (*theItem->allocateFunction)(theEnv);
            theHeader = (struct defmoduleItemHeader *) newDefmodule->itemsArray[i];
            theHeader->theModule = newDefmodule;
            theHeader->firstItem = NULL;
            theHeader->lastItem = NULL;
           }
        }
     }

   /*=======================================*/
   /* Add the module to the list of modules */
   /* and make it the current module.       */
   /*=======================================*/

#if (! BLOAD_ONLY) && (! RUN_TIME) && DEFMODULE_CONSTRUCT
   SetNumberOfDefmodules(theEnv,1);
#endif

   DefmoduleData(theEnv)->LastDefmodule = newDefmodule;
   DefmoduleData(theEnv)->ListOfDefmodules = newDefmodule;
   SetCurrentModule(theEnv,newDefmodule);
  }
Beispiel #21
0
static bool ConstructToCode(
  Environment *theEnv,
  const char *fileName,
  const char *pathName,
  char *fileNameBuffer,
  unsigned int fileID,
  FILE *headerFP,
  unsigned int imageID,
  unsigned int maxIndices)
  {
   unsigned int fileCount = 1;
   Defmodule *theModule;
   Defglobal *theDefglobal;
   unsigned int moduleCount = 0, moduleArrayCount = 0, moduleArrayVersion = 1;
   unsigned int defglobalArrayCount = 0, defglobalArrayVersion = 1;
   FILE *moduleFile = NULL, *defglobalFile = NULL;

   /*================================================*/
   /* Include the appropriate defglobal header file. */
   /*================================================*/

   fprintf(headerFP,"#include \"globldef.h\"\n");

   /*===================================================================*/
   /* Loop through all the modules and all the defglobals writing their */
   /*  C code representation to the file as they are traversed.         */
   /*===================================================================*/

   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      SetCurrentModule(theEnv,theModule);

      moduleFile = OpenFileIfNeeded(theEnv,moduleFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount,
                                    moduleArrayVersion,headerFP,
                                    "struct defglobalModule",ModulePrefix(DefglobalData(theEnv)->DefglobalCodeItem),
                                    false,NULL);

      if (moduleFile == NULL)
        {
         CloseDefglobalFiles(theEnv,moduleFile,defglobalFile,maxIndices);
         return false;
        }

      DefglobalModuleToCode(theEnv,moduleFile,theModule,imageID,maxIndices,moduleCount);
      moduleFile = CloseFileIfNeeded(theEnv,moduleFile,&moduleArrayCount,&moduleArrayVersion,
                                     maxIndices,NULL,NULL);

      for (theDefglobal = GetNextDefglobal(theEnv,NULL);
           theDefglobal != NULL;
           theDefglobal = GetNextDefglobal(theEnv,theDefglobal))
        {
         defglobalFile = OpenFileIfNeeded(theEnv,defglobalFile,fileName,pathName,fileNameBuffer,fileID,imageID,&fileCount,
                                         defglobalArrayVersion,headerFP,
                                         "Defglobal",ConstructPrefix(DefglobalData(theEnv)->DefglobalCodeItem),
                                         false,NULL);
         if (defglobalFile == NULL)
           {
            CloseDefglobalFiles(theEnv,moduleFile,defglobalFile,maxIndices);
            return false;
           }

         DefglobalToCode(theEnv,defglobalFile,theDefglobal,imageID,maxIndices,moduleCount);
         defglobalArrayCount++;
         defglobalFile = CloseFileIfNeeded(theEnv,defglobalFile,&defglobalArrayCount,
                                           &defglobalArrayVersion,maxIndices,NULL,NULL);
        }

      moduleCount++;
      moduleArrayCount++;
     }

   CloseDefglobalFiles(theEnv,moduleFile,defglobalFile,maxIndices);

   return true;
  }
Beispiel #22
0
static void ReturnDefmodule(
  Environment *theEnv,
  Defmodule *theDefmodule,
  bool environmentClear)
  {
   unsigned int i;
   struct moduleItem *theItem;
   struct portItem *theSpec, *nextSpec;

   /*=====================================================*/
   /* Set the current module to the module being deleted. */
   /*=====================================================*/

   if (theDefmodule == NULL) return;

   if (! environmentClear)
     { SetCurrentModule(theEnv,theDefmodule); }

   /*============================================*/
   /* Call the free functions for the constructs */
   /* belonging to this module.                  */
   /*============================================*/

   if (theDefmodule->itemsArray != NULL)
     {
      if (! environmentClear)
        {
         for (i = 0, theItem = DefmoduleData(theEnv)->ListOfModuleItems;
              (i < DefmoduleData(theEnv)->NumberOfModuleItems) && (theItem != NULL);
              i++, theItem = theItem->next)
           {
            if (theItem->freeFunction != NULL)
              { (*theItem->freeFunction)(theEnv,theDefmodule->itemsArray[i]); }
           }
        }

      rm(theEnv,theDefmodule->itemsArray,sizeof(void *) * DefmoduleData(theEnv)->NumberOfModuleItems);
    }

   /*======================================================*/
   /* Decrement the symbol count for the defmodule's name. */
   /*======================================================*/

   if (! environmentClear)
     { ReleaseLexeme(theEnv,theDefmodule->header.name); }

   /*====================================*/
   /* Free the items in the import list. */
   /*====================================*/

   theSpec = theDefmodule->importList;
   while (theSpec != NULL)
     {
      nextSpec = theSpec->next;
      if (! environmentClear)
        {
         if (theSpec->moduleName != NULL) ReleaseLexeme(theEnv,theSpec->moduleName);
         if (theSpec->constructType != NULL) ReleaseLexeme(theEnv,theSpec->constructType);
         if (theSpec->constructName != NULL) ReleaseLexeme(theEnv,theSpec->constructName);
        }
      rtn_struct(theEnv,portItem,theSpec);
      theSpec = nextSpec;
     }

   /*====================================*/
   /* Free the items in the export list. */
   /*====================================*/

   theSpec = theDefmodule->exportList;
   while (theSpec != NULL)
     {
      nextSpec = theSpec->next;
      if (! environmentClear)
        {
         if (theSpec->moduleName != NULL) ReleaseLexeme(theEnv,theSpec->moduleName);
         if (theSpec->constructType != NULL) ReleaseLexeme(theEnv,theSpec->constructType);
         if (theSpec->constructName != NULL) ReleaseLexeme(theEnv,theSpec->constructName);
        }
      rtn_struct(theEnv,portItem,theSpec);
      theSpec = nextSpec;
     }

   /*=========================================*/
   /* Free the defmodule pretty print string. */
   /*=========================================*/

   if (theDefmodule->header.ppForm != NULL)
     {
      rm(theEnv,(void *) theDefmodule->header.ppForm,
         sizeof(char) * (strlen(theDefmodule->header.ppForm) + 1));
     }

   /*=======================*/
   /* Return the user data. */
   /*=======================*/

   ClearUserDataList(theEnv,theDefmodule->header.usrData);

   /*======================================*/
   /* Return the defmodule data structure. */
   /*======================================*/

   rtn_struct(theEnv,defmodule,theDefmodule);
  }
Beispiel #23
0
static void BsaveBinaryItem(
  Environment *theEnv,
  FILE *fp)
  {
   size_t space;
   Deftemplate *theDeftemplate;
   struct bsaveDeftemplate tempDeftemplate;
   struct templateSlot *theSlot;
   struct bsaveTemplateSlot tempTemplateSlot;
   struct bsaveDeftemplateModule tempTemplateModule;
   Defmodule *theModule;
   struct deftemplateModule *theModuleItem;

   /*============================================================*/
   /* Write out the amount of space taken up by the deftemplate, */
   /* deftemplateModule, and templateSlot data structures in the */
   /* binary image.                                              */
   /*============================================================*/

   space = (DeftemplateBinaryData(theEnv)->NumberOfDeftemplates * sizeof(struct bsaveDeftemplate)) +
           (DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots * sizeof(struct bsaveTemplateSlot)) +
           (DeftemplateBinaryData(theEnv)->NumberOfTemplateModules * sizeof(struct bsaveDeftemplateModule));
   GenWrite(&space,sizeof(size_t),fp);

   /*===================================================*/
   /* Write out each deftemplate module data structure. */
   /*===================================================*/

   DeftemplateBinaryData(theEnv)->NumberOfDeftemplates = 0;
   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      SetCurrentModule(theEnv,theModule);

      theModuleItem = (struct deftemplateModule *)
                      GetModuleItem(theEnv,NULL,FindModuleItem(theEnv,"deftemplate")->moduleIndex);
      AssignBsaveDefmdlItemHdrVals(&tempTemplateModule.header,
                                           &theModuleItem->header);
      GenWrite(&tempTemplateModule,sizeof(struct bsaveDeftemplateModule),fp);
     }

   /*============================================*/
   /* Write out each deftemplate data structure. */
   /*============================================*/

   DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots = 0;
   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      SetCurrentModule(theEnv,theModule);

      for (theDeftemplate = GetNextDeftemplate(theEnv,NULL);
           theDeftemplate != NULL;
           theDeftemplate = GetNextDeftemplate(theEnv,theDeftemplate))
        {
         AssignBsaveConstructHeaderVals(&tempDeftemplate.header,
                                          &theDeftemplate->header);
         tempDeftemplate.implied = theDeftemplate->implied;
         tempDeftemplate.numberOfSlots = theDeftemplate->numberOfSlots;
         tempDeftemplate.patternNetwork = BsaveFactPatternIndex(theDeftemplate->patternNetwork);

         if (theDeftemplate->slotList != NULL)
           { tempDeftemplate.slotList = DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots; }
         else
           { tempDeftemplate.slotList = ULONG_MAX; }

         GenWrite(&tempDeftemplate,sizeof(struct bsaveDeftemplate),fp);

         DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots += theDeftemplate->numberOfSlots;
        }
     }

   /*=============================================*/
   /* Write out each templateSlot data structure. */
   /*=============================================*/

   for (theModule = GetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theEnv,theModule))
     {
      SetCurrentModule(theEnv,theModule);

      for (theDeftemplate = GetNextDeftemplate(theEnv,NULL);
           theDeftemplate != NULL;
           theDeftemplate = GetNextDeftemplate(theEnv,theDeftemplate))
        {
         for (theSlot = theDeftemplate->slotList;
              theSlot != NULL;
              theSlot = theSlot->next)
           {
            tempTemplateSlot.constraints = ConstraintIndex(theSlot->constraints);
            tempTemplateSlot.slotName = theSlot->slotName->bucket;
            tempTemplateSlot.multislot = theSlot->multislot;
            tempTemplateSlot.noDefault = theSlot->noDefault;
            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 = ULONG_MAX;

            GenWrite(&tempTemplateSlot,sizeof(struct bsaveTemplateSlot),fp);
           }
        }
     }

   /*=============================================================*/
   /* If a binary image was already loaded when the bsave command */
   /* was issued, then restore the counts indicating the number   */
   /* of deftemplates, deftemplate modules, and deftemplate slots */
   /* in the binary image (these were overwritten by the binary   */
   /* save).                                                      */
   /*=============================================================*/

   RestoreBloadCount(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfDeftemplates);
   RestoreBloadCount(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateSlots);
   RestoreBloadCount(theEnv,&DeftemplateBinaryData(theEnv)->NumberOfTemplateModules);
  }
Beispiel #24
0
void Reset(
  Environment *theEnv)
  {
   struct voidCallFunctionItem *resetPtr;
   GCBlock gcb;

   /*=====================================*/
   /* The reset command can't be executed */
   /* while a reset is in progress.       */
   /*=====================================*/

   if (ConstructData(theEnv)->ResetInProgress) return;

   ConstructData(theEnv)->ResetInProgress = true;
   ConstructData(theEnv)->ResetReadyInProgress = true;
   
   /*=====================================*/
   /* If embedded, clear the error flags. */
   /*=====================================*/
   
   if (EvaluationData(theEnv)->CurrentExpression == NULL)
     { ResetErrorFlags(theEnv); }
   SetErrorValue(theEnv,NULL);
    
   /*========================================*/
   /* Set up the frame for tracking garbage. */
   /*========================================*/

   GCBlockStart(theEnv,&gcb);

   /*=======================================================*/
   /* Call the before reset function to determine if the    */
   /* reset should continue. [Used by the some of the       */
   /* windowed interfaces to query the user whether a       */
   /* reset should proceed with activations on the agenda.] */
   /*=======================================================*/

   if ((ConstructData(theEnv)->BeforeResetCallback != NULL) ?
       ((*ConstructData(theEnv)->BeforeResetCallback)(theEnv) == false) : false)
     {
      ConstructData(theEnv)->ResetReadyInProgress = false;
      ConstructData(theEnv)->ResetInProgress = false;
      return;
     }
   ConstructData(theEnv)->ResetReadyInProgress = false;

   /*===========================*/
   /* Call each reset function. */
   /*===========================*/

   for (resetPtr = ConstructData(theEnv)->ListOfResetFunctions;
        (resetPtr != NULL) && (GetHaltExecution(theEnv) == false);
        resetPtr = resetPtr->next)
     { (*resetPtr->func)(theEnv,resetPtr->context); }

   /*============================================*/
   /* Set the current module to the MAIN module. */
   /*============================================*/

   SetCurrentModule(theEnv,FindDefmodule(theEnv,"MAIN"));

   /*===========================================*/
   /* Perform periodic cleanup if the reset was */
   /* issued from an embedded controller.       */
   /*===========================================*/

   GCBlockEnd(theEnv,&gcb);
   CallPeriodicTasks(theEnv);

   /*===================================*/
   /* A reset is no longer in progress. */
   /*===================================*/

   ConstructData(theEnv)->ResetInProgress = false;
  }
Beispiel #25
0
static void BsaveFind()
  {
   struct defrule *theDefrule, *theDisjunct;
   struct defmodule *theModule;

   /*=======================================================*/
   /* If a binary image is already loaded, then temporarily */
   /* save the count values since these will be overwritten */
   /* in the process of saving the binary image.            */
   /*=======================================================*/

   if (Bloaded())
     {
      SaveBloadCount(NumberOfDefruleModules);
      SaveBloadCount(NumberOfDefrules);
      SaveBloadCount(NumberOfJoins);
#if FUZZY_DEFTEMPLATES 
      SaveBloadCount(NumberOfPatternFuzzyValues);
#endif
     }

   /*====================================================*/
   /* Set the binary save ID for defrule data structures */
   /* and count the number of each type.                 */
   /*====================================================*/

   TagRuleNetwork(&NumberOfDefruleModules,&NumberOfDefrules,&NumberOfJoins);

#if FUZZY_DEFTEMPLATES 
   NumberOfPatternFuzzyValues = 0;
#endif

   /*===========================*/
   /* Loop through each module. */
   /*===========================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      /*============================*/
      /* Set the current module to  */
      /* the module being examined. */
      /*============================*/

      SetCurrentModule((void *) theModule);

      /*==================================================*/
      /* Loop through each defrule in the current module. */
      /*==================================================*/

      for (theDefrule = (struct defrule *) GetNextDefrule(NULL);
           theDefrule != NULL;
           theDefrule = (struct defrule *) GetNextDefrule(theDefrule))
        {
         /*================================================*/
         /* Initialize the construct header for the binary */
         /* save. The binary save ID has already been set. */
         /*================================================*/

         MarkConstructHeaderNeededItems(&theDefrule->header,theDefrule->header.bsaveID);

         /*===========================================*/
         /* Count and mark data structures associated */
         /* with dynamic salience.                    */
         /*===========================================*/

#if DYNAMIC_SALIENCE
         ExpressionCount += ExpressionSize(theDefrule->dynamicSalience);
         MarkNeededItems(theDefrule->dynamicSalience);
#endif

#if CERTAINTY_FACTORS 
         ExpressionCount += ExpressionSize(theDefrule->dynamicCF);
         MarkNeededItems(theDefrule->dynamicCF);
#endif

         /*==========================================*/
         /* Loop through each disjunct of the rule   */
         /* counting and marking the data structures */
         /* associated with RHS actions.             */
         /*==========================================*/

         for (theDisjunct = theDefrule;
              theDisjunct != NULL;
              theDisjunct = theDisjunct->disjunct)
           {
            ExpressionCount += ExpressionSize(theDisjunct->actions);
            MarkNeededItems(theDisjunct->actions);
#if FUZZY_DEFTEMPLATES 
            /* count the number of PatternFuzzyValues store with each rule
               and mark all of the FuzzyValues pointed to as needed
            */
            if (theDisjunct->numberOfFuzzySlots > 0)
              { int i;
                FUZZY_VALUE_HN *fvhnPtr;
                struct fzSlotLocator  *fvSLPtr;

                NumberOfPatternFuzzyValues += theDisjunct->numberOfFuzzySlots;
                for (i= 0; i<theDisjunct->numberOfFuzzySlots; i++)
                   {
                     fvSLPtr = theDisjunct->pattern_fv_arrayPtr + i;
                     fvhnPtr = fvSLPtr->fvhnPtr;
                     if (fvhnPtr != NULL)
                       { fvhnPtr->neededFuzzyValue = TRUE;
                       }
                   }
              }
#endif
           }
        }
     }

   /*===============================*/
   /* Reset the bsave tags assigned */
   /* to defrule data structures.   */
   /*===============================*/

   MarkRuleNetwork(1);
  }
Beispiel #26
0
static void BsaveBinaryItem(
  FILE *fp)
  {
   unsigned long int space;
   struct defglobal *theDefglobal;
   struct bsaveDefglobal newDefglobal;
   struct defmodule *theModule;
   struct bsaveDefglobalModule tempDefglobalModule;
   struct defglobalModule *theModuleItem;

   /*==========================================================*/
   /* Write out the amount of space taken up by the defglobal  */
   /* and defglobalModule data structures in the binary image. */
   /*==========================================================*/

   space = NumberOfDefglobals * sizeof(struct bsaveDefglobal) +
           (NumberOfDefglobalModules * sizeof(struct bsaveDefglobalModule));
   GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp);

   /*=================================================*/
   /* Write out each defglobal module data structure. */
   /*=================================================*/

   NumberOfDefglobals = 0;
   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      SetCurrentModule((void *) theModule);

      theModuleItem = (struct defglobalModule *)
                      GetModuleItem(NULL,FindModuleItem("defglobal")->moduleIndex);
      AssignBsaveDefmdlItemHdrVals(&tempDefglobalModule.header,
                                           &theModuleItem->header);
      GenWrite(&tempDefglobalModule,(unsigned long) sizeof(struct bsaveDefglobalModule),fp);
     }

   /*===========================*/
   /* Write out each defglobal. */
   /*===========================*/

   NumberOfDefglobals = 0;
   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      SetCurrentModule((void *) theModule);

      for (theDefglobal = (struct defglobal *) GetNextDefglobal(NULL);
           theDefglobal != NULL;
           theDefglobal = (struct defglobal *) GetNextDefglobal(theDefglobal))
        {
         AssignBsaveConstructHeaderVals(&newDefglobal.header,
                                          &theDefglobal->header);
         newDefglobal.initial = HashedExpressionIndex(theDefglobal->initial);

         GenWrite(&newDefglobal,(unsigned long) sizeof(struct bsaveDefglobal),fp);
        }
     }

   /*=============================================================*/
   /* If a binary image was already loaded when the bsave command */
   /* was issued, then restore the counts indicating the number   */
   /* of defglobals and defglobal modules in the binary image     */
   /* (these were overwritten by the binary save).                */
   /*=============================================================*/

   if (Bloaded())
     {
      RestoreBloadCount(&NumberOfDefglobalModules);
      RestoreBloadCount(&NumberOfDefglobals);
     }
  }
Beispiel #27
0
static void BsaveBinaryItem(
  FILE *fp)
  {
   unsigned long int space;
   struct defrule *theDefrule; 
#if FUZZY_DEFTEMPLATES
   struct defrule *theDisjunct;
#endif
   struct defmodule *theModule;
   struct defruleModule *theModuleItem;
   struct bsaveDefruleModule tempDefruleModule;
#if CERTAINTY_FACTORS
   long int disjunctExpressionCountCF = 0L;
#endif

   /*===============================================*/
   /* Write out the space required by the defrules. */
   /*===============================================*/

   space = (NumberOfDefrules * sizeof(struct bsaveDefrule)) +
           (NumberOfJoins * sizeof(struct bsaveJoinNode)) +
#if FUZZY_DEFTEMPLATES  
           (NumberOfPatternFuzzyValues * sizeof(struct fzSlotLocator)) +
#endif
           (NumberOfDefruleModules * sizeof(struct bsaveDefruleModule));
   GenWrite(&space,(unsigned long) sizeof(unsigned long int),fp);

   /*===============================================*/
   /* Write out each defrule module data structure. */
   /*===============================================*/

   NumberOfDefrules = 0;
#if FUZZY_DEFTEMPLATES  
   NumberOfPatternFuzzyValues = 0;
#endif
   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      SetCurrentModule((void *) theModule);

      theModuleItem = (struct defruleModule *)
                      GetModuleItem(NULL,FindModuleItem("defrule")->moduleIndex);
      AssignBsaveDefmdlItemHdrVals(&tempDefruleModule.header,
                                           &theModuleItem->header);
      GenWrite(&tempDefruleModule,(unsigned long) sizeof(struct bsaveDefruleModule),fp);
     }

   /*========================================*/
   /* Write out each defrule data structure. */
   /*========================================*/

   for (theModule = (struct defmodule *) GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = (struct defmodule *) GetNextDefmodule(theModule))
     {
      SetCurrentModule((void *) theModule);

      for (theDefrule = (struct defrule *) GetNextDefrule(NULL);
           theDefrule != NULL;
           theDefrule = (struct defrule *) GetNextDefrule(theDefrule))
        { BsaveDisjuncts(fp,theDefrule); }
     }
#if FUZZY_DEFTEMPLATES 
   /*====================================*/
   /* Write out the PatternFuzzyValues . */
   /*====================================*/

   theModule = (struct defmodule *) GetNextDefmodule(NULL);
   while (theModule != NULL)
     {
      SetCurrentModule((VOID *) theModule);

      theDefrule = (struct defrule *) GetNextDefrule(NULL);
      while (theDefrule != NULL)
        {
         theDisjunct = theDefrule;
         while (theDisjunct != NULL)
           {
            int i;
            struct bsaveFzSlotLocator tempFZSlotLocator;

            for (i=0; i<theDisjunct->numberOfFuzzySlots; i++)
               {
                 FUZZY_VALUE_HN *fvhnPtr;
                 struct fzSlotLocator  *fvSLPtr;

                 fvSLPtr = theDisjunct->pattern_fv_arrayPtr + i;
                 fvhnPtr = fvSLPtr->fvhnPtr;

                 tempFZSlotLocator.patternNum = fvSLPtr->patternNum;
                 tempFZSlotLocator.slotNum = fvSLPtr->slotNum;
                 tempFZSlotLocator.fvhnPtr = fvhnPtr->bucket;

                 GenWrite(&tempFZSlotLocator,(unsigned long) sizeof(struct bsaveFzSlotLocator),fp);
                }

            theDisjunct = theDisjunct->disjunct;
           }
         theDefrule = (struct defrule *) GetNextDefrule(theDefrule);
        }

      theModule = (struct defmodule *) GetNextDefmodule(theModule);
     }
#endif

   /*=============================*/
   /* Write out the Rete Network. */
   /*=============================*/

   MarkRuleNetwork(1);
   BsaveJoins(fp);

   /*=============================================================*/
   /* If a binary image was already loaded when the bsave command */
   /* was issued, then restore the counts indicating the number   */
   /* of defrules, defrule modules, and joins in the binary image */
   /* (these were overwritten by the binary save).                */
   /*=============================================================*/

   if (Bloaded())
     {
      RestoreBloadCount(&NumberOfDefruleModules);
      RestoreBloadCount(&NumberOfDefrules);
      RestoreBloadCount(&NumberOfJoins);
#if FUZZY_DEFTEMPLATES
      RestoreBloadCount(&NumberOfPatternFuzzyValues);
#endif
     }
  }
Beispiel #28
0
/*******************************************************
  NAME         : DefinstancesToCode
  DESCRIPTION  : Writes out static array code for
                   definstances
  INPUTS       : 1) The base name of the construct set
                 2) The base id for this construct
                 3) The file pointer for the header file
                 4) The base id for the construct set
                 5) The max number of indices allowed
                    in an array
  RETURNS      : -1 if no definstances, 0 on errors,
                  1 if definstances written
  SIDE EFFECTS : Code written to files
  NOTES        : None
 *******************************************************/
static int DefinstancesToCode(
  char *fileName,
  int fileID,
  FILE *headerFP,
  int imageID,
  int maxIndices)
  {
   int fileCount = 1;
   struct defmodule *theModule;
   DEFINSTANCES *theDefinstances;
   int moduleCount = 0, moduleArrayCount = 0, moduleArrayVersion = 1;
   int definstancesArrayCount = 0, definstancesArrayVersion = 1;
   FILE *moduleFile = NULL, *definstancesFile = NULL;

   /* ================================================
      Include the appropriate definstances header file
      ================================================ */
   fprintf(headerFP,"#include \"defins.h\"\n");

   /* =============================================================
      Loop through all the modules and all the definstances writing
      their C code representation to the file as they are traversed
      ============================================================= */
   theModule = (struct defmodule *) GetNextDefmodule(NULL);

   while (theModule != NULL)
     {
      SetCurrentModule((void *) theModule);

      moduleFile = OpenFileIfNeeded(moduleFile,fileName,fileID,imageID,&fileCount,
                                    moduleArrayVersion,headerFP,
                                    "DEFINSTANCES_MODULE",ModulePrefix(DefinstancesCodeItem),
                                    FALSE,NULL);

      if (moduleFile == NULL)
        {
         CloseDefinstancesFiles(moduleFile,definstancesFile,maxIndices);
         return(0);
        }

      DefinstancesModuleToCode(moduleFile,theModule,imageID,maxIndices);
      moduleFile = CloseFileIfNeeded(moduleFile,&moduleArrayCount,&moduleArrayVersion,
                                     maxIndices,NULL,NULL);

      theDefinstances = (DEFINSTANCES *) GetNextDefinstances(NULL);

      while (theDefinstances != NULL)
        {
         definstancesFile = OpenFileIfNeeded(definstancesFile,fileName,fileID,imageID,&fileCount,
                                             definstancesArrayVersion,headerFP,
                                             "DEFINSTANCES",ConstructPrefix(DefinstancesCodeItem),
                                             FALSE,NULL);
         if (definstancesFile == NULL)
           {
            CloseDefinstancesFiles(moduleFile,definstancesFile,maxIndices);
            return(0);
           }

         SingleDefinstancesToCode(definstancesFile,theDefinstances,imageID,
                                  maxIndices,moduleCount);
         definstancesArrayCount++;
         definstancesFile = CloseFileIfNeeded(definstancesFile,&definstancesArrayCount,
                                              &definstancesArrayVersion,maxIndices,NULL,NULL);

         theDefinstances = (DEFINSTANCES *) GetNextDefinstances(theDefinstances);
        }

      theModule = (struct defmodule *) GetNextDefmodule(theModule);
      moduleCount++;
      moduleArrayCount++;
     }

   CloseDefinstancesFiles(moduleFile,definstancesFile,maxIndices);

   return(1);
  }
Beispiel #29
0
static void ClearBload()
  {
   unsigned long int space;
   long i;
   struct patternParser *theParser = NULL;
   struct patternEntity *theEntity = NULL;
   void *theModule;

   /*===========================================*/
   /* Delete all known entities before removing */
   /* the defrule data structures.              */
   /*===========================================*/

   GetNextPatternEntity(&theParser,&theEntity);
   while (theEntity != NULL)
     {
      (*theEntity->theInfo->base.deleteFunction)(theEntity);
      theEntity = NULL;
      GetNextPatternEntity(&theParser,&theEntity);
     }

   /*=========================================*/
   /* Remove all activations from the agenda. */
   /*=========================================*/

   SaveCurrentModule();
   for (theModule = GetNextDefmodule(NULL);
        theModule != NULL;
        theModule = GetNextDefmodule(theModule))
     {
      SetCurrentModule(theModule);
      RemoveAllActivations();
     }
   RestoreCurrentModule();
   ClearFocusStack();

   /*==========================================================*/
   /* Remove all partial matches from the beta memories in the */
   /* join network. Alpha memories do not need to be examined  */
   /* since all pattern entities have been deleted by now.     */
   /*==========================================================*/

   for (i = 0; i < NumberOfJoins; i++)
     { FlushAlphaBetaMemory(JoinArray[i].beta); }

   /*================================================*/
   /* Decrement the symbol count for each rule name. */
   /*================================================*/

   for (i = 0; i < NumberOfDefrules; i++)
     { UnmarkConstructHeader(&DefruleArray[i].header); }

   /*==================================================*/
   /* Return the space allocated for the bload arrays. */
   /*==================================================*/

   space = NumberOfDefruleModules * sizeof(struct defruleModule);
   if (space != 0) genlongfree((void *) ModuleArray,space);

   space = NumberOfDefrules * sizeof(struct defrule);
   if (space != 0) genlongfree((void *) DefruleArray,space);

#if FUZZY_DEFTEMPLATES  
   space = NumberOfPatternFuzzyValues * sizeof(struct fzSlotLocator);
   if (space != 0) genlongfree((void *) PatternFuzzyValueArray,space);
#endif

   space = NumberOfJoins * sizeof(struct joinNode);
   if (space != 0) genlongfree((void *) JoinArray,space);
  }
Beispiel #30
0
globle int ParseDefmodule(
  char *readSource)
  {
   SYMBOL_HN *defmoduleName;
   struct defmodule *newDefmodule;
   struct token inputToken;
   int i;
   struct moduleItem *theItem;
   struct portItem *portSpecs, *nextSpec;
   struct defmoduleItemHeader *theHeader;
   struct callFunctionItem *defineFunctions;
   struct defmodule *redefiningMainModule = NULL;
   int parseError;
   struct portItem *oldImportList, *oldExportList;
   short overwrite = FALSE;

   /*================================================*/
   /* Flush the buffer which stores the pretty print */
   /* representation for a module.  Add the already  */
   /* parsed keyword defmodule to this buffer.       */
   /*================================================*/

   SetPPBufferStatus(ON);
   FlushPPBuffer();
   SetIndentDepth(3);
   SavePPBuffer("(defmodule ");

   /*===============================*/
   /* Modules cannot be loaded when */
   /* a binary load is in effect.   */
   /*===============================*/

#if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE
   if ((Bloaded() == TRUE) && (! CheckSyntaxMode))
     {
      CannotLoadWithBloadMessage("defmodule");
      return(TRUE);
     }
#endif

   /*=====================================================*/
   /* Parse the name and comment fields of the defmodule. */
   /* Remove the defmodule if it already exists.          */
   /*=====================================================*/

   defmoduleName = GetConstructNameAndComment(readSource,&inputToken,"defmodule",
                                              FindDefmodule,DeleteDefmodule,"+",
                                              TRUE,TRUE,FALSE);
   if (defmoduleName == NULL) { return(TRUE); }

   if (strcmp(ValueToString(defmoduleName),"MAIN") == 0)
     { redefiningMainModule = (struct defmodule *) FindDefmodule("MAIN"); }

   /*==============================================*/
   /* Create the defmodule structure if necessary. */
   /*==============================================*/

   if (redefiningMainModule == NULL)
     {
      newDefmodule = (struct defmodule *) FindDefmodule(ValueToString(defmoduleName));
      if (newDefmodule)
        { overwrite = TRUE; }
      else
        {
         newDefmodule = get_struct(defmodule);
         newDefmodule->name = defmoduleName;
         newDefmodule->usrData = NULL;
         newDefmodule->next = NULL;
        }
     }
   else
     {
      overwrite = TRUE;
      newDefmodule = redefiningMainModule;
     }

   if (overwrite)
     {
      oldImportList = newDefmodule->importList;
      oldExportList = newDefmodule->exportList;
     }

   newDefmodule->importList = NULL;
   newDefmodule->exportList = NULL;

   /*===================================*/
   /* Finish parsing the defmodule (its */
   /* import/export specifications).    */
   /*===================================*/

   parseError = ParsePortSpecifications(readSource,&inputToken,newDefmodule);

   /*====================================*/
   /* Check for import/export conflicts. */
   /*====================================*/

   if (! parseError) parseError = FindMultiImportConflict(newDefmodule);

   /*======================================================*/
   /* If an error occured in parsing or an import conflict */
   /* was detected, abort the definition of the defmodule. */
   /* If we're only checking syntax, then we want to exit  */
   /* at this point as well.                               */
   /*======================================================*/

   if (parseError || CheckSyntaxMode)
     {
      while (newDefmodule->importList != NULL)
        {
         nextSpec = newDefmodule->importList->next;
         rtn_struct(portItem,newDefmodule->importList);
         newDefmodule->importList = nextSpec;
        }

      while (newDefmodule->exportList != NULL)
        {
         nextSpec = newDefmodule->exportList->next;
         rtn_struct(portItem,newDefmodule->exportList);
         newDefmodule->exportList = nextSpec;
        }

      if ((redefiningMainModule == NULL) && (! overwrite))
        { rtn_struct(defmodule,newDefmodule); }

      if (overwrite)
        {
         newDefmodule->importList = oldImportList;
         newDefmodule->exportList = oldExportList;
        }

      if (parseError) return(TRUE);
      return(FALSE);
     }

   /*===============================================*/
   /* Increment the symbol table counts for symbols */
   /* used in the defmodule data structures.        */
   /*===============================================*/

   if (redefiningMainModule == NULL)
     { IncrementSymbolCount(newDefmodule->name); }
   else
     {
      if ((newDefmodule->importList != NULL) ||
          (newDefmodule->exportList != NULL))
        { MainModuleRedefinable = FALSE; }
     }

   for (portSpecs = newDefmodule->importList; portSpecs != NULL; portSpecs = portSpecs->next)
     {
      if (portSpecs->moduleName != NULL) IncrementSymbolCount(portSpecs->moduleName);
      if (portSpecs->constructType != NULL) IncrementSymbolCount(portSpecs->constructType);
      if (portSpecs->constructName != NULL) IncrementSymbolCount(portSpecs->constructName);
     }

   for (portSpecs = newDefmodule->exportList; portSpecs != NULL; portSpecs = portSpecs->next)
     {
      if (portSpecs->moduleName != NULL) IncrementSymbolCount(portSpecs->moduleName);
      if (portSpecs->constructType != NULL) IncrementSymbolCount(portSpecs->constructType);
      if (portSpecs->constructName != NULL) IncrementSymbolCount(portSpecs->constructName);
     }

   /*====================================================*/
   /* Allocate storage for the module's construct lists. */
   /*====================================================*/

   if (redefiningMainModule != NULL) { /* Do nothing */ }
   else if (NumberOfModuleItems == 0) newDefmodule->itemsArray = NULL;
   else
     {
      newDefmodule->itemsArray = (struct defmoduleItemHeader **) gm2((int) sizeof(void *) * NumberOfModuleItems);
      for (i = 0, theItem = ListOfModuleItems;
           (i < NumberOfModuleItems) && (theItem != NULL);
           i++, theItem = theItem->next)
        {
         if (theItem->allocateFunction == NULL)
           { newDefmodule->itemsArray[i] = NULL; }
         else
           {
            newDefmodule->itemsArray[i] = (struct defmoduleItemHeader *)
                                          (*theItem->allocateFunction)();
            theHeader = (struct defmoduleItemHeader *) newDefmodule->itemsArray[i];
            theHeader->theModule = newDefmodule;
            theHeader->firstItem = NULL;
            theHeader->lastItem = NULL;
           }
        }
     }

   /*=======================================*/
   /* Save the pretty print representation. */
   /*=======================================*/

   SavePPBuffer("\n");

   if (GetConserveMemory() == TRUE)
     { newDefmodule->ppForm = NULL; }
   else
     { newDefmodule->ppForm = CopyPPBuffer(); }

   /*==============================================*/
   /* Add the defmodule to the list of defmodules. */
   /*==============================================*/

   if (redefiningMainModule == NULL)
     {
      if (LastDefmodule == NULL) ListOfDefmodules = newDefmodule;
      else LastDefmodule->next = newDefmodule;
      LastDefmodule = newDefmodule;
      newDefmodule->bsaveID = NumberOfDefmodules++;
     }

   SetCurrentModule((void *) newDefmodule);

   /*=========================================*/
   /* Call any functions required by other    */
   /* constructs when a new module is defined */
   /*=========================================*/

   for (defineFunctions = AfterModuleDefinedFunctions;
        defineFunctions != NULL;
        defineFunctions = defineFunctions->next)
     { (* (void (*)(void)) defineFunctions->func)(); }

   /*===============================================*/
   /* Defmodule successfully parsed with no errors. */
   /*===============================================*/

   return(FALSE);
  }