repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
DrItanium/durandal
|
include/obsolete/ExpertSystem/KnowledgeConstructionEngine.h
|
#ifndef _knowledge_construction_engine_h
#define _knowledge_construction_engine_h
#include "ExpertSystem/CLIPSObjectBuilder.h"
#include "ExpertSystem/CLIPSValueBuilder.h"
#include "ExpertSystem/CLIPSUserBuilder.h"
#include "ExpertSystem/CLIPSArgumentBuilder.h"
#include "ExpertSystem/CLIPSBasicBlockBuilder.h"
#include "ExpertSystem/CLIPSConstantBuilder.h"
#include "ExpertSystem/CLIPSInstructionBuilder.h"
#include "ExpertSystem/CLIPSLoopBuilder.h"
#include "ExpertSystem/CLIPSOperatorBuilder.h"
#include "ExpertSystem/CLIPSRegionBuilder.h"
#include "ExpertSystem/CLIPSTypeBuilder.h"
#include "ExpertSystem/CLIPSModuleBuilder.h"
#include "ExpertSystem/CLIPSFunctionBuilder.h"
#endif
|
DrItanium/durandal
|
include/electron/dffctdef.h
|
<gh_stars>1-10
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/22/14 */
/* */
/* DEFFACTS HEADER FILE */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* <NAME> */
/* */
/* Revision History: */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/*************************************************************/
#ifndef _H_dffctdef
#define _H_dffctdef
#ifndef _H_conscomp
#include "conscomp.h"
#endif
#ifndef _H_symbol
#include "symbol.h"
#endif
#ifndef _H_expressn
#include "expressn.h"
#endif
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifndef _H_constrct
#include "constrct.h"
#endif
#ifndef _H_moduldef
#include "moduldef.h"
#endif
#ifndef _H_cstrccom
#include "cstrccom.h"
#endif
#define DEFFACTS_DATA 0
struct deffactsData
{
struct construct *DeffactsConstruct;
int DeffactsModuleIndex;
#if CONSTRUCT_COMPILER && (! RUN_TIME)
struct CodeGeneratorItem *DeffactsCodeItem;
#endif
};
struct deffacts
{
struct constructHeader header;
struct expr *assertList;
};
struct deffactsModule
{
struct defmoduleItemHeader header;
};
#define DeffactsData(theEnv) ((struct deffactsData *) GetEnvironmentData(theEnv,DEFFACTS_DATA))
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _DFFCTDEF_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void InitializeDeffacts(void *);
LOCALE void *EnvFindDeffacts(void *,const char *);
LOCALE void *EnvGetNextDeffacts(void *,void *);
LOCALE void CreateInitialFactDeffacts(void);
LOCALE intBool EnvIsDeffactsDeletable(void *,void *);
LOCALE struct deffactsModule *GetDeffactsModuleItem(void *,struct defmodule *);
LOCALE const char *EnvDeffactsModule(void *,void *);
LOCALE const char *EnvGetDeffactsName(void *,void *);
LOCALE const char *EnvGetDeffactsPPForm(void *,void *);
#if ALLOW_ENVIRONMENT_GLOBALS
LOCALE void *FindDeffacts(const char *);
LOCALE void *GetNextDeffacts(void *);
LOCALE intBool IsDeffactsDeletable(void *);
LOCALE const char *DeffactsModule(void *);
LOCALE const char *GetDeffactsName(void *);
LOCALE const char *GetDeffactsPPForm(void *);
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_dffctdef */
|
DrItanium/durandal
|
include/indirect/IndirectUniqueIdentifier.h
|
#ifndef _indirect_unique_identifier_h
#define _indirect_unique_identifier_h
/* This is a class that defines a pointer used to provide a unique ID useful
* for pass registration. Thanks goes to silvas on #llvm for providing me with
* this technique instead of my over the top static SSD GC idea.
*
* This class stores a single char* ptr that is used as the unique identifer
* that the static char ID field provides in native LLVM passes.
*/
namespace indirect {
class IndirectUniqueIdentifier {
private:
char* id;
public:
IndirectUniqueIdentifier();
~IndirectUniqueIdentifier();
char* getID();
};
}
#endif
|
DrItanium/durandal
|
lib/maya/fsoverride.c
|
/*
maya
Copyright (c) 2012-2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include "clips.h"
#include "maya/libmaya.h"
#if FILE_SYSTEM_ROOTING
#if ! RUN_TIME
static void deallocateFileSystemRootData(void* theEnv);
static int GetFileSystemRootingIsEnabled(void* theEnv);
static int SetFileSystemRootingIsEnabled(void* theEnv);
static void GetFileSystemRoot(void* theEnv, DATA_OBJECT_PTR ret);
static void SetFileSystemRoot(void* theEnv, DATA_OBJECT_PTR ret);
#endif
void DefineFSOverrideFunctions(void* theEnv) {
#if ! RUN_TIME
char* base;
char* tmp;
int size;
if(!AllocateEnvironmentData(theEnv, FILE_SYSTEM_ROOT_DATA,
sizeof(FileSystemRootData), deallocateFileSystemRootData)) {
printf("Error allocating environment data for FILE_SYSTEM_ROOT_DATA\n");
exit(EXIT_FAILURE);
}
base = getenv((const char*)FILE_SYSTEM_BASE);
if (base == NULL) {
size = 1;
tmp = gm1(theEnv, 1);
tmp[0] = '\0';
FileSystemRootData(theEnv)->rootingenabled = FALSE;
} else {
//make a copy
size = sizeof(char) * (strlen(base) + 2);
tmp = gm1(theEnv, size);
gensprintf(tmp, "%s", base);
FileSystemRootData(theEnv)->rootingenabled = TRUE;
}
FileSystemRootData(theEnv)->root = tmp;
FileSystemRootData(theEnv)->stringlength = size;
FileSystemRootData(theEnv)->issymbol = FALSE;
//TODO: define custom environment data structure for base path and if
//file-system rooting should take place (
EnvDefineFunction2(theEnv,
"get-file-system-rooting-is-enabled",
'b',
PTIEF GetFileSystemRootingIsEnabled,
"GetFileSystemRootingIsEnabled",
"00a");
EnvDefineFunction2(theEnv,
"set-file-system-rooting-is-enabled",
'b',
PTIEF SetFileSystemRootingIsEnabled,
"SetFileSystemRootingIsEnabled",
"11w");
EnvDefineFunction2(theEnv,
"get-file-system-root",
'k',
PTIEF GetFileSystemRoot,
"GetFileSystemRoot",
"00a");
EnvDefineFunction2(theEnv,
"set-file-system-root",
'k',
PTIEF SetFileSystemRoot,
"SetFileSystemRoot",
"11k");
EnvDefineFunction2(theEnv,
"remove",
'b',
PTIEF FS_RemoveFunction,
"FS_RemoveFunction",
"11k");
EnvDefineFunction2(theEnv,
"rename",
'b',
PTIEF FS_RenameFunction,
"FS_RenameFunction",
"22k");
#endif
}
FILE* GenOpen(void* theEnv, const char* fileName, const char* accessType) {
char* base;
char* tmp;
int size;
FILE* result;
if(FileSystemRootData(theEnv)->rootingenabled) {
base = FileSystemRootData(theEnv)->root;
size = sizeof(char) * (strlen(fileName) + strlen(base) + 2);
tmp = gm1(theEnv, size);
gensprintf(tmp, "%s/%s", base, fileName);
result = _GenOpen(theEnv, tmp, accessType);
rm(theEnv,tmp, size);
} else {
result = _GenOpen(theEnv, fileName, accessType);
}
return result;
}
int GenOpenReadBinary(void* theEnv, const char* funcName, const char* fileName) {
char* base;
char* tmp;
int result, size;
if(FileSystemRootData(theEnv)->rootingenabled) {
base = FileSystemRootData(theEnv)->root;
size = sizeof(char) * (strlen(fileName) + strlen(base) + 2);
tmp = gm1(theEnv, size);
gensprintf(tmp, "%s/%s", base, fileName);
result = _GenOpenReadBinary(theEnv, funcName, tmp);
rm(theEnv,tmp, size);
} else {
result = _GenOpenReadBinary(theEnv, funcName, fileName);
}
return result;
}
int FS_RemoveFunction(void *theEnv) {
const char *theFileName;
char *base;
char* tmp;
int result, size;
if (EnvArgCountCheck(theEnv,"remove",EXACTLY,1) == -1)
return(FALSE);
if ((theFileName = GetFileName(theEnv,"remove",1)) == NULL)
return(FALSE);
if(FileSystemRootData(theEnv)->rootingenabled) {
base = FileSystemRootData(theEnv)->root;
size = sizeof(char) * (strlen(theFileName) + strlen(base) + 2);
tmp = gm1(theEnv, size);
gensprintf(tmp, "%s/%s", base, theFileName);
result = (genremove(tmp));
rm(theEnv,tmp, size);
} else {
result = (genremove(theFileName));
}
return result;
}
int FS_RenameFunction(void *theEnv) {
const char* oldFileName;
const char* newFileName;
char* old;
char* new;
char* base;
int sizeOld, sizeNew, result;
if(EnvArgCountCheck(theEnv,"rename",EXACTLY,2) == -1) {
return(FALSE);
}
if((oldFileName = GetFileName(theEnv,"rename",1)) == NULL) {
return(FALSE);
}
if((newFileName = GetFileName(theEnv,"rename",2)) == NULL) {
return(FALSE);
}
if(FileSystemRootData(theEnv)->rootingenabled) {
base = FileSystemRootData(theEnv)->root;
sizeOld = sizeof(char) * (strlen(base) + strlen(oldFileName) + 2);
sizeNew = sizeof(char) * (strlen(base) + strlen(newFileName) + 2);
old = gm1(theEnv, sizeOld);
new = gm1(theEnv, sizeNew);
gensprintf(old, "%s/%s", base, oldFileName);
gensprintf(new, "%s/%s", base, newFileName);
result = genrename(old,new);
rm(theEnv,old, sizeOld);
rm(theEnv,new, sizeNew);
} else {
result = genrename(oldFileName, newFileName);
}
return result;
}
void deallocateFileSystemRootData(void* theEnv) {
rm(theEnv,FileSystemRootData(theEnv)->root,
FileSystemRootData(theEnv)->stringlength);
FileSystemRootData(theEnv)->root = 0;
FileSystemRootData(theEnv)->stringlength = 0;
}
int GetFileSystemRootingIsEnabled(void* theEnv) {
if (FileSystemRootData(theEnv)->rootingenabled) {
return TRUE;
} else {
return FALSE;
}
}
int SetFileSystemRootingIsEnabled(void* theEnv) {
int oldValue;
DATA_OBJECT arg;
oldValue = FileSystemRootData(theEnv)->rootingenabled;
EnvRtnUnknown(theEnv, 1, &arg);
if((arg.value == EnvFalseSymbol(theEnv)) && (arg.type == SYMBOL)) {
FileSystemRootData(theEnv)->rootingenabled = FALSE;
} else {
FileSystemRootData(theEnv)->rootingenabled = TRUE;
}
return oldValue;
}
void GetFileSystemRoot(void* theEnv, DATA_OBJECT_PTR ret) {
if(EnvArgCountCheck(theEnv, "get-file-system-root", EXACTLY, 0) == -1) {
SetpType(ret, SYMBOL);
SetpValue(ret, EnvFalseSymbol(theEnv));
return;
}
if(FileSystemRootData(theEnv)->issymbol) {
SetpType(ret, SYMBOL);
} else {
SetpType(ret, STRING);
}
SetpValue(ret, EnvAddSymbol(theEnv, FileSystemRootData(theEnv)->root));
}
void SetFileSystemRoot(void* theEnv, DATA_OBJECT_PTR ret) {
DATA_OBJECT arg0;
void* oldValue;
char* newRoot;
char* value;
int size;
if(EnvArgCountCheck(theEnv, "set-file-system-root", EXACTLY, 1) == -1) {
SetpType(ret, SYMBOL);
SetpValue(ret, EnvFalseSymbol(theEnv));
return;
}
if(!EnvArgTypeCheck(theEnv, "set-file-system-root", 1, SYMBOL_OR_STRING, &arg0)) {
SetpType(ret, SYMBOL);
SetpValue(ret, EnvFalseSymbol(theEnv));
return;
}
oldValue = EnvAddSymbol(theEnv, FileSystemRootData(theEnv)->root);
if(FileSystemRootData(theEnv)->issymbol) {
SetpType(ret, SYMBOL);
} else {
SetpType(ret, STRING);
}
SetpValue(ret, oldValue);
rm(theEnv, FileSystemRootData(theEnv)->root,
FileSystemRootData(theEnv)->stringlength);
if(arg0.type == SYMBOL) {
FileSystemRootData(theEnv)->issymbol = TRUE;
} else {
FileSystemRootData(theEnv)->issymbol = FALSE;
}
newRoot = DOToString(arg0);
size = sizeof(char) * strlen(newRoot) + 1;
value = gm1(theEnv, size);
gensprintf(value, "%s", newRoot);
if (size > 1) {
FileSystemRootData(theEnv)->rootingenabled = TRUE;
} else {
FileSystemRootData(theEnv)->rootingenabled = FALSE;
}
FileSystemRootData(theEnv)->root = value;
FileSystemRootData(theEnv)->stringlength = size;
}
#endif /* FILE_SYSTEM_ROOTING */
|
DrItanium/durandal
|
lib/electron/tmpltdef.c
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/22/14 */
/* */
/* DEFTEMPLATE MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: Defines basic deftemplate primitive functions */
/* such as allocating and deallocating, traversing, and */
/* finding deftemplate data structures. */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* <NAME> */
/* */
/* Revision History: */
/* */
/* 6.23: Added support for templates maintaining their */
/* own list of facts. */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* Corrected code to remove run-time program */
/* compiler warnings. */
/* */
/* 6.30: Added code for deftemplate run time */
/* initialization of hashed comparisons to */
/* constants. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Support for deftemplate slot facets. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/*************************************************************/
#define _TMPLTDEF_SOURCE_
#include "setup.h"
#if DEFTEMPLATE_CONSTRUCT
#include <stdio.h>
#define _STDIO_INCLUDED_
#include "memalloc.h"
#include "exprnops.h"
#include "cstrccom.h"
#include "network.h"
#include "tmpltpsr.h"
#include "tmpltbsc.h"
#include "tmpltutl.h"
#include "tmpltfun.h"
#include "router.h"
#include "modulpsr.h"
#include "modulutl.h"
#include "cstrnchk.h"
#include "envrnmnt.h"
#if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE
#include "bload.h"
#include "tmpltbin.h"
#endif
#if CONSTRUCT_COMPILER && (! RUN_TIME)
#include "tmpltcmp.h"
#endif
#include "tmpltdef.h"
/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/
static void *AllocateModule(void *);
static void ReturnModule(void *,void *);
static void ReturnDeftemplate(void *,void *);
static void InitializeDeftemplateModules(void *);
static void DeallocateDeftemplateData(void *);
static void DestroyDeftemplateAction(void *,struct constructHeader *,void *);
static void DestroyDeftemplate(void *,void *);
#if RUN_TIME
static void RuntimeDeftemplateAction(void *,struct constructHeader *,void *);
static void SearchForHashedPatternNodes(void *,struct factPatternNode *);
#endif
/******************************************************************/
/* InitializeDeftemplates: Initializes the deftemplate construct. */
/******************************************************************/
globle void InitializeDeftemplates(
void *theEnv)
{
globle struct entityRecord deftemplatePtrRecord = { "DEFTEMPLATE_PTR",
DEFTEMPLATE_PTR,1,0,0,
NULL,
NULL,NULL,
NULL,
NULL,
DecrementDeftemplateBusyCount,
IncrementDeftemplateBusyCount,
NULL,NULL,NULL,NULL,NULL };
AllocateEnvironmentData(theEnv,DEFTEMPLATE_DATA,sizeof(struct deftemplateData),DeallocateDeftemplateData);
memcpy(&DeftemplateData(theEnv)->DeftemplatePtrRecord,&deftemplatePtrRecord,sizeof(struct entityRecord));
InitializeFacts(theEnv);
InitializeDeftemplateModules(theEnv);
DeftemplateBasicCommands(theEnv);
DeftemplateFunctions(theEnv);
DeftemplateData(theEnv)->DeftemplateConstruct =
AddConstruct(theEnv,"deftemplate","deftemplates",ParseDeftemplate,EnvFindDeftemplate,
GetConstructNamePointer,GetConstructPPForm,
GetConstructModuleItem,EnvGetNextDeftemplate,SetNextConstruct,
EnvIsDeftemplateDeletable,EnvUndeftemplate,ReturnDeftemplate);
InstallPrimitive(theEnv,(ENTITY_RECORD_PTR) &DeftemplateData(theEnv)->DeftemplatePtrRecord,DEFTEMPLATE_PTR);
}
/******************************************************/
/* DeallocateDeftemplateData: Deallocates environment */
/* data for the deftemplate construct. */
/******************************************************/
static void DeallocateDeftemplateData(
void *theEnv)
{
#if ! RUN_TIME
struct deftemplateModule *theModuleItem;
void *theModule;
#endif
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv)) return;
#endif
DoForAllConstructs(theEnv,DestroyDeftemplateAction,DeftemplateData(theEnv)->DeftemplateModuleIndex,FALSE,NULL);
#if ! RUN_TIME
for (theModule = EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = EnvGetNextDefmodule(theEnv,theModule))
{
theModuleItem = (struct deftemplateModule *)
GetModuleItem(theEnv,(struct defmodule *) theModule,
DeftemplateData(theEnv)->DeftemplateModuleIndex);
rtn_struct(theEnv,deftemplateModule,theModuleItem);
}
#endif
}
/*****************************************************/
/* DestroyDeftemplateAction: Action used to remove */
/* deftemplates as a result of DestroyEnvironment. */
/*****************************************************/
static void DestroyDeftemplateAction(
void *theEnv,
struct constructHeader *theConstruct,
void *buffer)
{
struct deftemplate *theDeftemplate = (struct deftemplate *) theConstruct;
if (theDeftemplate == NULL) return;
DestroyDeftemplate(theEnv,theDeftemplate);
}
/*************************************************************/
/* InitializeDeftemplateModules: Initializes the deftemplate */
/* construct for use with the defmodule construct. */
/*************************************************************/
static void InitializeDeftemplateModules(
void *theEnv)
{
DeftemplateData(theEnv)->DeftemplateModuleIndex = RegisterModuleItem(theEnv,"deftemplate",
AllocateModule,
ReturnModule,
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
BloadDeftemplateModuleReference,
#else
NULL,
#endif
#if CONSTRUCT_COMPILER && (! RUN_TIME)
DeftemplateCModuleReference,
#else
NULL,
#endif
EnvFindDeftemplate);
#if (! BLOAD_ONLY) && (! RUN_TIME) && DEFMODULE_CONSTRUCT
AddPortConstructItem(theEnv,"deftemplate",SYMBOL);
#endif
}
/***************************************************/
/* AllocateModule: Allocates a deftemplate module. */
/***************************************************/
static void *AllocateModule(
void *theEnv)
{
return((void *) get_struct(theEnv,deftemplateModule));
}
/*************************************************/
/* ReturnModule: Deallocates a deftemplate module. */
/*************************************************/
static void ReturnModule(
void *theEnv,
void *theItem)
{
FreeConstructHeaderModule(theEnv,(struct defmoduleItemHeader *) theItem,DeftemplateData(theEnv)->DeftemplateConstruct);
rtn_struct(theEnv,deftemplateModule,theItem);
}
/****************************************************************/
/* GetDeftemplateModuleItem: Returns a pointer to the defmodule */
/* item for the specified deftemplate or defmodule. */
/****************************************************************/
globle struct deftemplateModule *GetDeftemplateModuleItem(
void *theEnv,
struct defmodule *theModule)
{
return((struct deftemplateModule *) GetConstructModuleItemByIndex(theEnv,theModule,DeftemplateData(theEnv)->DeftemplateModuleIndex));
}
/*****************************************************/
/* EnvFindDeftemplate: Searches for a deftemplate in */
/* the list of deftemplates. Returns a pointer to */
/* the deftemplate if found, otherwise NULL. */
/*****************************************************/
globle void *EnvFindDeftemplate(
void *theEnv,
const char *deftemplateName)
{
return(FindNamedConstruct(theEnv,deftemplateName,DeftemplateData(theEnv)->DeftemplateConstruct));
}
/***********************************************************************/
/* EnvGetNextDeftemplate: If passed a NULL pointer, returns the first */
/* deftemplate in the ListOfDeftemplates. Otherwise returns the next */
/* deftemplate following the deftemplate passed as an argument. */
/***********************************************************************/
globle void *EnvGetNextDeftemplate(
void *theEnv,
void *deftemplatePtr)
{
return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) deftemplatePtr,DeftemplateData(theEnv)->DeftemplateModuleIndex));
}
/***********************************************************/
/* EnvIsDeftemplateDeletable: Returns TRUE if a particular */
/* deftemplate can be deleted, otherwise returns FALSE. */
/***********************************************************/
globle intBool EnvIsDeftemplateDeletable(
void *theEnv,
void *vTheDeftemplate)
{
struct deftemplate *theDeftemplate = (struct deftemplate *) vTheDeftemplate;
if (! ConstructsDeletable(theEnv))
{ return FALSE; }
if (theDeftemplate->busyCount > 0) return(FALSE);
if (theDeftemplate->patternNetwork != NULL) return(FALSE);
return(TRUE);
}
/**************************************************************/
/* ReturnDeftemplate: Returns the data structures associated */
/* with a deftemplate construct to the pool of free memory. */
/**************************************************************/
static void ReturnDeftemplate(
void *theEnv,
void *vTheConstruct)
{
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct deftemplate *theConstruct = (struct deftemplate *) vTheConstruct;
struct templateSlot *slotPtr;
if (theConstruct == NULL) return;
/*====================================================================*/
/* If a template is redefined, then we want to save its debug status. */
/*====================================================================*/
#if DEBUGGING_FUNCTIONS
DeftemplateData(theEnv)->DeletedTemplateDebugFlags = 0;
if (theConstruct->watch) BitwiseSet(DeftemplateData(theEnv)->DeletedTemplateDebugFlags,0);
#endif
/*===========================================*/
/* Free storage used by the templates slots. */
/*===========================================*/
slotPtr = theConstruct->slotList;
while (slotPtr != NULL)
{
DecrementSymbolCount(theEnv,slotPtr->slotName);
RemoveHashedExpression(theEnv,slotPtr->defaultList);
slotPtr->defaultList = NULL;
RemoveHashedExpression(theEnv,slotPtr->facetList);
slotPtr->facetList = NULL;
RemoveConstraint(theEnv,slotPtr->constraints);
slotPtr->constraints = NULL;
slotPtr = slotPtr->next;
}
ReturnSlots(theEnv,theConstruct->slotList);
/*==================================*/
/* Free storage used by the header. */
/*==================================*/
DeinstallConstructHeader(theEnv,&theConstruct->header);
rtn_struct(theEnv,deftemplate,theConstruct);
#endif
}
/**************************************************************/
/* DestroyDeftemplate: Returns the data structures associated */
/* with a deftemplate construct to the pool of free memory. */
/**************************************************************/
static void DestroyDeftemplate(
void *theEnv,
void *vTheConstruct)
{
struct deftemplate *theConstruct = (struct deftemplate *) vTheConstruct;
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct templateSlot *slotPtr, *nextSlot;
#endif
if (theConstruct == NULL) return;
#if (! BLOAD_ONLY) && (! RUN_TIME)
slotPtr = theConstruct->slotList;
while (slotPtr != NULL)
{
nextSlot = slotPtr->next;
rtn_struct(theEnv,templateSlot,slotPtr);
slotPtr = nextSlot;
}
#endif
DestroyFactPatternNetwork(theEnv,theConstruct->patternNetwork);
/*==================================*/
/* Free storage used by the header. */
/*==================================*/
#if (! BLOAD_ONLY) && (! RUN_TIME)
DeinstallConstructHeader(theEnv,&theConstruct->header);
rtn_struct(theEnv,deftemplate,theConstruct);
#endif
}
/***********************************************/
/* ReturnSlots: Returns the slot structures of */
/* a deftemplate to free memory. */
/***********************************************/
globle void ReturnSlots(
void *theEnv,
struct templateSlot *slotPtr)
{
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct templateSlot *nextSlot;
while (slotPtr != NULL)
{
nextSlot = slotPtr->next;
ReturnExpression(theEnv,slotPtr->defaultList);
ReturnExpression(theEnv,slotPtr->facetList);
RemoveConstraint(theEnv,slotPtr->constraints);
rtn_struct(theEnv,templateSlot,slotPtr);
slotPtr = nextSlot;
}
#endif
}
/*************************************************/
/* DecrementDeftemplateBusyCount: Decrements the */
/* busy count of a deftemplate data structure. */
/*************************************************/
globle void DecrementDeftemplateBusyCount(
void *theEnv,
void *vTheTemplate)
{
struct deftemplate *theTemplate = (struct deftemplate *) vTheTemplate;
if (! ConstructData(theEnv)->ClearInProgress) theTemplate->busyCount--;
}
/*************************************************/
/* IncrementDeftemplateBusyCount: Increments the */
/* busy count of a deftemplate data structure. */
/*************************************************/
globle void IncrementDeftemplateBusyCount(
void *theEnv,
void *vTheTemplate)
{
struct deftemplate *theTemplate = (struct deftemplate *) vTheTemplate;
theTemplate->busyCount++;
}
/*******************************************************************/
/* EnvGetNextFactInTemplate: If passed a NULL pointer, returns the */
/* first fact in the template's fact-list. Otherwise returns the */
/* next template fact following the fact passed as an argument. */
/*******************************************************************/
globle void *EnvGetNextFactInTemplate(
void *theEnv,
void *theTemplate,
void *factPtr)
{
if (factPtr == NULL)
{ return((void *) ((struct deftemplate *) theTemplate)->factList); }
if (((struct fact *) factPtr)->garbage) return(NULL);
return((void *) ((struct fact *) factPtr)->nextTemplateFact);
}
#if ! RUN_TIME
/******************************/
/* CreateDeftemplateScopeMap: */
/******************************/
globle void *CreateDeftemplateScopeMap(
void *theEnv,
struct deftemplate *theDeftemplate)
{
unsigned scopeMapSize;
char *scopeMap;
const char *templateName;
struct defmodule *matchModule, *theModule;
int moduleID,count;
void *theBitMap;
templateName = ValueToString(theDeftemplate->header.name);
matchModule = theDeftemplate->header.whichModule->theModule;
scopeMapSize = (sizeof(char) * ((GetNumberOfDefmodules(theEnv) / BITS_PER_BYTE) + 1));
scopeMap = (char *) gm2(theEnv,scopeMapSize);
ClearBitString((void *) scopeMap,scopeMapSize);
SaveCurrentModule(theEnv);
for (theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL) ;
theModule != NULL ;
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule))
{
EnvSetCurrentModule(theEnv,(void *) theModule);
moduleID = (int) theModule->bsaveID;
if (FindImportedConstruct(theEnv,"deftemplate",matchModule,
templateName,&count,TRUE,NULL) != NULL)
SetBitMap(scopeMap,moduleID);
}
RestoreCurrentModule(theEnv);
theBitMap = EnvAddBitMap(theEnv,scopeMap,scopeMapSize);
IncrementBitMapCount(theBitMap);
rm(theEnv,(void *) scopeMap,scopeMapSize);
return(theBitMap);
}
#endif
#if RUN_TIME
/**************************************************/
/* RuntimeDeftemplateAction: Action to be applied */
/* to each deftemplate construct when a runtime */
/* initialization occurs. */
/**************************************************/
static void RuntimeDeftemplateAction(
void *theEnv,
struct constructHeader *theConstruct,
void *buffer)
{
struct deftemplate *theDeftemplate = (struct deftemplate *) theConstruct;
SearchForHashedPatternNodes(theEnv,theDeftemplate->patternNetwork);
}
/*******************************************************************/
/* SearchForHashedPatternNodes: */
/*******************************************************************/
static void SearchForHashedPatternNodes(
void *theEnv,
struct factPatternNode *theNode)
{
while (theNode != NULL)
{
if ((theNode->lastLevel != NULL) && (theNode->lastLevel->header.selector))
{ AddHashedPatternNode(theEnv,theNode->lastLevel,theNode,theNode->networkTest->type,theNode->networkTest->value); }
SearchForHashedPatternNodes(theEnv,theNode->nextLevel);
theNode = theNode->rightNode;
}
}
/*******************************************************************/
/* DeftemplateRunTimeInitialize: */
/*******************************************************************/
globle void DeftemplateRunTimeInitialize(
void *theEnv)
{
DoForAllConstructs(theEnv,RuntimeDeftemplateAction,DeftemplateData(theEnv)->DeftemplateModuleIndex,TRUE,NULL);
}
#endif /* RUN_TIME */
/*##################################*/
/* Additional Environment Functions */
/*##################################*/
globle const char *EnvDeftemplateModule(
void *theEnv,
void *theDeftemplate)
{
return GetConstructModuleName((struct constructHeader *) theDeftemplate);
}
globle const char *EnvGetDeftemplateName(
void *theEnv,
void *theDeftemplate)
{
return GetConstructNameString((struct constructHeader *) theDeftemplate);
}
globle const char *EnvGetDeftemplatePPForm(
void *theEnv,
void *theDeftemplate)
{
return GetConstructPPForm(theEnv,(struct constructHeader *) theDeftemplate);
}
/*#####################################*/
/* ALLOW_ENVIRONMENT_GLOBALS Functions */
/*#####################################*/
#if ALLOW_ENVIRONMENT_GLOBALS
globle const char *DeftemplateModule(
void *theDeftemplate)
{
return EnvDeftemplateModule(GetCurrentEnvironment(),theDeftemplate);
}
globle void *FindDeftemplate(
const char *deftemplateName)
{
return EnvFindDeftemplate(GetCurrentEnvironment(),deftemplateName);
}
globle const char *GetDeftemplateName(
void *theDeftemplate)
{
return EnvGetDeftemplateName(GetCurrentEnvironment(),theDeftemplate);
}
globle const char *GetDeftemplatePPForm(
void *theDeftemplate)
{
return EnvGetDeftemplatePPForm(GetCurrentEnvironment(),theDeftemplate);
}
globle void *GetNextDeftemplate(
void *deftemplatePtr)
{
return EnvGetNextDeftemplate(GetCurrentEnvironment(),deftemplatePtr);
}
globle intBool IsDeftemplateDeletable(
void *vTheDeftemplate)
{
return EnvIsDeftemplateDeletable(GetCurrentEnvironment(),vTheDeftemplate);
}
globle void *GetNextFactInTemplate(
void *theTemplate,
void *factPtr)
{
return EnvGetNextFactInTemplate(GetCurrentEnvironment(),theTemplate,factPtr);
}
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* DEFTEMPLATE_CONSTRUCT */
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/Types.h
|
<reponame>DrItanium/durandal
#ifndef _expert_system_types_h
#define _expert_system_types_h
typedef long long PointerAddress;
typedef long long ExecutionDuration;
#define CharBuffer(size) (char*)calloc(size, sizeof(char))
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/LLVMFunctions.h
|
#ifndef _llvm_functions_h
#define _llvm_functions_h
/*
* Contains all of the CLIPS=>LLVM and LLVM=>CLIPS wrapper functions.
* These functions show up in CLIPS as various different things
*/
#include "ExpertSystem/Types.h"
extern "C" void RegisterExpertSystemFunctions(void *theEnv);
extern "C" void LLVMPrint(void *theEnv);
extern "C" void BatchLoad(void *theEnv);
extern "C" void* IsIdenticalTo(void *theEnv);
extern "C" void* IsIdenticalToWhenDefined(void *theEnv);
extern "C" void* IsSameOperationAs(void *theEnv);
extern "C" PointerAddress CloneInstruction(void *theEnv);
extern "C" void* UnlinkAndMoveInstructionBefore(void *theEnv);
extern "C" void* UnlinkAndMoveInstructionAfter(void *theEnv);
extern "C" void* MoveInstructionBefore(void *theEnv);
extern "C" void* MoveInstructionAfter(void *theEnv);
extern "C" void* UnlinkAndDeleteInstruction(void *theEnv);
extern "C" void* ScheduleInstructions(void *theEnv);
extern "C" void* ReplaceUsesOf(void *theEnv);
extern "C" void* ReplaceAllUsesOf(void *theEnv);
extern "C" PointerAddress CreatePhiNode(void *theEnv);
extern "C" void* UnlinkInstruction(void *theEnv);
extern "C" void* DeleteInstruction(void *theEnv);
#endif
|
DrItanium/durandal
|
include/electron/factcom.h
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/20/14 */
/* */
/* FACT COMMANDS HEADER FILE */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* Revision History: */
/* */
/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */
/* */
/* 6.24: Added environment parameter to GenClose. */
/* Added environment parameter to GenOpen. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Support for long long integers. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW and */
/* MAC_MCW). */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Added code to prevent a clear command from */
/* being executed during fact assertions via */
/* Increment/DecrementClearReadyLocks API. */
/* */
/*************************************************************/
#ifndef _H_factcom
#define _H_factcom
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _FACTCOM_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void FactCommandDefinitions(void *);
LOCALE void AssertCommand(void *,DATA_OBJECT_PTR);
LOCALE void RetractCommand(void *);
LOCALE void AssertStringFunction(void *,DATA_OBJECT_PTR);
LOCALE void FactsCommand(void *);
LOCALE void EnvFacts(void *,const char *,void *,long long,long long,long long);
LOCALE int SetFactDuplicationCommand(void *);
LOCALE int GetFactDuplicationCommand(void *);
LOCALE int SaveFactsCommand(void *);
LOCALE int LoadFactsCommand(void *);
LOCALE int EnvSaveFacts(void *,const char *,int,struct expr *);
LOCALE int EnvLoadFacts(void *,const char *);
LOCALE int EnvLoadFactsFromString(void *,const char *,long);
LOCALE long long FactIndexFunction(void *);
#if ALLOW_ENVIRONMENT_GLOBALS
#if DEBUGGING_FUNCTIONS
LOCALE void Facts(const char *,void *,long long,long long,long long);
#endif
LOCALE intBool LoadFacts(const char *);
LOCALE intBool SaveFacts(const char *,int,struct expr *);
LOCALE intBool LoadFactsFromString(const char *,int);
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_factcom */
|
DrItanium/durandal
|
lib/electron/genrcfun.c
|
<reponame>DrItanium/durandal
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* */
/*******************************************************/
/*************************************************************/
/* Purpose: Generic Functions Internal Routines */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.23: Changed name of variable log to logName */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* 6.24: Removed IMPERATIVE_METHODS compilation flag. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Changed integer type/precision. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Fixed linkage issue when DEBUGGING_FUNCTIONS */
/* is set to 0 and PROFILING_FUNCTIONS is set to */
/* 1. */
/* */
/* Fixed typing issue when OBJECT_SYSTEM */
/* compiler flag is set to 0. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if DEFGENERIC_CONSTRUCT
#if BLOAD || BLOAD_AND_BSAVE
#include "bload.h"
#endif
#if OBJECT_SYSTEM
#include "classcom.h"
#include "classfun.h"
#endif
#include "argacces.h"
#include "constrct.h"
#include "cstrcpsr.h"
#include "envrnmnt.h"
#include "genrccom.h"
#include "genrcexe.h"
#include "memalloc.h"
#include "prccode.h"
#include "router.h"
#include "sysdep.h"
#define _GENRCFUN_SOURCE_
#include "genrcfun.h"
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
#if DEBUGGING_FUNCTIONS
static void DisplayGenericCore(void *,DEFGENERIC *);
#endif
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if ! RUN_TIME
/***************************************************
NAME : ClearDefgenericsReady
DESCRIPTION : Determines if it is safe to
remove all defgenerics
Assumes *all* constructs will be
deleted - only checks to see if
any methods are currently
executing
INPUTS : None
RETURNS : TRUE if no methods are
executing, FALSE otherwise
SIDE EFFECTS : None
NOTES : Used by (clear) and (bload)
***************************************************/
globle intBool ClearDefgenericsReady(
void *theEnv)
{
return((DefgenericData(theEnv)->CurrentGeneric != NULL) ? FALSE : TRUE);
}
/*****************************************************
NAME : AllocateDefgenericModule
DESCRIPTION : Creates and initializes a
list of defgenerics for a new module
INPUTS : None
RETURNS : The new deffunction module
SIDE EFFECTS : Deffunction module created
NOTES : None
*****************************************************/
globle void *AllocateDefgenericModule(
void *theEnv)
{
return((void *) get_struct(theEnv,defgenericModule));
}
/***************************************************
NAME : FreeDefgenericModule
DESCRIPTION : Removes a deffunction module and
all associated deffunctions
INPUTS : The deffunction module
RETURNS : Nothing useful
SIDE EFFECTS : Module and deffunctions deleted
NOTES : None
***************************************************/
globle void FreeDefgenericModule(
void *theEnv,
void *theItem)
{
#if (! BLOAD_ONLY)
FreeConstructHeaderModule(theEnv,(struct defmoduleItemHeader *) theItem,DefgenericData(theEnv)->DefgenericConstruct);
#endif
rtn_struct(theEnv,defgenericModule,theItem);
}
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/************************************************************
NAME : ClearDefmethods
DESCRIPTION : Deletes all defmethods - generic headers
are left intact
INPUTS : None
RETURNS : TRUE if all methods deleted, FALSE otherwise
SIDE EFFECTS : Defmethods deleted
NOTES : Clearing generic functions is done in
two stages
1) Delete all methods (to clear any
references to other constructs)
2) Delete all generic headers
This allows other constructs which
mutually refer to generic functions
to be cleared
************************************************************/
globle int ClearDefmethods(
void *theEnv)
{
register DEFGENERIC *gfunc;
int success = TRUE;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv) == TRUE) return(FALSE);
#endif
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,NULL);
while (gfunc != NULL)
{
if (RemoveAllExplicitMethods(theEnv,gfunc) == FALSE)
success = FALSE;
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc);
}
return(success);
}
/*****************************************************************
NAME : RemoveAllExplicitMethods
DESCRIPTION : Deletes all explicit defmethods - generic headers
are left intact (as well as a method for an
overloaded system function)
INPUTS : None
RETURNS : TRUE if all methods deleted, FALSE otherwise
SIDE EFFECTS : Explicit defmethods deleted
NOTES : None
*****************************************************************/
globle int RemoveAllExplicitMethods(
void *theEnv,
DEFGENERIC *gfunc)
{
long i,j;
unsigned systemMethodCount = 0;
DEFMETHOD *narr;
if (MethodsExecuting(gfunc) == FALSE)
{
for (i = 0 ; i < gfunc->mcnt ; i++)
{
if (gfunc->methods[i].system)
systemMethodCount++;
else
DeleteMethodInfo(theEnv,gfunc,&gfunc->methods[i]);
}
if (systemMethodCount != 0)
{
narr = (DEFMETHOD *) gm2(theEnv,(systemMethodCount * sizeof(DEFMETHOD)));
i = 0;
j = 0;
while (i < gfunc->mcnt)
{
if (gfunc->methods[i].system)
GenCopyMemory(DEFMETHOD,1,&narr[j++],&gfunc->methods[i]);
i++;
}
rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * gfunc->mcnt));
gfunc->mcnt = (short) systemMethodCount;
gfunc->methods = narr;
}
else
{
if (gfunc->mcnt != 0)
rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * gfunc->mcnt));
gfunc->mcnt = 0;
gfunc->methods = NULL;
}
return(TRUE);
}
return(FALSE);
}
/**************************************************
NAME : RemoveDefgeneric
DESCRIPTION : Removes a generic function node
from the generic list along with
all its methods
INPUTS : The generic function
RETURNS : Nothing useful
SIDE EFFECTS : List adjusted
Nodes deallocated
NOTES : Assumes generic is not in use!!!
**************************************************/
globle void RemoveDefgeneric(
void *theEnv,
void *vgfunc)
{
DEFGENERIC *gfunc = (DEFGENERIC *) vgfunc;
long i;
for (i = 0 ; i < gfunc->mcnt ; i++)
DeleteMethodInfo(theEnv,gfunc,&gfunc->methods[i]);
if (gfunc->mcnt != 0)
rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * gfunc->mcnt));
DecrementSymbolCount(theEnv,GetDefgenericNamePointer((void *) gfunc));
EnvSetDefgenericPPForm(theEnv,(void *) gfunc,NULL);
ClearUserDataList(theEnv,gfunc->header.usrData);
rtn_struct(theEnv,defgeneric,gfunc);
}
/****************************************************************
NAME : ClearDefgenerics
DESCRIPTION : Deletes all generic headers
INPUTS : None
RETURNS : TRUE if all methods deleted, FALSE otherwise
SIDE EFFECTS : Generic headers deleted (and any implicit system
function methods)
NOTES : None
****************************************************************/
globle int ClearDefgenerics(
void *theEnv)
{
register DEFGENERIC *gfunc,*gtmp;
int success = TRUE;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv) == TRUE) return(FALSE);
#endif
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,NULL);
while (gfunc != NULL)
{
gtmp = gfunc;
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc);
if (RemoveAllExplicitMethods(theEnv,gtmp) == FALSE)
{
CantDeleteItemErrorMessage(theEnv,"generic function",EnvGetDefgenericName(theEnv,gtmp));
success = FALSE;
}
else
{
RemoveConstructFromModule(theEnv,(struct constructHeader *) gtmp);
RemoveDefgeneric(theEnv,(void *) gtmp);
}
}
return(success);
}
/********************************************************
NAME : MethodAlterError
DESCRIPTION : Prints out an error message reflecting
that a generic function's methods
cannot be altered while any of them
are executing
INPUTS : The generic function
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
********************************************************/
globle void MethodAlterError(
void *theEnv,
DEFGENERIC *gfunc)
{
PrintErrorID(theEnv,"GENRCFUN",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"Defgeneric ");
EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WERROR," cannot be modified while one of its methods is executing.\n");
}
/***************************************************
NAME : DeleteMethodInfo
DESCRIPTION : Deallocates all the data associated
w/ a method but does not release
the method structure itself
INPUTS : 1) The generic function address
2) The method address
RETURNS : Nothing useful
SIDE EFFECTS : Nodes deallocated
NOTES : None
***************************************************/
globle void DeleteMethodInfo(
void *theEnv,
DEFGENERIC *gfunc,
DEFMETHOD *meth)
{
short j,k;
RESTRICTION *rptr;
SaveBusyCount(gfunc);
ExpressionDeinstall(theEnv,meth->actions);
ReturnPackedExpression(theEnv,meth->actions);
ClearUserDataList(theEnv,meth->usrData);
if (meth->ppForm != NULL)
rm(theEnv,(void *) meth->ppForm,(sizeof(char) * (strlen(meth->ppForm)+1)));
for (j = 0 ; j < meth->restrictionCount ; j++)
{
rptr = &meth->restrictions[j];
for (k = 0 ; k < rptr->tcnt ; k++)
#if OBJECT_SYSTEM
DecrementDefclassBusyCount(theEnv,rptr->types[k]);
#else
DecrementIntegerCount(theEnv,(INTEGER_HN *) rptr->types[k]);
#endif
if (rptr->types != NULL)
rm(theEnv,(void *) rptr->types,(sizeof(void *) * rptr->tcnt));
ExpressionDeinstall(theEnv,rptr->query);
ReturnPackedExpression(theEnv,rptr->query);
}
if (meth->restrictions != NULL)
rm(theEnv,(void *) meth->restrictions,
(sizeof(RESTRICTION) * meth->restrictionCount));
RestoreBusyCount(gfunc);
}
/***************************************************
NAME : DestroyMethodInfo
DESCRIPTION : Deallocates all the data associated
w/ a method but does not release
the method structure itself
INPUTS : 1) The generic function address
2) The method address
RETURNS : Nothing useful
SIDE EFFECTS : Nodes deallocated
NOTES : None
***************************************************/
globle void DestroyMethodInfo(
void *theEnv,
DEFGENERIC *gfunc,
DEFMETHOD *meth)
{
register int j;
register RESTRICTION *rptr;
ReturnPackedExpression(theEnv,meth->actions);
ClearUserDataList(theEnv,meth->usrData);
if (meth->ppForm != NULL)
rm(theEnv,(void *) meth->ppForm,(sizeof(char) * (strlen(meth->ppForm)+1)));
for (j = 0 ; j < meth->restrictionCount ; j++)
{
rptr = &meth->restrictions[j];
if (rptr->types != NULL)
rm(theEnv,(void *) rptr->types,(sizeof(void *) * rptr->tcnt));
ReturnPackedExpression(theEnv,rptr->query);
}
if (meth->restrictions != NULL)
rm(theEnv,(void *) meth->restrictions,
(sizeof(RESTRICTION) * meth->restrictionCount));
}
/***************************************************
NAME : MethodsExecuting
DESCRIPTION : Determines if any of the methods of
a generic function are currently
executing
INPUTS : The generic function address
RETURNS : TRUE if any methods are executing,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle int MethodsExecuting(
DEFGENERIC *gfunc)
{
long i;
for (i = 0 ; i < gfunc->mcnt ; i++)
if (gfunc->methods[i].busy > 0)
return(TRUE);
return(FALSE);
}
#endif
#if ! OBJECT_SYSTEM
/**************************************************************
NAME : SubsumeType
DESCRIPTION : Determines if the second type subsumes
the first type
(e.g. INTEGER is subsumed by NUMBER_TYPE_CODE)
INPUTS : Two type codes
RETURNS : TRUE if type 2 subsumes type 1, FALSE
otherwise
SIDE EFFECTS : None
NOTES : Used only when COOL is not present
**************************************************************/
globle intBool SubsumeType(
int t1,
int t2)
{
if ((t2 == OBJECT_TYPE_CODE) || (t2 == PRIMITIVE_TYPE_CODE))
return(TRUE);
if ((t2 == NUMBER_TYPE_CODE) && ((t1 == INTEGER) || (t1 == FLOAT)))
return(TRUE);
if ((t2 == LEXEME_TYPE_CODE) && ((t1 == STRING) || (t1 == SYMBOL)))
return(TRUE);
if ((t2 == ADDRESS_TYPE_CODE) && ((t1 == EXTERNAL_ADDRESS) ||
(t1 == FACT_ADDRESS) || (t1 == INSTANCE_ADDRESS)))
return(TRUE);
if ((t2 == LEXEME_TYPE_CODE) &&
((t1 == INSTANCE_NAME) || (t1 == INSTANCE_ADDRESS)))
return(TRUE);
return(FALSE);
}
#endif
/*****************************************************
NAME : FindMethodByIndex
DESCRIPTION : Finds a generic function method of
specified index
INPUTS : 1) The generic function
2) The index
RETURNS : The position of the method in the
generic function's method array,
-1 if not found
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle long FindMethodByIndex(
DEFGENERIC *gfunc,
long theIndex)
{
long i;
for (i = 0 ; i < gfunc->mcnt ; i++)
if (gfunc->methods[i].index == theIndex)
return(i);
return(-1);
}
#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS
/******************************************************************
NAME : PrintMethod
DESCRIPTION : Lists a brief description of methods for a method
INPUTS : 1) Buffer for method info
2) Size of buffer (not including space for '\0')
3) The method address
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : A terminating newline is NOT included
******************************************************************/
globle void PrintMethod(
void *theEnv,
char *buf,
size_t buflen,
DEFMETHOD *meth)
{
long j,k;
register RESTRICTION *rptr;
char numbuf[15];
buf[0] = '\0';
if (meth->system)
genstrncpy(buf,"SYS",(STD_SIZE) buflen);
gensprintf(numbuf,"%-2d ",meth->index);
genstrncat(buf,numbuf,(STD_SIZE) buflen-3);
for (j = 0 ; j < meth->restrictionCount ; j++)
{
rptr = &meth->restrictions[j];
if ((((int) j) == meth->restrictionCount-1) && (meth->maxRestrictions == -1))
{
if ((rptr->tcnt == 0) && (rptr->query == NULL))
{
genstrncat(buf,"$?",buflen-strlen(buf));
break;
}
genstrncat(buf,"($? ",buflen-strlen(buf));
}
else
genstrncat(buf,"(",buflen-strlen(buf));
for (k = 0 ; k < rptr->tcnt ; k++)
{
#if OBJECT_SYSTEM
genstrncat(buf,EnvGetDefclassName(theEnv,rptr->types[k]),buflen-strlen(buf));
#else
genstrncat(buf,TypeName(theEnv,ValueToInteger(rptr->types[k])),buflen-strlen(buf));
#endif
if (((int) k) < (((int) rptr->tcnt) - 1))
genstrncat(buf," ",buflen-strlen(buf));
}
if (rptr->query != NULL)
{
if (rptr->tcnt != 0)
genstrncat(buf," ",buflen-strlen(buf));
genstrncat(buf,"<qry>",buflen-strlen(buf));
}
genstrncat(buf,")",buflen-strlen(buf));
if (((int) j) != (((int) meth->restrictionCount)-1))
genstrncat(buf," ",buflen-strlen(buf));
}
}
#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */
#if DEBUGGING_FUNCTIONS
/*************************************************************
NAME : PreviewGeneric
DESCRIPTION : Allows the user to see a printout of all the
applicable methods for a particular generic
function call
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Any side-effects of evaluating the generic
function arguments
and evaluating query-functions to determine
the set of applicable methods
NOTES : H/L Syntax: (preview-generic <func> <args>)
*************************************************************/
globle void PreviewGeneric(
void *theEnv)
{
DEFGENERIC *gfunc;
DEFGENERIC *previousGeneric;
int oldce;
DATA_OBJECT temp;
EvaluationData(theEnv)->EvaluationError = FALSE;
if (EnvArgTypeCheck(theEnv,"preview-generic",1,SYMBOL,&temp) == FALSE)
return;
gfunc = LookupDefgenericByMdlOrScope(theEnv,DOToString(temp));
if (gfunc == NULL)
{
PrintErrorID(theEnv,"GENRCFUN",3,FALSE);
EnvPrintRouter(theEnv,WERROR,"Unable to find generic function ");
EnvPrintRouter(theEnv,WERROR,DOToString(temp));
EnvPrintRouter(theEnv,WERROR," in function preview-generic.\n");
return;
}
oldce = ExecutingConstruct(theEnv);
SetExecutingConstruct(theEnv,TRUE);
previousGeneric = DefgenericData(theEnv)->CurrentGeneric;
DefgenericData(theEnv)->CurrentGeneric = gfunc;
EvaluationData(theEnv)->CurrentEvaluationDepth++;
PushProcParameters(theEnv,GetFirstArgument()->nextArg,
CountArguments(GetFirstArgument()->nextArg),
EnvGetDefgenericName(theEnv,(void *) gfunc),"generic function",
UnboundMethodErr);
if (EvaluationData(theEnv)->EvaluationError)
{
PopProcParameters(theEnv);
DefgenericData(theEnv)->CurrentGeneric = previousGeneric;
EvaluationData(theEnv)->CurrentEvaluationDepth--;
SetExecutingConstruct(theEnv,oldce);
return;
}
gfunc->busy++;
DisplayGenericCore(theEnv,gfunc);
gfunc->busy--;
PopProcParameters(theEnv);
DefgenericData(theEnv)->CurrentGeneric = previousGeneric;
EvaluationData(theEnv)->CurrentEvaluationDepth--;
SetExecutingConstruct(theEnv,oldce);
}
#endif /* DEBUGGING_FUNCTIONS */
/***************************************************
NAME : CheckGenericExists
DESCRIPTION : Finds the address of named
generic function and prints out
error message if not found
INPUTS : 1) Calling function
2) Name of generic function
RETURNS : Generic function address (NULL if
not found)
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle DEFGENERIC *CheckGenericExists(
void *theEnv,
const char *fname,
const char *gname)
{
DEFGENERIC *gfunc;
gfunc = LookupDefgenericByMdlOrScope(theEnv,gname);
if (gfunc == NULL)
{
PrintErrorID(theEnv,"GENRCFUN",3,FALSE);
EnvPrintRouter(theEnv,WERROR,"Unable to find generic function ");
EnvPrintRouter(theEnv,WERROR,gname);
EnvPrintRouter(theEnv,WERROR," in function ");
EnvPrintRouter(theEnv,WERROR,fname);
EnvPrintRouter(theEnv,WERROR,".\n");
SetEvaluationError(theEnv,TRUE);
}
return(gfunc);
}
/***************************************************
NAME : CheckMethodExists
DESCRIPTION : Finds the array index of the
specified method and prints out
error message if not found
INPUTS : 1) Calling function
2) Generic function address
3) Index of method
RETURNS : Method array index (-1 if not found)
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle long CheckMethodExists(
void *theEnv,
const char *fname,
DEFGENERIC *gfunc,
long mi)
{
long fi;
fi = FindMethodByIndex(gfunc,mi);
if (fi == -1)
{
PrintErrorID(theEnv,"GENRCFUN",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"Unable to find method ");
EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WERROR," #");
PrintLongInteger(theEnv,WERROR,mi);
EnvPrintRouter(theEnv,WERROR," in function ");
EnvPrintRouter(theEnv,WERROR,fname);
EnvPrintRouter(theEnv,WERROR,".\n");
SetEvaluationError(theEnv,TRUE);
}
return(fi);
}
#if ! OBJECT_SYSTEM
/*******************************************************
NAME : TypeName
DESCRIPTION : Given an integer type code, this
function returns the string name of
the type
INPUTS : The type code
RETURNS : The name-string of the type, or
"<???UNKNOWN-TYPE???>" for unrecognized
types
SIDE EFFECTS : EvaluationError set and error message
printed for unrecognized types
NOTES : Used only when COOL is not present
*******************************************************/
globle const char *TypeName(
void *theEnv,
int tcode)
{
switch (tcode)
{
case INTEGER : return(INTEGER_TYPE_NAME);
case FLOAT : return(FLOAT_TYPE_NAME);
case SYMBOL : return(SYMBOL_TYPE_NAME);
case STRING : return(STRING_TYPE_NAME);
case MULTIFIELD : return(MULTIFIELD_TYPE_NAME);
case EXTERNAL_ADDRESS : return(EXTERNAL_ADDRESS_TYPE_NAME);
case FACT_ADDRESS : return(FACT_ADDRESS_TYPE_NAME);
case INSTANCE_ADDRESS : return(INSTANCE_ADDRESS_TYPE_NAME);
case INSTANCE_NAME : return(INSTANCE_NAME_TYPE_NAME);
case OBJECT_TYPE_CODE : return(OBJECT_TYPE_NAME);
case PRIMITIVE_TYPE_CODE : return(PRIMITIVE_TYPE_NAME);
case NUMBER_TYPE_CODE : return(NUMBER_TYPE_NAME);
case LEXEME_TYPE_CODE : return(LEXEME_TYPE_NAME);
case ADDRESS_TYPE_CODE : return(ADDRESS_TYPE_NAME);
case INSTANCE_TYPE_CODE : return(INSTANCE_TYPE_NAME);
default : PrintErrorID(theEnv,"INSCOM",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"Undefined type in function type.\n");
SetEvaluationError(theEnv,TRUE);
return("<UNKNOWN-TYPE>");
}
}
#endif
/******************************************************
NAME : PrintGenericName
DESCRIPTION : Prints the name of a gneric function
(including the module name if the
generic is not in the current module)
INPUTS : 1) The logical name of the output
2) The generic functions
RETURNS : Nothing useful
SIDE EFFECTS : Generic name printed
NOTES : None
******************************************************/
globle void PrintGenericName(
void *theEnv,
const char *logName,
DEFGENERIC *gfunc)
{
if (gfunc->header.whichModule->theModule != ((struct defmodule *) EnvGetCurrentModule(theEnv)))
{
EnvPrintRouter(theEnv,logName,EnvGetDefmoduleName(theEnv,(void *)
gfunc->header.whichModule->theModule));
EnvPrintRouter(theEnv,logName,"::");
}
EnvPrintRouter(theEnv,logName,ValueToString((void *) gfunc->header.name));
}
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if DEBUGGING_FUNCTIONS
/*********************************************************
NAME : DisplayGenericCore
DESCRIPTION : Prints out a description of a core
frame of applicable methods for
a particular call of a generic function
INPUTS : The generic function
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
*********************************************************/
static void DisplayGenericCore(
void *theEnv,
DEFGENERIC *gfunc)
{
long i;
char buf[256];
int rtn = FALSE;
for (i = 0 ; i < gfunc->mcnt ; i++)
{
gfunc->methods[i].busy++;
if (IsMethodApplicable(theEnv,&gfunc->methods[i]))
{
rtn = TRUE;
EnvPrintRouter(theEnv,WDISPLAY,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WDISPLAY," #");
PrintMethod(theEnv,buf,255,&gfunc->methods[i]);
EnvPrintRouter(theEnv,WDISPLAY,buf);
EnvPrintRouter(theEnv,WDISPLAY,"\n");
}
gfunc->methods[i].busy--;
}
if (rtn == FALSE)
{
EnvPrintRouter(theEnv,WDISPLAY,"No applicable methods for ");
EnvPrintRouter(theEnv,WDISPLAY,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WDISPLAY,".\n");
}
}
#endif
#endif
|
DrItanium/durandal
|
include/electron/insfile.h
|
<gh_stars>1-10
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.24: Added environment parameter to GenClose. */
/* Added environment parameter to GenOpen. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* Corrected code to remove compiler warnings. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Changed integer type/precision. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/*************************************************************/
#ifndef _H_insfile
#define _H_insfile
#ifndef _H_expressn
#include "expressn.h"
#endif
#define INSTANCE_FILE_DATA 30
#if BLOAD_INSTANCES || BSAVE_INSTANCES
struct instanceFileData
{
const char *InstanceBinaryPrefixID;
const char *InstanceBinaryVersionID;
unsigned long BinaryInstanceFileSize;
#if BLOAD_INSTANCES
unsigned long BinaryInstanceFileOffset;
char *CurrentReadBuffer;
unsigned long CurrentReadBufferSize;
unsigned long CurrentReadBufferOffset;
#endif
};
#define InstanceFileData(theEnv) ((struct instanceFileData *) GetEnvironmentData(theEnv,INSTANCE_FILE_DATA))
#endif /* BLOAD_INSTANCES || BSAVE_INSTANCES */
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _INSFILE_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void SetupInstanceFileCommands(void *);
LOCALE long SaveInstancesCommand(void *);
LOCALE long LoadInstancesCommand(void *);
LOCALE long RestoreInstancesCommand(void *);
LOCALE long EnvSaveInstances(void *,const char *,int,EXPRESSION *,intBool);
#if BSAVE_INSTANCES
LOCALE long BinarySaveInstancesCommand(void *);
LOCALE long EnvBinarySaveInstances(void *,const char *,int,EXPRESSION *,intBool);
#endif
#if BLOAD_INSTANCES
LOCALE long BinaryLoadInstancesCommand(void *);
LOCALE long EnvBinaryLoadInstances(void *,const char *);
#endif
LOCALE long EnvLoadInstances(void *,const char *);
LOCALE long EnvLoadInstancesFromString(void *,const char *,int);
LOCALE long EnvRestoreInstances(void *,const char *);
LOCALE long EnvRestoreInstancesFromString(void *,const char *,int);
#if ALLOW_ENVIRONMENT_GLOBALS
#if BLOAD_INSTANCES
LOCALE long BinaryLoadInstances(const char *);
#endif
#if BSAVE_INSTANCES
LOCALE long BinarySaveInstances(const char *,int,EXPRESSION *,intBool);
#endif
LOCALE long LoadInstances(const char *);
LOCALE long LoadInstancesFromString(const char *,int);
LOCALE long RestoreInstances(const char *);
LOCALE long RestoreInstancesFromString(const char *,int);
LOCALE long SaveInstances(const char *,int,EXPRESSION *,intBool);
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_insfile */
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSUserBuilder.h
|
#ifndef _clips_user_builder_h
#define _clips_user_builder_h
#include "llvm/User.h"
#include "ExpertSystem/CLIPSValueBuilder.h"
using namespace llvm;
class CLIPSUserBuilder : public CLIPSValueBuilder {
public:
CLIPSUserBuilder(std::string nm, std::string ty, FunctionNamer& namer);
void addFields(User* user, KnowledgeConstructor* kc, char* parent);
void build(User* user, KnowledgeConstructor* kc, char* parent);
};
#endif
|
DrItanium/durandal
|
include/pipeline/clips/CLIPSPassTemplates.h
|
#ifndef _clips_pass_templates_h
#define _clips_pass_templates_h
#include "indirect/IndirectPasses.h"
#include "pipeline/clips/CLIPSPass.h"
using namespace indirect;
namespace pipeline {
namespace clips {
class CLIPSModulePass : public IndirectModulePass, public CLIPSPass {
public:
CLIPSModulePass(char& id) : IndirectModulePass(id) { }
using IndirectModulePass::runOnModule;
virtual bool runOnModule(llvm::Module& module);
};
class CLIPSFunctionPass : public IndirectFunctionPass, public CLIPSPass {
public:
CLIPSFunctionPass(char& id) : IndirectFunctionPass(id) { }
using IndirectFunctionPass::runOnFunction;
virtual bool runOnFunction(llvm::Function& fn);
};
class CLIPSBasicBlockPass : public IndirectBasicBlockPass, public CLIPSPass {
public:
CLIPSBasicBlockPass(char& id) : IndirectBasicBlockPass(id) { }
using IndirectBasicBlockPass::runOnBasicBlock;
virtual bool runOnBasicBlock(llvm::BasicBlock& bb);
};
class CLIPSLoopPass : public IndirectLoopPass, public CLIPSPass {
public:
CLIPSLoopPass(char& id) : IndirectLoopPass(id) { }
using IndirectLoopPass::runOnLoop;
virtual bool runOnLoop(llvm::Loop* l, llvm::LPPassManager& lpm);
};
class CLIPSRegionPass : public IndirectRegionPass, public CLIPSPass {
public:
CLIPSRegionPass(char& id) : IndirectRegionPass(id) { }
using IndirectRegionPass::runOnRegion;
virtual bool runOnRegion(llvm::Region* r, llvm::RGPassManager& rg);
};
class CLIPSMachineFunctionPass : public IndirectMachineFunctionPass, public CLIPSPass {
public:
CLIPSMachineFunctionPass(char& id) : IndirectMachineFunctionPass(id) { }
using IndirectMachineFunctionPass::runOnMachineFunction;
virtual bool runOnMachineFunction(llvm::MachineFunction& mf);
};
class CLIPSCallGraphSCCPass : public IndirectCallGraphSCCPass, public CLIPSPass {
public:
CLIPSCallGraphSCCPass(char& id) : IndirectCallGraphSCCPass(id) { }
using IndirectCallGraphSCCPass::runOnSCC;
virtual bool runOnSCC(llvm::CallGraphSCC& scc);
};
}
}
#endif
|
DrItanium/durandal
|
lib/electron/prdctfun.c
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* PREDICATE FUNCTIONS MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: Contains the code for several predicate */
/* functions including not, and, or, eq, neq, <=, >=, <, */
/* >, =, <>, symbolp, stringp, lexemep, numberp, integerp, */
/* floatp, oddp, evenp, multifieldp, sequencep, and */
/* pointerp. */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Support for long long integers. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW and */
/* MAC_MCW). */
/* */
/*************************************************************/
#define _PRDCTFUN_SOURCE_
#include <stdio.h>
#define _STDIO_INCLUDED_
#include "setup.h"
#include "envrnmnt.h"
#include "exprnpsr.h"
#include "argacces.h"
#include "multifld.h"
#include "router.h"
#include "prdctfun.h"
/**************************************************/
/* PredicateFunctionDefinitions: Defines standard */
/* math and predicate functions. */
/**************************************************/
globle void PredicateFunctionDefinitions(
void *theEnv)
{
#if ! RUN_TIME
EnvDefineFunction2(theEnv,"not", 'b', NotFunction, "NotFunction", "11");
EnvDefineFunction2(theEnv,"and", 'b', AndFunction, "AndFunction", "2*");
EnvDefineFunction2(theEnv,"or", 'b', OrFunction, "OrFunction", "2*");
EnvDefineFunction2(theEnv,"eq", 'b', EqFunction, "EqFunction", "2*");
EnvDefineFunction2(theEnv,"neq", 'b', NeqFunction, "NeqFunction", "2*");
EnvDefineFunction2(theEnv,"<=", 'b', LessThanOrEqualFunction, "LessThanOrEqualFunction", "2*n");
EnvDefineFunction2(theEnv,">=", 'b', GreaterThanOrEqualFunction, "GreaterThanOrEqualFunction", "2*n");
EnvDefineFunction2(theEnv,"<", 'b', LessThanFunction, "LessThanFunction", "2*n");
EnvDefineFunction2(theEnv,">", 'b', GreaterThanFunction, "GreaterThanFunction", "2*n");
EnvDefineFunction2(theEnv,"=", 'b', NumericEqualFunction, "NumericEqualFunction", "2*n");
EnvDefineFunction2(theEnv,"<>", 'b', NumericNotEqualFunction, "NumericNotEqualFunction", "2*n");
EnvDefineFunction2(theEnv,"!=", 'b', NumericNotEqualFunction, "NumericNotEqualFunction", "2*n");
EnvDefineFunction2(theEnv,"symbolp", 'b', SymbolpFunction, "SymbolpFunction", "11");
EnvDefineFunction2(theEnv,"wordp", 'b', SymbolpFunction, "SymbolpFunction", "11");
EnvDefineFunction2(theEnv,"stringp", 'b', StringpFunction, "StringpFunction", "11");
EnvDefineFunction2(theEnv,"lexemep", 'b', LexemepFunction, "LexemepFunction", "11");
EnvDefineFunction2(theEnv,"numberp", 'b', NumberpFunction, "NumberpFunction", "11");
EnvDefineFunction2(theEnv,"integerp", 'b', IntegerpFunction, "IntegerpFunction", "11");
EnvDefineFunction2(theEnv,"floatp", 'b', FloatpFunction, "FloatpFunction", "11");
EnvDefineFunction2(theEnv,"oddp", 'b', OddpFunction, "OddpFunction", "11i");
EnvDefineFunction2(theEnv,"evenp", 'b', EvenpFunction, "EvenpFunction", "11i");
EnvDefineFunction2(theEnv,"multifieldp",'b', MultifieldpFunction, "MultifieldpFunction", "11");
EnvDefineFunction2(theEnv,"sequencep",'b', MultifieldpFunction, "MultifieldpFunction", "11");
EnvDefineFunction2(theEnv,"pointerp", 'b', PointerpFunction, "PointerpFunction", "11");
#else
#endif
}
/************************************/
/* EqFunction: H/L access routine */
/* for the eq function. */
/************************************/
globle intBool EqFunction(
void *theEnv)
{
DATA_OBJECT item, nextItem;
int numArgs, i;
struct expr *theExpression;
/*====================================*/
/* Determine the number of arguments. */
/*====================================*/
numArgs = EnvRtnArgCount(theEnv);
if (numArgs == 0) return(FALSE);
/*==============================================*/
/* Get the value of the first argument against */
/* which subsequent arguments will be compared. */
/*==============================================*/
theExpression = GetFirstArgument();
EvaluateExpression(theEnv,theExpression,&item);
/*=====================================*/
/* Compare all arguments to the first. */
/* If any are different, return FALSE. */
/*=====================================*/
theExpression = GetNextArgument(theExpression);
for (i = 2 ; i <= numArgs ; i++)
{
EvaluateExpression(theEnv,theExpression,&nextItem);
if (GetType(nextItem) != GetType(item))
{ return(FALSE); }
if (GetType(nextItem) == MULTIFIELD)
{
if (MultifieldDOsEqual(&nextItem,&item) == FALSE)
{ return(FALSE); }
}
else if (nextItem.value != item.value)
{ return(FALSE); }
theExpression = GetNextArgument(theExpression);
}
/*=====================================*/
/* All of the arguments were identical */
/* to the first. Return TRUE. */
/*=====================================*/
return(TRUE);
}
/*************************************/
/* NeqFunction: H/L access routine */
/* for the neq function. */
/*************************************/
globle intBool NeqFunction(
void *theEnv)
{
DATA_OBJECT item, nextItem;
int numArgs, i;
struct expr *theExpression;
/*====================================*/
/* Determine the number of arguments. */
/*====================================*/
numArgs = EnvRtnArgCount(theEnv);
if (numArgs == 0) return(FALSE);
/*==============================================*/
/* Get the value of the first argument against */
/* which subsequent arguments will be compared. */
/*==============================================*/
theExpression = GetFirstArgument();
EvaluateExpression(theEnv,theExpression,&item);
/*=====================================*/
/* Compare all arguments to the first. */
/* If any are the same, return FALSE. */
/*=====================================*/
for (i = 2, theExpression = GetNextArgument(theExpression);
i <= numArgs;
i++, theExpression = GetNextArgument(theExpression))
{
EvaluateExpression(theEnv,theExpression,&nextItem);
if (GetType(nextItem) != GetType(item))
{ continue; }
else if (nextItem.type == MULTIFIELD)
{
if (MultifieldDOsEqual(&nextItem,&item) == TRUE)
{ return(FALSE); }
}
else if (nextItem.value == item.value)
{ return(FALSE); }
}
/*=====================================*/
/* All of the arguments were different */
/* from the first. Return TRUE. */
/*=====================================*/
return(TRUE);
}
/*****************************************/
/* StringpFunction: H/L access routine */
/* for the stringp function. */
/*****************************************/
globle intBool StringpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"stringp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) == STRING)
{ return(TRUE); }
else
{ return(FALSE); }
}
/*****************************************/
/* SymbolpFunction: H/L access routine */
/* for the symbolp function. */
/*****************************************/
globle intBool SymbolpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"symbolp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) == SYMBOL)
{ return(TRUE); }
else
{ return(FALSE); }
}
/*****************************************/
/* LexemepFunction: H/L access routine */
/* for the lexemep function. */
/*****************************************/
globle intBool LexemepFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"lexemep",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if ((GetType(item) == SYMBOL) || (GetType(item) == STRING))
{ return(TRUE); }
else
{ return(FALSE); }
}
/*****************************************/
/* NumberpFunction: H/L access routine */
/* for the numberp function. */
/*****************************************/
globle intBool NumberpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"numberp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if ((GetType(item) == FLOAT) || (GetType(item) == INTEGER))
{ return(TRUE); }
else
{ return(FALSE); }
}
/****************************************/
/* FloatpFunction: H/L access routine */
/* for the floatp function. */
/****************************************/
globle intBool FloatpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"floatp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) == FLOAT)
{ return(TRUE); }
else
{ return(FALSE); }
}
/******************************************/
/* IntegerpFunction: H/L access routine */
/* for the integerp function. */
/******************************************/
globle intBool IntegerpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"integerp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) != INTEGER) return(FALSE);
return(TRUE);
}
/*********************************************/
/* MultifieldpFunction: H/L access routine */
/* for the multifieldp function. */
/*********************************************/
globle intBool MultifieldpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"multifieldp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) != MULTIFIELD) return(FALSE);
return(TRUE);
}
/******************************************/
/* PointerpFunction: H/L access routine */
/* for the pointerp function. */
/******************************************/
globle intBool PointerpFunction(
void *theEnv)
{
DATA_OBJECT item;
if (EnvArgCountCheck(theEnv,"pointerp",EXACTLY,1) == -1) return(FALSE);
EnvRtnUnknown(theEnv,1,&item);
if (GetType(item) != EXTERNAL_ADDRESS) return(FALSE);
return(TRUE);
}
/*************************************/
/* NotFunction: H/L access routine */
/* for the not function. */
/*************************************/
globle intBool NotFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT result;
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(FALSE); }
if (EvaluateExpression(theEnv,theArgument,&result)) return(FALSE);
if ((result.value == EnvFalseSymbol(theEnv)) && (result.type == SYMBOL))
{ return(TRUE); }
return(FALSE);
}
/*************************************/
/* AndFunction: H/L access routine */
/* for the and function. */
/*************************************/
globle intBool AndFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT result;
for (theArgument = GetFirstArgument();
theArgument != NULL;
theArgument = GetNextArgument(theArgument))
{
if (EvaluateExpression(theEnv,theArgument,&result)) return(FALSE);
if ((result.value == EnvFalseSymbol(theEnv)) && (result.type == SYMBOL))
{ return(FALSE); }
}
return(TRUE);
}
/************************************/
/* OrFunction: H/L access routine */
/* for the or function. */
/************************************/
globle intBool OrFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT result;
for (theArgument = GetFirstArgument();
theArgument != NULL;
theArgument = GetNextArgument(theArgument))
{
if (EvaluateExpression(theEnv,theArgument,&result)) return(FALSE);
if ((result.value != EnvFalseSymbol(theEnv)) || (result.type != SYMBOL))
{ return(TRUE); }
}
return(FALSE);
}
/*****************************************/
/* LessThanOrEqualFunction: H/L access */
/* routine for the <= function. */
/*****************************************/
globle intBool LessThanOrEqualFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,"<=",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*====================================================*/
/* Compare each of the subsequent arguments to its */
/* predecessor. If any is greater, then return FALSE. */
/*====================================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,"<=",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) > ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) > ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) > (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) > ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
rv1.type = rv2.type;
rv1.value = rv2.value;
}
/*======================================*/
/* Each argument was less than or equal */
/* to it predecessor. Return TRUE. */
/*======================================*/
return(TRUE);
}
/********************************************/
/* GreaterThanOrEqualFunction: H/L access */
/* routine for the >= function. */
/********************************************/
globle intBool GreaterThanOrEqualFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,">=",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*===================================================*/
/* Compare each of the subsequent arguments to its */
/* predecessor. If any is lesser, then return FALSE. */
/*===================================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,">=",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) < ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) < ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) < (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) < ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
rv1.type = rv2.type;
rv1.value = rv2.value;
}
/*=========================================*/
/* Each argument was greater than or equal */
/* to its predecessor. Return TRUE. */
/*=========================================*/
return(TRUE);
}
/**********************************/
/* LessThanFunction: H/L access */
/* routine for the < function. */
/**********************************/
globle intBool LessThanFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,"<",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*==========================================*/
/* Compare each of the subsequent arguments */
/* to its predecessor. If any is greater or */
/* equal, then return FALSE. */
/*==========================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,"<",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) >= ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) >= ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) >= (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) >= ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
rv1.type = rv2.type;
rv1.value = rv2.value;
}
/*=================================*/
/* Each argument was less than its */
/* predecessor. Return TRUE. */
/*=================================*/
return(TRUE);
}
/*************************************/
/* GreaterThanFunction: H/L access */
/* routine for the > function. */
/*************************************/
globle intBool GreaterThanFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,">",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*==========================================*/
/* Compare each of the subsequent arguments */
/* to its predecessor. If any is lesser or */
/* equal, then return FALSE. */
/*==========================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,">",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) <= ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) <= ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) <= (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) <= ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
rv1.type = rv2.type;
rv1.value = rv2.value;
}
/*================================*/
/* Each argument was greater than */
/* its predecessor. Return TRUE. */
/*================================*/
return(TRUE);
}
/**************************************/
/* NumericEqualFunction: H/L access */
/* routine for the = function. */
/**************************************/
globle intBool NumericEqualFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,"=",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*=================================================*/
/* Compare each of the subsequent arguments to the */
/* first. If any is unequal, then return FALSE. */
/*=================================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,"=",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) != ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) != ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) != (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) != ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
}
/*=================================*/
/* All arguments were equal to the */
/* first argument. Return TRUE. */
/*=================================*/
return(TRUE);
}
/*****************************************/
/* NumericNotEqualFunction: H/L access */
/* routine for the <> function. */
/*****************************************/
globle intBool NumericNotEqualFunction(
void *theEnv)
{
EXPRESSION *theArgument;
DATA_OBJECT rv1, rv2;
int pos = 1;
/*=========================*/
/* Get the first argument. */
/*=========================*/
theArgument = GetFirstArgument();
if (theArgument == NULL) { return(TRUE); }
if (! GetNumericArgument(theEnv,theArgument,"<>",&rv1,FALSE,pos)) return(FALSE);
pos++;
/*=================================================*/
/* Compare each of the subsequent arguments to the */
/* first. If any is equal, then return FALSE. */
/*=================================================*/
for (theArgument = GetNextArgument(theArgument);
theArgument != NULL;
theArgument = GetNextArgument(theArgument), pos++)
{
if (! GetNumericArgument(theEnv,theArgument,"<>",&rv2,FALSE,pos)) return(FALSE);
if (rv1.type == INTEGER)
{
if (rv2.type == INTEGER)
{
if (ValueToLong(rv1.value) == ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if ((double) ValueToLong(rv1.value) == ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
else
{
if (rv2.type == INTEGER)
{
if (ValueToDouble(rv1.value) == (double) ValueToLong(rv2.value))
{ return(FALSE); }
}
else
{
if (ValueToDouble(rv1.value) == ValueToDouble(rv2.value))
{ return(FALSE); }
}
}
}
/*===================================*/
/* All arguments were unequal to the */
/* first argument. Return TRUE. */
/*===================================*/
return(TRUE);
}
/**************************************/
/* OddpFunction: H/L access routine */
/* for the oddp function. */
/**************************************/
globle intBool OddpFunction(
void *theEnv)
{
DATA_OBJECT item;
long long num, halfnum;
if (EnvArgCountCheck(theEnv,"oddp",EXACTLY,1) == -1) return(FALSE);
if (EnvArgTypeCheck(theEnv,"oddp",1,INTEGER,&item) == FALSE) return(FALSE);
num = DOToLong(item);
halfnum = (num / 2) * 2;
if (num == halfnum) return(FALSE);
return(TRUE);
}
/***************************************/
/* EvenpFunction: H/L access routine */
/* for the evenp function. */
/***************************************/
globle intBool EvenpFunction(
void *theEnv)
{
DATA_OBJECT item;
long long num, halfnum;
if (EnvArgCountCheck(theEnv,"evenp",EXACTLY,1) == -1) return(FALSE);
if (EnvArgTypeCheck(theEnv,"evenp",1,INTEGER,&item) == FALSE) return(FALSE);
num = DOToLong(item);
halfnum = (num / 2) * 2;
if (num != halfnum) return(FALSE);
return(TRUE);
}
|
DrItanium/durandal
|
include/indirect/IndirectPassRegistry.h
|
<reponame>DrItanium/durandal<gh_stars>1-10
#ifndef _indirect_pass_registry_h
#define _indirect_pass_registry_h
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
#include "indirect/IndirectPassHeader.h"
#include "indirect/RegisterIndirectPass.h"
#include "indirect/IndirectPassGenerator.h"
/*
* In order to keep track of indirect passes it's necessary to define a new
* PassRegistry that keeps track of extra information while interacting with
* llvm::PassRegistry automatically.
*/
namespace indirect {
class IndirectPassRegistry {
public:
typedef llvm::StringMap<indirect::IndirectPassHeader*> PassHeaderMapType;
typedef llvm::StringMap<indirect::RegisterIndirectPass*> RegisterIndirectPassMapType;
typedef llvm::StringMap<indirect::IndirectPassGeneratorBase*> PassGeneratorMapType;
private:
PassHeaderMapType registeredIndirectPasses;
RegisterIndirectPassMapType registeredIndirectPassInfos;
PassGeneratorMapType registeredPassGenerators;
public:
IndirectPassRegistry();
~IndirectPassRegistry();
static IndirectPassRegistry* getIndirectPassRegistry();
template<class PassGeneratorClass>
static IndirectPassGeneratorBase* buildPassGenerator() {
return new PassGeneratorClass();
}
static const void* getUniqueId(const char* name);
static const void* getUniqueId(llvm::StringRef name);
static const void* getUniqueId(char* name);
template<class PassGeneratorClass>
void registerPassGenerator(char* name) {
registerPassGenerator<PassGeneratorClass>(
llvm::StringRef((const char*)name));
}
template<class PassGeneratorClass>
void registerPassGenerator(const char* name) {
registerPassGenerator<PassGeneratorClass>(
llvm::StringRef(name));
}
template<class PassGeneratorClass>
void registerPassGenerator(llvm::StringRef name) {
assert((registeredPassGenerators.find(name) ==
registeredPassGenerators.end()) &&
"Pass generator already registered!");
registeredPassGenerators[name] =
IndirectPassRegistry::buildPassGenerator<PassGeneratorClass>();
}
void registerIndirectPassHeader(indirect::IndirectPassHeader* header);
void unregisterIndirectPassHeader(indirect::IndirectPassHeader* header);
void unregisterIndirectPassHeader(char* name);
void unregisterIndirectPassHeader(const char* name);
void unregisterIndirectPassHeader(llvm::StringRef name);
IndirectPassHeader* getIndirectPassHeader(char* name) const;
IndirectPassHeader* getIndirectPassHeader(const char* name) const;
IndirectPassHeader* getIndirectPassHeader(llvm::StringRef name) const;
llvm::PassInfo* getIndirectPassInfo(char* name) const;
llvm::PassInfo* getIndirectPassInfo(const char* name) const;
llvm::PassInfo* getIndirectPassInfo(llvm::StringRef name) const;
llvm::Pass* createPass(char* name);
llvm::Pass* createPass(const char* name);
llvm::Pass* createPass(llvm::StringRef name);
};
}
#endif
|
DrItanium/durandal
|
include/rampancy/CLIPSFunctions.h
|
<reponame>DrItanium/durandal<filename>include/rampancy/CLIPSFunctions.h
#ifndef _rampancy_llvm_h
#define _rampancy_llvm_h
// Contains the header interface between the Rampancy library and
// clips.
extern "C" void SetupRampancyExpertSystemInterfaces(void* ptr);
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSEnvironment.h
|
#ifndef _clips_environment_h
#define _clips_environment_h
#include "ExpertSystem/Types.h"
class CLIPSEnvironment {
private:
void* environment;
bool fullyOwned;
public:
CLIPSEnvironment(void* theEnv=0);
~CLIPSEnvironment();
bool environmentCreated();
void* getEnvironment();
void reset();
void clear();
void run(ExecutionDuration count);
void saveInstances(char* fileName);
void assertFact(char* str);
bool makeInstances(char* str);
bool makeInstance(char* str);
void batchStar(char* str);
void eval(char* str);
void build(char* str);
};
#endif
|
DrItanium/durandal
|
include/electron/insfun.h
|
<reponame>DrItanium/durandal
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* INSTANCE FUNCTIONS MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */
/* */
/* Changed name of variable log to logName */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* Changed name of variable exp to theExp */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* 6.24: Link error occurs for the SlotExistError */
/* function when OBJECT_SYSTEM is set to 0 in */
/* setup.h. DR0865 */
/* */
/* Converted INSTANCE_PATTERN_MATCHING to */
/* DEFRULE_CONSTRUCT. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* Moved EvaluateAndStoreInDataObject to */
/* evaluatn.c */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Changed integer type/precision. */
/* */
/* Changed garbage collection algorithm. */
/* */
/* Support for long long integers. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Fixed slot override default ?NONE bug. */
/* */
//*************************************************************/
#ifndef _H_insfun
#define _H_insfun
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifndef _H_moduldef
#include "moduldef.h"
#endif
#ifndef _H_object
#include "object.h"
#endif
#ifndef _H_pattern
#include "pattern.h"
#endif
typedef struct igarbage
{
INSTANCE_TYPE *ins;
struct igarbage *nxt;
} IGARBAGE;
#define INSTANCE_TABLE_HASH_SIZE 8191
#define InstanceSizeHeuristic(ins) sizeof(INSTANCE_TYPE)
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _INSFUN_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void EnvIncrementInstanceCount(void *,void *);
LOCALE void EnvDecrementInstanceCount(void *,void *);
LOCALE void InitializeInstanceTable(void *);
LOCALE void CleanupInstances(void *);
LOCALE unsigned HashInstance(SYMBOL_HN *);
LOCALE void DestroyAllInstances(void *);
LOCALE void RemoveInstanceData(void *,INSTANCE_TYPE *);
LOCALE INSTANCE_TYPE *FindInstanceBySymbol(void *,SYMBOL_HN *);
LOCALE INSTANCE_TYPE *FindInstanceInModule(void *,SYMBOL_HN *,struct defmodule *,
struct defmodule *,unsigned);
LOCALE INSTANCE_SLOT *FindInstanceSlot(void *,INSTANCE_TYPE *,SYMBOL_HN *);
LOCALE int FindInstanceTemplateSlot(void *,DEFCLASS *,SYMBOL_HN *);
LOCALE int PutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *,const char *);
LOCALE int DirectPutSlotValue(void *,INSTANCE_TYPE *,INSTANCE_SLOT *,DATA_OBJECT *,DATA_OBJECT *);
LOCALE intBool ValidSlotValue(void *,DATA_OBJECT *,SLOT_DESC *,INSTANCE_TYPE *,const char *);
LOCALE INSTANCE_TYPE *CheckInstance(void *,const char *);
LOCALE void NoInstanceError(void *,const char *,const char *);
LOCALE void StaleInstanceAddress(void *,const char *,int);
LOCALE int EnvGetInstancesChanged(void *);
LOCALE void EnvSetInstancesChanged(void *,int);
LOCALE void PrintSlot(void *,const char *,SLOT_DESC *,INSTANCE_TYPE *,const char *);
LOCALE void PrintInstanceNameAndClass(void *,const char *,INSTANCE_TYPE *,intBool);
LOCALE void PrintInstanceName(void *,const char *,void *);
LOCALE void PrintInstanceLongForm(void *,const char *,void *);
#if DEFRULE_CONSTRUCT && OBJECT_SYSTEM
LOCALE void DecrementObjectBasisCount(void *,void *);
LOCALE void IncrementObjectBasisCount(void *,void *);
LOCALE void MatchObjectFunction(void *,void *);
LOCALE intBool NetworkSynchronized(void *,void *);
#endif
#if ALLOW_ENVIRONMENT_GLOBALS
LOCALE void DecrementInstanceCount(void *);
LOCALE int GetInstancesChanged(void);
LOCALE void IncrementInstanceCount(void *);
LOCALE void SetInstancesChanged(int);
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_insfun */
|
DrItanium/durandal
|
include/indirect/IndirectPasses.h
|
<gh_stars>1-10
#ifndef _indirect_module_pass_h
#define _indirect_module_pass_h
#include "llvm/ADT/StringRef.h"
#include "llvm/Pass.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/CallGraphSCCPass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "indirect/IndirectPassHeader.h"
#include "indirect/IndirectPass.h"
/* These classes are extensions of the different passes defined in LLVM
* Unless you want to implement a backend you should never need to mess with
* these classes directly.
*
* These classes are abstract and are meant to be inherited from to be used to
* implement backend base template passes. The logic for what to do when
* running a module pass is run. It is up to the programmer to provide
* interaction logic if they want to return information from another language
* into C++.
*
* It is also up to the implementer to provide mechanims to bundle non native
* passes together if they wish it.
*/
namespace indirect {
class IndirectModulePass : public llvm::ModulePass, public IndirectPass {
public:
IndirectModulePass(char& ident);
using llvm::ModulePass::runOnModule;
using llvm::ModulePass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnModule(llvm::Module &m) = 0;
};
class IndirectFunctionPass : public llvm::FunctionPass, public IndirectPass{
public:
IndirectFunctionPass(char& ident);
using llvm::FunctionPass::runOnFunction;
using llvm::FunctionPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnFunction(llvm::Function& fn) = 0;
};
class IndirectBasicBlockPass : public llvm::BasicBlockPass, public IndirectPass {
public:
IndirectBasicBlockPass(char& ident);
using llvm::BasicBlockPass::runOnBasicBlock;
using llvm::BasicBlockPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnBasicBlock(llvm::BasicBlock& bb) = 0;
};
class IndirectLoopPass : public llvm::LoopPass, public IndirectPass {
public:
IndirectLoopPass(char& ident);
using llvm::LoopPass::runOnLoop;
using llvm::LoopPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnLoop(llvm::Loop* loop,
llvm::LPPassManager& lpm) = 0;
};
class IndirectMachineFunctionPass : public llvm::MachineFunctionPass, public IndirectPass {
public:
IndirectMachineFunctionPass(char& ident);
using llvm::MachineFunctionPass::runOnMachineFunction;
using llvm::MachineFunctionPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnMachineFunction(llvm::MachineFunction& mf) = 0;
};
class IndirectRegionPass : public llvm::RegionPass, public IndirectPass {
public:
IndirectRegionPass(char& ident);
using llvm::RegionPass::runOnRegion;
using llvm::RegionPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnRegion(llvm::Region* region,
llvm::RGPassManager& rgm) = 0;
};
class IndirectCallGraphSCCPass : public llvm::CallGraphSCCPass, public IndirectPass {
public:
IndirectCallGraphSCCPass(char& ident);
using llvm::CallGraphSCCPass::runOnSCC;
using llvm::CallGraphSCCPass::getAnalysisUsage;
virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const;
virtual bool runOnSCC(llvm::CallGraphSCC& scc) = 0;
};
class PassTypeNotSupported {
public:
PassTypeNotSupported(char& id) {
bool b = false;
assert(b == true && "Given Pass Type Not Supported");
}
};
}
#endif
|
DrItanium/durandal
|
include/rampancy/Compiler.h
|
<reponame>DrItanium/durandal
#ifndef _rampancy_compiler_h
#define _rampancy_compiler_h
/*
* The rampancy library is a standard way to access compilers and interpreters
* from within CLIPS. It assumes that you're going to generate a pass
*
* This class is abstract
*/
#include "llvm/Pass.h"
#include "llvm/Module.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/StringRef.h"
namespace rampancy {
class Compiler {
private:
llvm::LLVMContext* context;
CLIPSEnvironment* env;
public:
Compiler();
~Compiler();
//this one gets arguments straight from CLIPS
virtual llvm::Module* compile() = 0;
virtual llvm::Module* compile(int argc, char** argv) = 0;
virtual llvm::Module* interpret() = 0;
virtual llvm::Module* interpret(llvm::StringRef input) = 0;
llvm::LLVMContext* getContext();
void setContext(llvm::LLVMContext* context);
void setEnvironment(CLIPSEnvironment* tEnv);
CLIPSEnvironment* getEnvironment();
};
}
#endif
|
DrItanium/durandal
|
include/indirect/IndirectAnalysisUsageDeclaration.h
|
<gh_stars>1-10
#ifndef _indirect_analysis_usage_declaration_h
#define _indirect_analysis_usage_declaration_h
#include "llvm/Pass.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallVector.h"
/* Defines the actions that would normally be provided by getAnalysisUsage but
* in an indirect manner.
*/
namespace indirect {
class IndirectAnalysisUsageDeclaration {
public:
typedef llvm::SmallVector<std::string*, 32> VectorType;
private:
bool pAll;
bool pCFG;
VectorType required, requiredTransitive, preserved;
public:
IndirectAnalysisUsageDeclaration();
~IndirectAnalysisUsageDeclaration();
void addRequired(char* name);
void addRequired(const char* name);
void addRequired(llvm::StringRef name);
void addRequiredTransitive(const char* name);
void addRequiredTransitive(char* name);
void addRequiredTransitive(llvm::StringRef name);
void addPreserved(char* name);
void addPreserved(const char* name);
void addPreserved(llvm::StringRef name);
void setPreservesAll(bool preservesAll);
void setPreservesCFG(bool preservsCFG);
bool preservesAll();
bool preservesCFG();
void updateAnalysisUsage(llvm::AnalysisUsage& usage);
void operator() (llvm::AnalysisUsage& usage);
};
}
#endif
|
DrItanium/durandal
|
lib/electron/factrhs.c
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/20/14 */
/* */
/* FACT RHS PATTERN PARSER MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: Provides a number of routines for parsing fact */
/* patterns typically found on the RHS of a rule (such as */
/* the assert command). Also contains some functions for */
/* parsing RHS slot values (used by functions such as */
/* assert, modify, and duplicate). */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* <NAME> */
/* <NAME> */
/* */
/* Revision History: */
/* */
/* 6.30: Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Added code to prevent a clear command from */
/* being executed during fact assertions via */
/* Increment/DecrementClearReadyLocks API. */
/* */
/*************************************************************/
#define _FACTRHS_SOURCE_
#include <stdio.h>
#define _STDIO_INCLUDED_
#include <string.h>
#include "setup.h"
#if DEFTEMPLATE_CONSTRUCT
#include "constant.h"
#include "envrnmnt.h"
#include "extnfunc.h"
#include "modulutl.h"
#include "modulpsr.h"
#include "pattern.h"
#include "prntutil.h"
#include "cstrcpsr.h"
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
#include "bload.h"
#endif
#include "tmpltpsr.h"
#include "tmpltrhs.h"
#include "tmpltutl.h"
#include "exprnpsr.h"
#include "strngrtr.h"
#include "router.h"
#include "factrhs.h"
/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/
#if RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE
static void NoSuchTemplateError(void *,const char *);
#endif
#if (! RUN_TIME)
/**********************************************************************/
/* BuildRHSAssert: Parses zero or more RHS fact patterns (the format */
/* which is used by the assert command and the deffacts construct). */
/* Each of the RHS patterns is attached to an assert command and if */
/* there is more than one assert command, then a progn command is */
/* wrapped around all of the assert commands. */
/**********************************************************************/
globle struct expr *BuildRHSAssert(
void *theEnv,
const char *logicalName,
struct token *theToken,
int *error,
int atLeastOne,
int readFirstParen,
const char *whereParsed)
{
struct expr *lastOne, *nextOne, *assertList, *stub;
*error = FALSE;
/*===============================================================*/
/* If the first parenthesis of the RHS fact pattern has not been */
/* read yet, then get the next token. If a right parenthesis is */
/* encountered then exit (however, set the error return value if */
/* at least one fact was expected). */
/*===============================================================*/
if (readFirstParen == FALSE)
{
if (theToken->type == RPAREN)
{
if (atLeastOne)
{
*error = TRUE;
SyntaxErrorMessage(theEnv,whereParsed);
}
return(NULL);
}
}
/*================================================*/
/* Parse the facts until no more are encountered. */
/*================================================*/
lastOne = assertList = NULL;
while ((nextOne = GetRHSPattern(theEnv,logicalName,theToken,
error,FALSE,readFirstParen,
TRUE,RPAREN)) != NULL)
{
PPCRAndIndent(theEnv);
stub = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"assert"));
stub->argList = nextOne;
nextOne = stub;
if (lastOne == NULL)
{ assertList = nextOne; }
else
{ lastOne->nextArg = nextOne; }
lastOne = nextOne;
readFirstParen = TRUE;
}
/*======================================================*/
/* If an error was detected while parsing, then return. */
/*======================================================*/
if (*error)
{
ReturnExpression(theEnv,assertList);
return(NULL);
}
/*======================================*/
/* Fix the pretty print representation. */
/*======================================*/
if (theToken->type == RPAREN)
{
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,")");
}
/*==============================================================*/
/* If no facts are being asserted then return NULL. In addition */
/* if at least one fact was required, then signal an error. */
/*==============================================================*/
if (assertList == NULL)
{
if (atLeastOne)
{
*error = TRUE;
SyntaxErrorMessage(theEnv,whereParsed);
}
return(NULL);
}
/*===============================================*/
/* If more than one fact is being asserted, then */
/* wrap the assert commands within a progn call. */
/*===============================================*/
if (assertList->nextArg != NULL)
{
stub = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"progn"));
stub->argList = assertList;
assertList = stub;
}
/*==========================================================*/
/* Return the expression for asserting the specified facts. */
/*==========================================================*/
return(assertList);
}
#endif
/***************************************************************/
/* GetRHSPattern: Parses a single RHS fact pattern. The return */
/* value is the fact just parsed (or NULL if the delimiter */
/* for no more facts is the first token parsed). If an error */
/* occurs, then the error flag passed as an argument is set. */
/***************************************************************/
globle struct expr *GetRHSPattern(
void *theEnv,
const char *readSource,
struct token *tempToken,
int *error,
int constantsOnly,
int readFirstParen,
int checkFirstParen,
int endType)
{
struct expr *lastOne = NULL;
struct expr *nextOne, *firstOne, *argHead = NULL;
int printError, count;
struct deftemplate *theDeftemplate;
struct symbolHashNode *templateName;
const char *nullBitMap = "\0";
/*=================================================*/
/* Get the opening parenthesis of the RHS pattern. */
/*=================================================*/
*error = FALSE;
if (readFirstParen) GetToken(theEnv,readSource,tempToken);
if (checkFirstParen)
{
if (tempToken->type == endType) return(NULL);
if (tempToken->type != LPAREN)
{
SyntaxErrorMessage(theEnv,"RHS patterns");
*error = TRUE;
return(NULL);
}
}
/*======================================================*/
/* The first field of an asserted fact must be a symbol */
/* (but not = or : which have special significance). */
/*======================================================*/
GetToken(theEnv,readSource,tempToken);
if (tempToken->type != SYMBOL)
{
SyntaxErrorMessage(theEnv,"first field of a RHS pattern");
*error = TRUE;
return(NULL);
}
else if ((strcmp(ValueToString(tempToken->value),"=") == 0) ||
(strcmp(ValueToString(tempToken->value),":") == 0))
{
SyntaxErrorMessage(theEnv,"first field of a RHS pattern");
*error = TRUE;
return(NULL);
}
/*=========================================================*/
/* Check to see if the relation name is a reserved symbol. */
/*=========================================================*/
templateName = (struct symbolHashNode *) tempToken->value;
if (ReservedPatternSymbol(theEnv,ValueToString(templateName),NULL))
{
ReservedPatternSymbolErrorMsg(theEnv,ValueToString(templateName),"a relation name");
*error = TRUE;
return(NULL);
}
/*============================================================*/
/* A module separator in the name is illegal in this context. */
/*============================================================*/
if (FindModuleSeparator(ValueToString(templateName)))
{
IllegalModuleSpecifierMessage(theEnv);
*error = TRUE;
return(NULL);
}
/*=============================================================*/
/* Determine if there is an associated deftemplate. If so, let */
/* the deftemplate parsing functions parse the RHS pattern and */
/* then return the fact pattern that was parsed. */
/*=============================================================*/
theDeftemplate = (struct deftemplate *)
FindImportedConstruct(theEnv,"deftemplate",NULL,ValueToString(templateName),
&count,TRUE,NULL);
if (count > 1)
{
AmbiguousReferenceErrorMessage(theEnv,"deftemplate",ValueToString(templateName));
*error = TRUE;
return(NULL);
}
/*======================================================*/
/* If no deftemplate exists with the specified relation */
/* name, then create an implied deftemplate. */
/*======================================================*/
if (theDeftemplate == NULL)
#if (! BLOAD_ONLY) && (! RUN_TIME)
{
#if BLOAD || BLOAD_AND_BSAVE
if ((Bloaded(theEnv)) && (! ConstructData(theEnv)->CheckSyntaxMode))
{
NoSuchTemplateError(theEnv,ValueToString(templateName));
*error = TRUE;
return(NULL);
}
#endif
#if DEFMODULE_CONSTRUCT
if (FindImportExportConflict(theEnv,"deftemplate",((struct defmodule *) EnvGetCurrentModule(theEnv)),ValueToString(templateName)))
{
ImportExportConflictMessage(theEnv,"implied deftemplate",ValueToString(templateName),NULL,NULL);
*error = TRUE;
return(NULL);
}
#endif
if (! ConstructData(theEnv)->CheckSyntaxMode)
{ theDeftemplate = CreateImpliedDeftemplate(theEnv,(SYMBOL_HN *) templateName,TRUE); }
}
#else
{
NoSuchTemplateError(theEnv,ValueToString(templateName));
*error = TRUE;
return(NULL);
}
#endif
/*=========================================*/
/* If an explicit deftemplate exists, then */
/* parse the fact as a deftemplate fact. */
/*=========================================*/
if ((theDeftemplate != NULL) && (theDeftemplate->implied == FALSE))
{
firstOne = GenConstant(theEnv,DEFTEMPLATE_PTR,theDeftemplate);
firstOne->nextArg = ParseAssertTemplate(theEnv,readSource,tempToken,
error,endType,
constantsOnly,theDeftemplate);
if (*error)
{
ReturnExpression(theEnv,firstOne);
firstOne = NULL;
}
return(firstOne);
}
/*========================================*/
/* Parse the fact as an ordered RHS fact. */
/*========================================*/
firstOne = GenConstant(theEnv,DEFTEMPLATE_PTR,theDeftemplate);
#if (! RUN_TIME) && (! BLOAD_ONLY)
SavePPBuffer(theEnv," ");
#endif
while ((nextOne = GetAssertArgument(theEnv,readSource,tempToken,
error,endType,constantsOnly,&printError)) != NULL)
{
if (argHead == NULL) argHead = nextOne;
else lastOne->nextArg = nextOne;
lastOne = nextOne;
#if (! RUN_TIME) && (! BLOAD_ONLY)
SavePPBuffer(theEnv," ");
#endif
}
/*===========================================================*/
/* If an error occurred, set the error flag and return NULL. */
/*===========================================================*/
if (*error)
{
if (printError) SyntaxErrorMessage(theEnv,"RHS patterns");
ReturnExpression(theEnv,firstOne);
ReturnExpression(theEnv,argHead);
return(NULL);
}
/*=====================================*/
/* Fix the pretty print representation */
/* of the RHS ordered fact. */
/*=====================================*/
#if (! RUN_TIME) && (! BLOAD_ONLY)
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,tempToken->printForm);
#endif
/*==========================================================*/
/* Ordered fact assertions are processed by stuffing all of */
/* the fact's proposition (except the relation name) into a */
/* single multifield slot. */
/*==========================================================*/
firstOne->nextArg = GenConstant(theEnv,FACT_STORE_MULTIFIELD,EnvAddBitMap(theEnv,(void *) nullBitMap,1));
firstOne->nextArg->argList = argHead;
/*==============================*/
/* Return the RHS ordered fact. */
/*==============================*/
return(firstOne);
}
/********************************************************************/
/* GetAssertArgument: Parses a single RHS slot value and returns an */
/* expression representing the value. When parsing a deftemplate */
/* slot, the slot name has already been parsed when this function */
/* is called. NULL is returned if a slot or fact delimiter is */
/* encountered. In the event of a parse error, the error flag */
/* passed as an argument is set. */
/********************************************************************/
globle struct expr *GetAssertArgument(
void *theEnv,
const char *logicalName,
struct token *theToken,
int *error,
int endType,
int constantsOnly,
int *printError)
{
#if ! RUN_TIME
struct expr *nextField;
#else
struct expr *nextField = NULL;
#endif
/*=================================================*/
/* Read in the first token of the slot's value. If */
/* the end delimiter is encountered, then return. */
/*=================================================*/
*printError = TRUE;
GetToken(theEnv,logicalName,theToken);
if (theToken->type == endType) return(NULL);
/*=============================================================*/
/* If an equal sign of left parenthesis was parsed, then parse */
/* a function which is to be evaluated to determine the slot's */
/* value. The equal sign corresponds to the return value */
/* constraint which can be used in LHS fact patterns. The */
/* equal sign is no longer necessary on either the LHS or RHS */
/* of a rule to indicate that a function is being evaluated to */
/* determine its value either for assignment or pattern */
/* matching. */
/*=============================================================*/
if ((theToken->type == SYMBOL) ?
(strcmp(ValueToString(theToken->value),"=") == 0) :
(theToken->type == LPAREN))
{
if (constantsOnly)
{
*error = TRUE;
return(NULL);
}
#if ! RUN_TIME
if (theToken->type == LPAREN) nextField = Function1Parse(theEnv,logicalName);
else nextField = Function0Parse(theEnv,logicalName);
if (nextField == NULL)
#endif
{
*printError = FALSE;
*error = TRUE;
}
#if ! RUN_TIME
else
{
theToken->type= RPAREN;
theToken->value = (void *) EnvAddSymbol(theEnv,")");
theToken->printForm = ")";
}
#endif
return(nextField);
}
/*==================================================*/
/* Constants are always allowed as RHS slot values. */
/*==================================================*/
if ((theToken->type == SYMBOL) || (theToken->type == STRING) ||
#if OBJECT_SYSTEM
(theToken->type == INSTANCE_NAME) ||
#endif
(theToken->type == FLOAT) || (theToken->type == INTEGER))
{ return(GenConstant(theEnv,theToken->type,theToken->value)); }
/*========================================*/
/* Variables are also allowed as RHS slot */
/* values under some circumstances. */
/*========================================*/
if ((theToken->type == SF_VARIABLE) ||
#if DEFGLOBAL_CONSTRUCT
(theToken->type == GBL_VARIABLE) ||
(theToken->type == MF_GBL_VARIABLE) ||
#endif
(theToken->type == MF_VARIABLE))
{
if (constantsOnly)
{
*error = TRUE;
return(NULL);
}
return(GenConstant(theEnv,theToken->type,theToken->value));
}
/*==========================================================*/
/* If none of the other cases have been satisfied, then the */
/* token parsed is not appropriate for a RHS slot value. */
/*==========================================================*/
*error = TRUE;
return(NULL);
}
/****************************************************/
/* StringToFact: Converts the string representation */
/* of a fact to a fact data structure. */
/****************************************************/
globle struct fact *StringToFact(
void *theEnv,
const char *str)
{
struct token theToken;
struct fact *factPtr;
unsigned numberOfFields = 0, whichField;
struct expr *assertArgs, *tempPtr;
int error = FALSE;
DATA_OBJECT theResult;
/*=========================================*/
/* Open a string router and parse the fact */
/* using the router as an input source. */
/*=========================================*/
SetEvaluationError(theEnv,FALSE);
OpenStringSource(theEnv,"assert_str",str,0);
assertArgs = GetRHSPattern(theEnv,"assert_str",&theToken,
&error,FALSE,TRUE,
TRUE,RPAREN);
CloseStringSource(theEnv,"assert_str");
/*===========================================*/
/* Check for errors or the use of variables. */
/*===========================================*/
if ((assertArgs == NULL) && (! error))
{
SyntaxErrorMessage(theEnv,"RHS patterns");
ReturnExpression(theEnv,assertArgs);
return(NULL);
}
if (error)
{
ReturnExpression(theEnv,assertArgs);
return(NULL);
}
if (ExpressionContainsVariables(assertArgs,FALSE))
{
LocalVariableErrorMessage(theEnv,"the assert-string function");
SetEvaluationError(theEnv,TRUE);
ReturnExpression(theEnv,assertArgs);
return(NULL);
}
/*=======================================================*/
/* Count the number of fields needed for the fact and */
/* create a fact data structure of the appropriate size. */
/*=======================================================*/
for (tempPtr = assertArgs->nextArg; tempPtr != NULL; tempPtr = tempPtr->nextArg)
{ numberOfFields++; }
factPtr = (struct fact *) CreateFactBySize(theEnv,numberOfFields);
factPtr->whichDeftemplate = (struct deftemplate *) assertArgs->value;
/*=============================================*/
/* Copy the fields to the fact data structure. */
/*=============================================*/
EnvIncrementClearReadyLocks(theEnv);
ExpressionInstall(theEnv,assertArgs); /* DR0836 */
whichField = 0;
for (tempPtr = assertArgs->nextArg; tempPtr != NULL; tempPtr = tempPtr->nextArg)
{
EvaluateExpression(theEnv,tempPtr,&theResult);
factPtr->theProposition.theFields[whichField].type = theResult.type;
factPtr->theProposition.theFields[whichField].value = theResult.value;
whichField++;
}
ExpressionDeinstall(theEnv,assertArgs); /* DR0836 */
ReturnExpression(theEnv,assertArgs);
EnvDecrementClearReadyLocks(theEnv);
/*==================*/
/* Return the fact. */
/*==================*/
return(factPtr);
}
#if RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE
/*********************************************************/
/* NoSuchTemplateError: Prints out an error message */
/* in a BLOAD_ONLY, RUN_TIME or bload active environment */
/* when an implied deftemplate cannot be created for */
/* an assert */
/*********************************************************/
static void NoSuchTemplateError(
void *theEnv,
const char *templateName)
{
PrintErrorID(theEnv,"FACTRHS",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"Template ");
EnvPrintRouter(theEnv,WERROR,templateName);
EnvPrintRouter(theEnv,WERROR," does not exist for assert.\n");
}
#endif /* RUN_TIME || BLOAD_ONLY || BLOAD || BLOAD_AND_BSAVE */
#endif /* DEFTEMPLATE_CONSTRUCT */
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSFunctionBuilder.h
|
#ifndef _clips_function_builder_h
#define _clips_function_builder_h
#include "ExpertSystem/CLIPSConstantBuilder.h"
using namespace llvm;
class CLIPSFunctionBuilder : public CLIPSGlobalValueBuilder {
public:
CLIPSFunctionBuilder(std::string nm, FunctionNamer& namer);
void setCallingConvention(CallingConv::ID id);
//void setAttributes(const AttributeSet& attr);
void addFields(Function* fn, KnowledgeConstructor* kc);
void build(Function* fn, KnowledgeConstructor* kc);
};
extern "C" void RegisterLLVMFunctionManipulationFunctions(void* theEnv);
#endif
|
DrItanium/durandal
|
include/indirect/IndirectPassGenerator.h
|
#ifndef _indirect_pass_generator_h
#define _indirect_pass_generator_h
#include "llvm/Pass.h"
#include "indirect/IndirectPassHeader.h"
#include "indirect/IndirectPasses.h"
namespace indirect {
class IndirectPassGeneratorBase {
public:
virtual llvm::Pass* createPass(IndirectPassHeader* header) = 0;
};
template<typename MP, typename FP, typename BBP, typename LP, typename RP,
typename MFP, typename CGSCCP>
class IndirectPassGeneratorTemplate : public IndirectPassGeneratorBase {
public:
IndirectPassGeneratorTemplate() { }
IndirectCallGraphSCCPass* generateBaseCallGraphSCCPass(char& id) {
return new CGSCCP(id);
}
IndirectRegionPass* generateBaseRegionPass(char& id) {
return new RP(id);
}
IndirectMachineFunctionPass* generateBaseMachineFunctionPass(char& id) {
return new MFP(id);
}
IndirectLoopPass* generateBaseLoopPass(char& id) {
return new LP(id);
}
IndirectBasicBlockPass* generateBaseBasicBlockPass(char& id) {
return new BBP(id);
}
IndirectFunctionPass* generateBaseFunctionPass(char& id) {
return new FP(id);
}
IndirectModulePass* generateBaseModulePass(char& id) {
return new MP(id);
}
using indirect::IndirectPassGeneratorBase::createPass;
virtual llvm::Pass* createPass(IndirectPassHeader* header) {
/*
* the first thing to do is to determine what kind of a pass this is
* supposed to be.
*/
char& id = *(header->getID());
switch(header->getPassType()) {
case IndirectPassHeader::Module:
{
IndirectModulePass* pass = generateBaseModulePass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::Function:
{
IndirectFunctionPass* pass = generateBaseFunctionPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::BasicBlock:
{
IndirectBasicBlockPass* pass =
generateBaseBasicBlockPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::Loop:
{
IndirectLoopPass* pass = generateBaseLoopPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::Region:
{
IndirectRegionPass* pass = generateBaseRegionPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::MachineFunction:
{
IndirectMachineFunctionPass* pass =
generateBaseMachineFunctionPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
case IndirectPassHeader::CallGraphSCC:
{
IndirectCallGraphSCCPass* pass =
generateBaseCallGraphSCCPass(id);
pass->setIndirectPassHeader(header);
return pass;
}
default:
return 0;
}
}
};
}
#endif
|
DrItanium/durandal
|
lib/electron/genrccom.c
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/22/14 */
/* */
/* */
/*******************************************************/
/*************************************************************/
/* Purpose: Generic Functions Interface Routines */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */
/* */
/* Corrected compilation errors for files */
/* generated by constructs-to-c. DR0861 */
/* */
/* Changed name of variable log to logName */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* 6.24: Removed IMPERATIVE_METHODS compilation flag. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* Corrected code to remove run-time program */
/* compiler warning. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Changed integer type/precision. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Fixed linkage issue when DEBUGGING_FUNCTIONS */
/* is set to 0 and PROFILING_FUNCTIONS is set to */
/* 1. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if DEFGENERIC_CONSTRUCT
#include <string.h>
#if DEFRULE_CONSTRUCT
#include "network.h"
#endif
#if BLOAD || BLOAD_AND_BSAVE
#include "bload.h"
#endif
#if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE
#include "genrcbin.h"
#endif
#if CONSTRUCT_COMPILER
#include "genrccmp.h"
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
#include "constrct.h"
#include "genrcpsr.h"
#endif
#if OBJECT_SYSTEM
#include "classcom.h"
#include "inscom.h"
#endif
#if DEBUGGING_FUNCTIONS
#include "watch.h"
#endif
#include "argacces.h"
#include "cstrcpsr.h"
#include "envrnmnt.h"
#include "extnfunc.h"
#include "genrcexe.h"
#include "memalloc.h"
#include "modulpsr.h"
#include "multifld.h"
#include "router.h"
#define _GENRCCOM_SOURCE_
#include "genrccom.h"
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
static void PrintGenericCall(void *,const char *,void *);
static intBool EvaluateGenericCall(void *,void *,DATA_OBJECT *);
static void DecrementGenericBusyCount(void *,void *);
static void IncrementGenericBusyCount(void *,void *);
static void DeallocateDefgenericData(void *);
#if ! RUN_TIME
static void DestroyDefgenericAction(void *,struct constructHeader *,void *);
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
static void SaveDefgenerics(void *,void *,const char *);
static void SaveDefmethods(void *,void *,const char *);
static void SaveDefmethodsForDefgeneric(void *,struct constructHeader *,void *);
static void RemoveDefgenericMethod(void *,DEFGENERIC *,long);
#endif
#if DEBUGGING_FUNCTIONS
static long ListMethodsForGeneric(void *,const char *,DEFGENERIC *);
static unsigned DefgenericWatchAccess(void *,int,unsigned,EXPRESSION *);
static unsigned DefgenericWatchPrint(void *,const char *,int,EXPRESSION *);
static unsigned DefmethodWatchAccess(void *,int,unsigned,EXPRESSION *);
static unsigned DefmethodWatchPrint(void *,const char *,int,EXPRESSION *);
static unsigned DefmethodWatchSupport(void *,const char *,const char *,unsigned,
void (*)(void *,const char *,void *,long),
void (*)(void *,unsigned,void *,long),
EXPRESSION *);
static void PrintMethodWatchFlag(void *,const char *,void *,long);
#endif
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/***********************************************************
NAME : SetupGenericFunctions
DESCRIPTION : Initializes all generic function
data structures, constructs and functions
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Generic function H/L functions set up
NOTES : None
***********************************************************/
globle void SetupGenericFunctions(
void *theEnv)
{
ENTITY_RECORD genericEntityRecord =
{ "GCALL", GCALL,0,0,1,
PrintGenericCall,PrintGenericCall,
NULL,EvaluateGenericCall,NULL,
DecrementGenericBusyCount,IncrementGenericBusyCount,
NULL,NULL,NULL,NULL,NULL };
AllocateEnvironmentData(theEnv,DEFGENERIC_DATA,sizeof(struct defgenericData),DeallocateDefgenericData);
memcpy(&DefgenericData(theEnv)->GenericEntityRecord,&genericEntityRecord,sizeof(struct entityRecord));
InstallPrimitive(theEnv,&DefgenericData(theEnv)->GenericEntityRecord,GCALL);
DefgenericData(theEnv)->DefgenericModuleIndex =
RegisterModuleItem(theEnv,"defgeneric",
#if (! RUN_TIME)
AllocateDefgenericModule,FreeDefgenericModule,
#else
NULL,NULL,
#endif
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
BloadDefgenericModuleReference,
#else
NULL,
#endif
#if CONSTRUCT_COMPILER && (! RUN_TIME)
DefgenericCModuleReference,
#else
NULL,
#endif
EnvFindDefgeneric);
DefgenericData(theEnv)->DefgenericConstruct = AddConstruct(theEnv,"defgeneric","defgenerics",
#if (! BLOAD_ONLY) && (! RUN_TIME)
ParseDefgeneric,
#else
NULL,
#endif
EnvFindDefgeneric,
GetConstructNamePointer,GetConstructPPForm,
GetConstructModuleItem,EnvGetNextDefgeneric,
SetNextConstruct,EnvIsDefgenericDeletable,
EnvUndefgeneric,
#if (! BLOAD_ONLY) && (! RUN_TIME)
RemoveDefgeneric
#else
NULL
#endif
);
#if ! RUN_TIME
AddClearReadyFunction(theEnv,"defgeneric",ClearDefgenericsReady,0);
#if BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE
SetupGenericsBload(theEnv);
#endif
#if CONSTRUCT_COMPILER
SetupGenericsCompiler(theEnv);
#endif
#if ! BLOAD_ONLY
#if DEFMODULE_CONSTRUCT
AddPortConstructItem(theEnv,"defgeneric",SYMBOL);
#endif
AddConstruct(theEnv,"defmethod","defmethods",ParseDefmethod,
NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
/* ================================================================
Make sure defmethods are cleared last, for other constructs may
be using them and need to be cleared first
Need to be cleared in two stages so that mutually dependent
constructs (like classes) can be cleared
================================================================ */
AddSaveFunction(theEnv,"defgeneric",SaveDefgenerics,1000);
AddSaveFunction(theEnv,"defmethod",SaveDefmethods,-1000);
EnvDefineFunction2(theEnv,"undefgeneric",'v',PTIEF UndefgenericCommand,"UndefgenericCommand","11w");
EnvDefineFunction2(theEnv,"undefmethod",'v',PTIEF UndefmethodCommand,"UndefmethodCommand","22*wg");
#endif
EnvDefineFunction2(theEnv,"call-next-method",'u',PTIEF CallNextMethod,"CallNextMethod","00");
FuncSeqOvlFlags(theEnv,"call-next-method",TRUE,FALSE);
EnvDefineFunction2(theEnv,"call-specific-method",'u',PTIEF CallSpecificMethod,
"CallSpecificMethod","2**wi");
FuncSeqOvlFlags(theEnv,"call-specific-method",TRUE,FALSE);
EnvDefineFunction2(theEnv,"override-next-method",'u',PTIEF OverrideNextMethod,
"OverrideNextMethod",NULL);
FuncSeqOvlFlags(theEnv,"override-next-method",TRUE,FALSE);
EnvDefineFunction2(theEnv,"next-methodp",'b',PTIEF NextMethodP,"NextMethodP","00");
FuncSeqOvlFlags(theEnv,"next-methodp",TRUE,FALSE);
EnvDefineFunction2(theEnv,"(gnrc-current-arg)",'u',PTIEF GetGenericCurrentArgument,
"GetGenericCurrentArgument",NULL);
#if DEBUGGING_FUNCTIONS
EnvDefineFunction2(theEnv,"ppdefgeneric",'v',PTIEF PPDefgenericCommand,"PPDefgenericCommand","11w");
EnvDefineFunction2(theEnv,"list-defgenerics",'v',PTIEF ListDefgenericsCommand,"ListDefgenericsCommand","01");
EnvDefineFunction2(theEnv,"ppdefmethod",'v',PTIEF PPDefmethodCommand,"PPDefmethodCommand","22*wi");
EnvDefineFunction2(theEnv,"list-defmethods",'v',PTIEF ListDefmethodsCommand,"ListDefmethodsCommand","01w");
EnvDefineFunction2(theEnv,"preview-generic",'v',PTIEF PreviewGeneric,"PreviewGeneric","1**w");
#endif
EnvDefineFunction2(theEnv,"get-defgeneric-list",'m',PTIEF GetDefgenericListFunction,
"GetDefgenericListFunction","01");
EnvDefineFunction2(theEnv,"get-defmethod-list",'m',PTIEF GetDefmethodListCommand,
"GetDefmethodListCommand","01w");
EnvDefineFunction2(theEnv,"get-method-restrictions",'m',PTIEF GetMethodRestrictionsCommand,
"GetMethodRestrictionsCommand","22iw");
EnvDefineFunction2(theEnv,"defgeneric-module",'w',PTIEF GetDefgenericModuleCommand,
"GetDefgenericModuleCommand","11w");
#if OBJECT_SYSTEM
EnvDefineFunction2(theEnv,"type",'u',PTIEF ClassCommand,"ClassCommand","11u");
#else
EnvDefineFunction2(theEnv,"type",'u',PTIEF TypeCommand,"TypeCommand","11u");
#endif
#endif
#if DEBUGGING_FUNCTIONS
AddWatchItem(theEnv,"generic-functions",0,&DefgenericData(theEnv)->WatchGenerics,34,
DefgenericWatchAccess,DefgenericWatchPrint);
AddWatchItem(theEnv,"methods",0,&DefgenericData(theEnv)->WatchMethods,33,
DefmethodWatchAccess,DefmethodWatchPrint);
#endif
}
/*****************************************************/
/* DeallocateDefgenericData: Deallocates environment */
/* data for the defgeneric construct. */
/*****************************************************/
static void DeallocateDefgenericData(
void *theEnv)
{
#if ! RUN_TIME
struct defgenericModule *theModuleItem;
void *theModule;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv)) return;
#endif
DoForAllConstructs(theEnv,DestroyDefgenericAction,DefgenericData(theEnv)->DefgenericModuleIndex,FALSE,NULL);
for (theModule = EnvGetNextDefmodule(theEnv,NULL);
theModule != NULL;
theModule = EnvGetNextDefmodule(theEnv,theModule))
{
theModuleItem = (struct defgenericModule *)
GetModuleItem(theEnv,(struct defmodule *) theModule,
DefgenericData(theEnv)->DefgenericModuleIndex);
rtn_struct(theEnv,defgenericModule,theModuleItem);
}
#else
#endif
}
#if ! RUN_TIME
/****************************************************/
/* DestroyDefgenericAction: Action used to remove */
/* defgenerics as a result of DestroyEnvironment. */
/****************************************************/
static void DestroyDefgenericAction(
void *theEnv,
struct constructHeader *theConstruct,
void *buffer)
{
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct defgeneric *theDefgeneric = (struct defgeneric *) theConstruct;
long i;
if (theDefgeneric == NULL) return;
for (i = 0 ; i < theDefgeneric->mcnt ; i++)
{ DestroyMethodInfo(theEnv,theDefgeneric,&theDefgeneric->methods[i]); }
if (theDefgeneric->mcnt != 0)
rm(theEnv,(void *) theDefgeneric->methods,(sizeof(DEFMETHOD) * theDefgeneric->mcnt));
DestroyConstructHeader(theEnv,&theDefgeneric->header);
rtn_struct(theEnv,defgeneric,theDefgeneric);
#else
#endif
}
#endif
/***************************************************
NAME : EnvFindDefgeneric
DESCRIPTION : Searches for a generic
INPUTS : The name of the generic
(possibly including a module name)
RETURNS : Pointer to the generic if
found, otherwise NULL
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle void *EnvFindDefgeneric(
void *theEnv,
const char *genericModuleAndName)
{
return(FindNamedConstruct(theEnv,genericModuleAndName,DefgenericData(theEnv)->DefgenericConstruct));
}
/***************************************************
NAME : LookupDefgenericByMdlOrScope
DESCRIPTION : Finds a defgeneric anywhere (if
module is specified) or in current
or imported modules
INPUTS : The defgeneric name
RETURNS : The defgeneric (NULL if not found)
SIDE EFFECTS : Error message printed on
ambiguous references
NOTES : None
***************************************************/
globle DEFGENERIC *LookupDefgenericByMdlOrScope(
void *theEnv,
const char *defgenericName)
{
return((DEFGENERIC *) LookupConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,defgenericName,TRUE));
}
/***************************************************
NAME : LookupDefgenericInScope
DESCRIPTION : Finds a defgeneric in current or
imported modules (module
specifier is not allowed)
INPUTS : The defgeneric name
RETURNS : The defgeneric (NULL if not found)
SIDE EFFECTS : Error message printed on
ambiguous references
NOTES : None
***************************************************/
globle DEFGENERIC *LookupDefgenericInScope(
void *theEnv,
const char *defgenericName)
{
return((DEFGENERIC *) LookupConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,defgenericName,FALSE));
}
/***********************************************************
NAME : EnvGetNextDefgeneric
DESCRIPTION : Finds first or next generic function
INPUTS : The address of the current generic function
RETURNS : The address of the next generic function
(NULL if none)
SIDE EFFECTS : None
NOTES : If ptr == NULL, the first generic function
is returned.
***********************************************************/
globle void *EnvGetNextDefgeneric(
void *theEnv,
void *ptr)
{
return((void *) GetNextConstructItem(theEnv,(struct constructHeader *) ptr,DefgenericData(theEnv)->DefgenericModuleIndex));
}
/***********************************************************
NAME : EnvGetNextDefmethod
DESCRIPTION : Find the next method for a generic function
INPUTS : 1) The generic function address
2) The index of the current method
RETURNS : The index of the next method
(0 if none)
SIDE EFFECTS : None
NOTES : If index == 0, the index of the first
method is returned
***********************************************************/
globle long EnvGetNextDefmethod(
void *theEnv,
void *ptr,
long theIndex)
{
DEFGENERIC *gfunc;
long mi;
gfunc = (DEFGENERIC *) ptr;
if (theIndex == 0)
{
if (gfunc->methods != NULL)
return(gfunc->methods[0].index);
return(0);
}
mi = FindMethodByIndex(gfunc,theIndex);
if ((mi+1) == gfunc->mcnt)
return(0);
return(gfunc->methods[mi+1].index);
}
/*****************************************************
NAME : GetDefmethodPointer
DESCRIPTION : Returns a pointer to a method
INPUTS : 1) Pointer to a defgeneric
2) Array index of method in generic's
method array (+1)
RETURNS : Pointer to the method.
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle DEFMETHOD *GetDefmethodPointer(
void *ptr,
long theIndex)
{
return(&((DEFGENERIC *) ptr)->methods[theIndex-1]);
}
/***************************************************
NAME : EnvIsDefgenericDeletable
DESCRIPTION : Determines if a generic function
can be deleted
INPUTS : Address of the generic function
RETURNS : TRUE if deletable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle int EnvIsDefgenericDeletable(
void *theEnv,
void *ptr)
{
if (! ConstructsDeletable(theEnv))
{ return FALSE; }
return ((((DEFGENERIC *) ptr)->busy == 0) ? TRUE : FALSE);
}
/***************************************************
NAME : EnvIsDefmethodDeletable
DESCRIPTION : Determines if a generic function
method can be deleted
INPUTS : 1) Address of the generic function
2) Index of the method
RETURNS : TRUE if deletable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle int EnvIsDefmethodDeletable(
void *theEnv,
void *ptr,
long theIndex)
{
if (! ConstructsDeletable(theEnv))
{ return FALSE; }
if (((DEFGENERIC *) ptr)->methods[FindMethodByIndex((DEFGENERIC *) ptr,theIndex)].system)
return(FALSE);
#if (! BLOAD_ONLY) && (! RUN_TIME)
return((MethodsExecuting((DEFGENERIC *) ptr) == FALSE) ? TRUE : FALSE);
#else
return FALSE;
#endif
}
/**********************************************************
NAME : UndefgenericCommand
DESCRIPTION : Deletes all methods for a generic function
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : methods deallocated
NOTES : H/L Syntax: (undefgeneric <name> | *)
**********************************************************/
globle void UndefgenericCommand(
void *theEnv)
{
UndefconstructCommand(theEnv,"undefgeneric",DefgenericData(theEnv)->DefgenericConstruct);
}
/****************************************************************
NAME : GetDefgenericModuleCommand
DESCRIPTION : Determines to which module a defgeneric belongs
INPUTS : None
RETURNS : The symbolic name of the module
SIDE EFFECTS : None
NOTES : H/L Syntax: (defgeneric-module <generic-name>)
****************************************************************/
globle void *GetDefgenericModuleCommand(
void *theEnv)
{
return(GetConstructModuleCommand(theEnv,"defgeneric-module",DefgenericData(theEnv)->DefgenericConstruct));
}
/**************************************************************
NAME : UndefmethodCommand
DESCRIPTION : Deletes one method for a generic function
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : methods deallocated
NOTES : H/L Syntax: (undefmethod <name> <index> | *)
**************************************************************/
globle void UndefmethodCommand(
void *theEnv)
{
DATA_OBJECT temp;
DEFGENERIC *gfunc;
long mi;
if (EnvArgTypeCheck(theEnv,"undefmethod",1,SYMBOL,&temp) == FALSE)
return;
gfunc = LookupDefgenericByMdlOrScope(theEnv,DOToString(temp));
if ((gfunc == NULL) ? (strcmp(DOToString(temp),"*") != 0) : FALSE)
{
PrintErrorID(theEnv,"GENRCCOM",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No such generic function ");
EnvPrintRouter(theEnv,WERROR,DOToString(temp));
EnvPrintRouter(theEnv,WERROR," in function undefmethod.\n");
return;
}
EnvRtnUnknown(theEnv,2,&temp);
if (temp.type == SYMBOL)
{
if (strcmp(DOToString(temp),"*") != 0)
{
PrintErrorID(theEnv,"GENRCCOM",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"Expected a valid method index in function undefmethod.\n");
return;
}
mi = 0;
}
else if (temp.type == INTEGER)
{
mi = (long) DOToLong(temp);
if (mi == 0)
{
PrintErrorID(theEnv,"GENRCCOM",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"Expected a valid method index in function undefmethod.\n");
return;
}
}
else
{
PrintErrorID(theEnv,"GENRCCOM",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"Expected a valid method index in function undefmethod.\n");
return;
}
EnvUndefmethod(theEnv,(void *) gfunc,mi);
}
/**************************************************************
NAME : EnvUndefgeneric
DESCRIPTION : Deletes all methods for a generic function
INPUTS : The generic-function address (NULL for all)
RETURNS : TRUE if generic successfully deleted,
FALSE otherwise
SIDE EFFECTS : methods deallocated
NOTES : None
**************************************************************/
globle intBool EnvUndefgeneric(
void *theEnv,
void *vptr)
{
#if RUN_TIME || BLOAD_ONLY
return(FALSE);
#else
DEFGENERIC *gfunc;
int success = TRUE;
gfunc = (DEFGENERIC *) vptr;
if (gfunc == NULL)
{
if (ClearDefmethods(theEnv) == FALSE)
success = FALSE;
if (ClearDefgenerics(theEnv) == FALSE)
success = FALSE;
return(success);
}
if (EnvIsDefgenericDeletable(theEnv,vptr) == FALSE)
return(FALSE);
RemoveConstructFromModule(theEnv,(struct constructHeader *) vptr);
RemoveDefgeneric(theEnv,gfunc);
return(TRUE);
#endif
}
/**************************************************************
NAME : EnvUndefmethod
DESCRIPTION : Deletes one method for a generic function
INPUTS : 1) Address of generic function (can be NULL)
2) Method index (0 for all)
RETURNS : TRUE if method deleted successfully,
FALSE otherwise
SIDE EFFECTS : methods deallocated
NOTES : None
**************************************************************/
globle intBool EnvUndefmethod(
void *theEnv,
void *vptr,
long mi)
{
DEFGENERIC *gfunc;
#if RUN_TIME || BLOAD_ONLY
gfunc = (DEFGENERIC *) vptr;
PrintErrorID(theEnv,"PRNTUTIL",4,FALSE);
EnvPrintRouter(theEnv,WERROR,"Unable to delete method ");
if (gfunc != NULL)
{
PrintGenericName(theEnv,WERROR,gfunc);
EnvPrintRouter(theEnv,WERROR," #");
PrintLongInteger(theEnv,WERROR,(long long) mi);
}
else
EnvPrintRouter(theEnv,WERROR,"*");
EnvPrintRouter(theEnv,WERROR,".\n");
return(FALSE);
#else
long nmi;
gfunc = (DEFGENERIC *) vptr;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv) == TRUE)
{
PrintErrorID(theEnv,"PRNTUTIL",4,FALSE);
EnvPrintRouter(theEnv,WERROR,"Unable to delete method ");
if (gfunc != NULL)
{
EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WERROR," #");
PrintLongInteger(theEnv,WERROR,(long long) mi);
}
else
EnvPrintRouter(theEnv,WERROR,"*");
EnvPrintRouter(theEnv,WERROR,".\n");
return(FALSE);
}
#endif
if (gfunc == NULL)
{
if (mi != 0)
{
PrintErrorID(theEnv,"GENRCCOM",3,FALSE);
EnvPrintRouter(theEnv,WERROR,"Incomplete method specification for deletion.\n");
return(FALSE);
}
return(ClearDefmethods(theEnv));
}
if (MethodsExecuting(gfunc))
{
MethodAlterError(theEnv,gfunc);
return(FALSE);
}
if (mi == 0)
RemoveAllExplicitMethods(theEnv,gfunc);
else
{
nmi = CheckMethodExists(theEnv,"undefmethod",gfunc,mi);
if (nmi == -1)
return(FALSE);
RemoveDefgenericMethod(theEnv,gfunc,nmi);
}
return(TRUE);
#endif
}
#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS
/*****************************************************
NAME : EnvGetDefmethodDescription
DESCRIPTION : Prints a synopsis of method parameter
restrictions into caller's buffer
INPUTS : 1) Caller's buffer
2) Buffer size (not including space
for terminating '\0')
3) Address of generic function
4) Index of method
RETURNS : Nothing useful
SIDE EFFECTS : Caller's buffer written
NOTES : Terminating '\n' not written
*****************************************************/
globle void EnvGetDefmethodDescription(
void *theEnv,
char *buf,
size_t buflen,
void *ptr,
long theIndex)
{
DEFGENERIC *gfunc;
long mi;
gfunc = (DEFGENERIC *) ptr;
mi = FindMethodByIndex(gfunc,theIndex);
PrintMethod(theEnv,buf,buflen,&gfunc->methods[mi]);
}
#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */
#if DEBUGGING_FUNCTIONS
/*********************************************************
NAME : EnvGetDefgenericWatch
DESCRIPTION : Determines if trace messages are
gnerated when executing generic function
INPUTS : A pointer to the generic
RETURNS : TRUE if a trace is active,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
*********************************************************/
globle unsigned EnvGetDefgenericWatch(
void *theEnv,
void *theGeneric)
{
return(((DEFGENERIC *) theGeneric)->trace);
}
/*********************************************************
NAME : EnvSetDefgenericWatch
DESCRIPTION : Sets the trace to ON/OFF for the
generic function
INPUTS : 1) TRUE to set the trace on,
FALSE to set it off
2) A pointer to the generic
RETURNS : Nothing useful
SIDE EFFECTS : Watch flag for the generic set
NOTES : None
*********************************************************/
globle void EnvSetDefgenericWatch(
void *theEnv,
unsigned newState,
void *theGeneric)
{
((DEFGENERIC *) theGeneric)->trace = newState;
}
/*********************************************************
NAME : EnvGetDefmethodWatch
DESCRIPTION : Determines if trace messages for calls
to this method will be generated or not
INPUTS : 1) A pointer to the generic
2) The index of the method
RETURNS : TRUE if a trace is active,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
*********************************************************/
globle unsigned EnvGetDefmethodWatch(
void *theEnv,
void *theGeneric,
long theIndex)
{
DEFGENERIC *gfunc;
long mi;
gfunc = (DEFGENERIC *) theGeneric;
mi = FindMethodByIndex(gfunc,theIndex);
return(gfunc->methods[mi].trace);
}
/*********************************************************
NAME : EnvSetDefmethodWatch
DESCRIPTION : Sets the trace to ON/OFF for the
calling of the method
INPUTS : 1) TRUE to set the trace on,
FALSE to set it off
2) A pointer to the generic
3) The index of the method
RETURNS : Nothing useful
SIDE EFFECTS : Watch flag for the method set
NOTES : None
*********************************************************/
globle void EnvSetDefmethodWatch(
void *theEnv,
unsigned newState,
void *theGeneric,
long theIndex)
{
DEFGENERIC *gfunc;
long mi;
gfunc = (DEFGENERIC *) theGeneric;
mi = FindMethodByIndex(gfunc,theIndex);
gfunc->methods[mi].trace = newState;
}
/********************************************************
NAME : PPDefgenericCommand
DESCRIPTION : Displays the pretty-print form of
a generic function header
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (ppdefgeneric <name>)
********************************************************/
globle void PPDefgenericCommand(
void *theEnv)
{
PPConstructCommand(theEnv,"ppdefgeneric",DefgenericData(theEnv)->DefgenericConstruct);
}
/**********************************************************
NAME : PPDefmethodCommand
DESCRIPTION : Displays the pretty-print form of
a method
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (ppdefmethod <name> <index>)
**********************************************************/
globle void PPDefmethodCommand(
void *theEnv)
{
DATA_OBJECT temp;
const char *gname;
DEFGENERIC *gfunc;
int gi;
if (EnvArgTypeCheck(theEnv,"ppdefmethod",1,SYMBOL,&temp) == FALSE)
return;
gname = DOToString(temp);
if (EnvArgTypeCheck(theEnv,"ppdefmethod",2,INTEGER,&temp) == FALSE)
return;
gfunc = CheckGenericExists(theEnv,"ppdefmethod",gname);
if (gfunc == NULL)
return;
gi = CheckMethodExists(theEnv,"ppdefmethod",gfunc,(long) DOToLong(temp));
if (gi == -1)
return;
if (gfunc->methods[gi].ppForm != NULL)
PrintInChunks(theEnv,WDISPLAY,gfunc->methods[gi].ppForm);
}
/******************************************************
NAME : ListDefmethodsCommand
DESCRIPTION : Lists a brief description of methods
for a particular generic function
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (list-defmethods <name>)
******************************************************/
globle void ListDefmethodsCommand(
void *theEnv)
{
DATA_OBJECT temp;
DEFGENERIC *gfunc;
if (EnvRtnArgCount(theEnv) == 0)
EnvListDefmethods(theEnv,WDISPLAY,NULL);
else
{
if (EnvArgTypeCheck(theEnv,"list-defmethods",1,SYMBOL,&temp) == FALSE)
return;
gfunc = CheckGenericExists(theEnv,"list-defmethods",DOToString(temp));
if (gfunc != NULL)
EnvListDefmethods(theEnv,WDISPLAY,(void *) gfunc);
}
}
/***************************************************************
NAME : EnvGetDefmethodPPForm
DESCRIPTION : Getsa generic function method pretty print form
INPUTS : 1) Address of the generic function
2) Index of the method
RETURNS : Method ppform
SIDE EFFECTS : None
NOTES : None
***************************************************************/
globle const char *EnvGetDefmethodPPForm(
void *theEnv,
void *ptr,
long theIndex)
{
DEFGENERIC *gfunc;
int mi;
gfunc = (DEFGENERIC *) ptr;
mi = FindMethodByIndex(gfunc,theIndex);
return(gfunc->methods[mi].ppForm);
}
/***************************************************
NAME : ListDefgenericsCommand
DESCRIPTION : Displays all defgeneric names
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Defgeneric names printed
NOTES : H/L Interface
***************************************************/
globle void ListDefgenericsCommand(
void *theEnv)
{
ListConstructCommand(theEnv,"list-defgenerics",DefgenericData(theEnv)->DefgenericConstruct);
}
/***************************************************
NAME : EnvListDefgenerics
DESCRIPTION : Displays all defgeneric names
INPUTS : 1) The logical name of the output
2) The module
RETURNS : Nothing useful
SIDE EFFECTS : Defgeneric names printed
NOTES : C Interface
***************************************************/
globle void EnvListDefgenerics(
void *theEnv,
const char *logicalName,
struct defmodule *theModule)
{
ListConstruct(theEnv,DefgenericData(theEnv)->DefgenericConstruct,logicalName,theModule);
}
/******************************************************
NAME : EnvListDefmethods
DESCRIPTION : Lists a brief description of methods
for a particular generic function
INPUTS : 1) The logical name of the output
2) Generic function to list methods for
(NULL means list all methods)
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
******************************************************/
globle void EnvListDefmethods(
void *theEnv,
const char *logicalName,
void *vptr)
{
DEFGENERIC *gfunc;
long count;
if (vptr != NULL)
count = ListMethodsForGeneric(theEnv,logicalName,(DEFGENERIC *) vptr);
else
{
count = 0L;
for (gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,NULL) ;
gfunc != NULL ;
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc))
{
count += ListMethodsForGeneric(theEnv,logicalName,gfunc);
if (EnvGetNextDefgeneric(theEnv,(void *) gfunc) != NULL)
EnvPrintRouter(theEnv,logicalName,"\n");
}
}
PrintTally(theEnv,logicalName,count,"method","methods");
}
#endif /* DEBUGGING_FUNCTIONS */
/***************************************************************
NAME : GetDefgenericListFunction
DESCRIPTION : Groups all defgeneric names into
a multifield list
INPUTS : A data object buffer to hold
the multifield result
RETURNS : Nothing useful
SIDE EFFECTS : Multifield allocated and filled
NOTES : H/L Syntax: (get-defgeneric-list [<module>])
***************************************************************/
globle void GetDefgenericListFunction(
void *theEnv,
DATA_OBJECT*returnValue)
{
GetConstructListFunction(theEnv,"get-defgeneric-list",returnValue,DefgenericData(theEnv)->DefgenericConstruct);
}
/***************************************************************
NAME : EnvGetDefgenericList
DESCRIPTION : Groups all defgeneric names into
a multifield list
INPUTS : 1) A data object buffer to hold
the multifield result
2) The module from which to obtain defgenerics
RETURNS : Nothing useful
SIDE EFFECTS : Multifield allocated and filled
NOTES : External C access
***************************************************************/
globle void EnvGetDefgenericList(
void *theEnv,
DATA_OBJECT *returnValue,
struct defmodule *theModule)
{
GetConstructList(theEnv,returnValue,DefgenericData(theEnv)->DefgenericConstruct,theModule);
}
/***********************************************************
NAME : GetDefmethodListCommand
DESCRIPTION : Groups indices of all methdos for a generic
function into a multifield variable
(NULL means get methods for all generics)
INPUTS : A data object buffer
RETURNS : Nothing useful
SIDE EFFECTS : Multifield set to list of method indices
NOTES : None
***********************************************************/
globle void GetDefmethodListCommand(
void *theEnv,
DATA_OBJECT_PTR returnValue)
{
DATA_OBJECT temp;
DEFGENERIC *gfunc;
if (EnvRtnArgCount(theEnv) == 0)
EnvGetDefmethodList(theEnv,NULL,returnValue);
else
{
if (EnvArgTypeCheck(theEnv,"get-defmethod-list",1,SYMBOL,&temp) == FALSE)
{
EnvSetMultifieldErrorValue(theEnv,returnValue);
return;
}
gfunc = CheckGenericExists(theEnv,"get-defmethod-list",DOToString(temp));
if (gfunc != NULL)
EnvGetDefmethodList(theEnv,(void *) gfunc,returnValue);
else
EnvSetMultifieldErrorValue(theEnv,returnValue);
}
}
/***********************************************************
NAME : EnvGetDefmethodList
DESCRIPTION : Groups indices of all methdos for a generic
function into a multifield variable
(NULL means get methods for all generics)
INPUTS : 1) A pointer to a generic function
2) A data object buffer
RETURNS : Nothing useful
SIDE EFFECTS : Multifield set to list of method indices
NOTES : None
***********************************************************/
globle void EnvGetDefmethodList(
void *theEnv,
void *vgfunc,
DATA_OBJECT_PTR returnValue)
{
DEFGENERIC *gfunc,*svg,*svnxt;
long i,j;
unsigned long count;
MULTIFIELD_PTR theList;
if (vgfunc != NULL)
{
gfunc = (DEFGENERIC *) vgfunc;
svnxt = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,vgfunc);
SetNextDefgeneric(vgfunc,NULL);
}
else
{
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,NULL);
svnxt = (gfunc != NULL) ? (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc) : NULL;
}
count = 0;
for (svg = gfunc ;
gfunc != NULL ;
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc))
count += (unsigned long) gfunc->mcnt;
count *= 2;
SetpType(returnValue,MULTIFIELD);
SetpDOBegin(returnValue,1);
SetpDOEnd(returnValue,count);
theList = (MULTIFIELD_PTR) EnvCreateMultifield(theEnv,count);
SetpValue(returnValue,theList);
for (gfunc = svg , i = 1 ;
gfunc != NULL ;
gfunc = (DEFGENERIC *) EnvGetNextDefgeneric(theEnv,(void *) gfunc))
{
for (j = 0 ; j < gfunc->mcnt ; j++)
{
SetMFType(theList,i,SYMBOL);
SetMFValue(theList,i++,GetDefgenericNamePointer((void *) gfunc));
SetMFType(theList,i,INTEGER);
SetMFValue(theList,i++,EnvAddLong(theEnv,(long long) gfunc->methods[j].index));
}
}
if (svg != NULL)
SetNextDefgeneric((void *) svg,(void *) svnxt);
}
/***********************************************************************************
NAME : GetMethodRestrictionsCommand
DESCRIPTION : Stores restrictions of a method in multifield
INPUTS : A data object buffer to hold a multifield
RETURNS : Nothing useful
SIDE EFFECTS : Multifield created (length zero on errors)
NOTES : Syntax: (get-method-restrictions <generic-function> <method-index>)
***********************************************************************************/
globle void GetMethodRestrictionsCommand(
void *theEnv,
DATA_OBJECT *result)
{
DATA_OBJECT temp;
DEFGENERIC *gfunc;
if (EnvArgTypeCheck(theEnv,"get-method-restrictions",1,SYMBOL,&temp) == FALSE)
{
EnvSetMultifieldErrorValue(theEnv,result);
return;
}
gfunc = CheckGenericExists(theEnv,"get-method-restrictions",DOToString(temp));
if (gfunc == NULL)
{
EnvSetMultifieldErrorValue(theEnv,result);
return;
}
if (EnvArgTypeCheck(theEnv,"get-method-restrictions",2,INTEGER,&temp) == FALSE)
{
EnvSetMultifieldErrorValue(theEnv,result);
return;
}
if (CheckMethodExists(theEnv,"get-method-restrictions",gfunc,(long) DOToLong(temp)) == -1)
{
EnvSetMultifieldErrorValue(theEnv,result);
return;
}
EnvGetMethodRestrictions(theEnv,(void *) gfunc,(unsigned) DOToLong(temp),result);
}
/***********************************************************************
NAME : EnvGetMethodRestrictions
DESCRIPTION : Stores restrictions of a method in multifield
INPUTS : 1) Pointer to the generic function
2) The method index
3) A data object buffer to hold a multifield
RETURNS : Nothing useful
SIDE EFFECTS : Multifield created (length zero on errors)
NOTES : The restrictions are stored in the multifield
in the following format:
<min-number-of-arguments>
<max-number-of-arguments> (-1 if wildcard allowed)
<restriction-count>
<index of 1st restriction>
.
.
<index of nth restriction>
<restriction 1>
<query TRUE/FALSE>
<number-of-classes>
<class 1>
.
.
<class n>
.
.
.
<restriction n>
Thus, for the method
(defmethod foo ((?a NUMBER SYMBOL) (?b (= 1 1)) $?c))
(get-method-restrictions foo 1) would yield
(2 -1 3 7 11 13 FALSE 2 NUMBER SYMBOL TRUE 0 FALSE 0)
***********************************************************************/
globle void EnvGetMethodRestrictions(
void *theEnv,
void *vgfunc,
long mi,
DATA_OBJECT *result)
{
short i,j;
register DEFMETHOD *meth;
register RESTRICTION *rptr;
long count;
int roffset,rstrctIndex;
MULTIFIELD_PTR theList;
meth = ((DEFGENERIC *) vgfunc)->methods + FindMethodByIndex((DEFGENERIC *) vgfunc,mi);
count = 3;
for (i = 0 ; i < meth->restrictionCount ; i++)
count += meth->restrictions[i].tcnt + 3;
theList = (MULTIFIELD_PTR) EnvCreateMultifield(theEnv,count);
SetpType(result,MULTIFIELD);
SetpValue(result,theList);
SetpDOBegin(result,1);
SetpDOEnd(result,count);
SetMFType(theList,1,INTEGER);
SetMFValue(theList,1,EnvAddLong(theEnv,(long long) meth->minRestrictions));
SetMFType(theList,2,INTEGER);
SetMFValue(theList,2,EnvAddLong(theEnv,(long long) meth->maxRestrictions));
SetMFType(theList,3,INTEGER);
SetMFValue(theList,3,EnvAddLong(theEnv,(long long) meth->restrictionCount));
roffset = 3 + meth->restrictionCount + 1;
rstrctIndex = 4;
for (i = 0 ; i < meth->restrictionCount ; i++)
{
rptr = meth->restrictions + i;
SetMFType(theList,rstrctIndex,INTEGER);
SetMFValue(theList,rstrctIndex++,EnvAddLong(theEnv,(long long) roffset));
SetMFType(theList,roffset,SYMBOL);
SetMFValue(theList,roffset++,(rptr->query != NULL) ? EnvTrueSymbol(theEnv) : EnvFalseSymbol(theEnv));
SetMFType(theList,roffset,INTEGER);
SetMFValue(theList,roffset++,EnvAddLong(theEnv,(long long) rptr->tcnt));
for (j = 0 ; j < rptr->tcnt ; j++)
{
SetMFType(theList,roffset,SYMBOL);
#if OBJECT_SYSTEM
SetMFValue(theList,roffset++,EnvAddSymbol(theEnv,EnvGetDefclassName(theEnv,rptr->types[j])));
#else
SetMFValue(theList,roffset++,EnvAddSymbol(theEnv,TypeName(theEnv,ValueToInteger(rptr->types[j]))));
#endif
}
}
}
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/***************************************************
NAME : PrintGenericCall
DESCRIPTION : PrintExpression() support function
for generic function calls
INPUTS : 1) The output logical name
2) The generic function
RETURNS : Nothing useful
SIDE EFFECTS : Call expression printed
NOTES : None
***************************************************/
static void PrintGenericCall(
void *theEnv,
const char *logName,
void *value)
{
#if DEVELOPER
EnvPrintRouter(theEnv,logName,"(");
EnvPrintRouter(theEnv,logName,EnvGetDefgenericName(theEnv,value));
if (GetFirstArgument() != NULL)
{
EnvPrintRouter(theEnv,logName," ");
PrintExpression(theEnv,logName,GetFirstArgument());
}
EnvPrintRouter(theEnv,logName,")");
#else
#endif
}
/*******************************************************
NAME : EvaluateGenericCall
DESCRIPTION : Primitive support function for
calling a generic function
INPUTS : 1) The generic function
2) A data object buffer to hold
the evaluation result
RETURNS : FALSE if the generic function
returns the symbol FALSE,
TRUE otherwise
SIDE EFFECTS : Data obejct buffer set and any
side-effects of calling the generic
NOTES : None
*******************************************************/
static intBool EvaluateGenericCall(
void *theEnv,
void *value,
DATA_OBJECT *result)
{
GenericDispatch(theEnv,(DEFGENERIC *) value,NULL,NULL,GetFirstArgument(),result);
if ((GetpType(result) == SYMBOL) &&
(GetpValue(result) == EnvFalseSymbol(theEnv)))
return(FALSE);
return(TRUE);
}
/***************************************************
NAME : DecrementGenericBusyCount
DESCRIPTION : Lowers the busy count of a
generic function construct
INPUTS : The generic function
RETURNS : Nothing useful
SIDE EFFECTS : Busy count decremented if a clear
is not in progress (see comment)
NOTES : None
***************************************************/
static void DecrementGenericBusyCount(
void *theEnv,
void *value)
{
/* ==============================================
The generics to which expressions in other
constructs may refer may already have been
deleted - thus, it is important not to modify
the busy flag during a clear.
============================================== */
if (! ConstructData(theEnv)->ClearInProgress)
((DEFGENERIC *) value)->busy--;
}
/***************************************************
NAME : IncrementGenericBusyCount
DESCRIPTION : Raises the busy count of a
generic function construct
INPUTS : The generic function
RETURNS : Nothing useful
SIDE EFFECTS : Busy count incremented
NOTES : None
***************************************************/
static void IncrementGenericBusyCount(
void *theEnv,
void *value)
{
((DEFGENERIC *) value)->busy++;
}
#if (! BLOAD_ONLY) && (! RUN_TIME)
/**********************************************************************
NAME : SaveDefgenerics
DESCRIPTION : Outputs pretty-print forms of generic function headers
INPUTS : The logical name of the output
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
**********************************************************************/
static void SaveDefgenerics(
void *theEnv,
void *theModule,
const char *logName)
{
SaveConstruct(theEnv,theModule,logName,DefgenericData(theEnv)->DefgenericConstruct);
}
/**********************************************************************
NAME : SaveDefmethods
DESCRIPTION : Outputs pretty-print forms of generic function methods
INPUTS : The logical name of the output
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
**********************************************************************/
static void SaveDefmethods(
void *theEnv,
void *theModule,
const char *logName)
{
DoForAllConstructsInModule(theEnv,theModule,SaveDefmethodsForDefgeneric,
DefgenericData(theEnv)->DefgenericModuleIndex,
FALSE,(void *) logName);
}
/***************************************************
NAME : SaveDefmethodsForDefgeneric
DESCRIPTION : Save the pretty-print forms of
all methods for a generic function
to a file
INPUTS : 1) The defgeneric
2) The logical name of the output
RETURNS : Nothing useful
SIDE EFFECTS : Methods written
NOTES : None
***************************************************/
static void SaveDefmethodsForDefgeneric(
void *theEnv,
struct constructHeader *theDefgeneric,
void *userBuffer)
{
DEFGENERIC *gfunc = (DEFGENERIC *) theDefgeneric;
const char *logName = (const char *) userBuffer;
long i;
for (i = 0 ; i < gfunc->mcnt ; i++)
{
if (gfunc->methods[i].ppForm != NULL)
{
PrintInChunks(theEnv,logName,gfunc->methods[i].ppForm);
EnvPrintRouter(theEnv,logName,"\n");
}
}
}
/****************************************************
NAME : RemoveDefgenericMethod
DESCRIPTION : Removes a generic function method
from the array and removes the
generic too if its the last method
INPUTS : 1) The generic function
2) The array index of the method
RETURNS : Nothing useful
SIDE EFFECTS : List adjusted
Nodes deallocated
NOTES : Assumes deletion is safe
****************************************************/
static void RemoveDefgenericMethod(
void *theEnv,
DEFGENERIC *gfunc,
long gi)
{
DEFMETHOD *narr;
long b,e;
if (gfunc->methods[gi].system)
{
SetEvaluationError(theEnv,TRUE);
PrintErrorID(theEnv,"GENRCCOM",4,FALSE);
EnvPrintRouter(theEnv,WERROR,"Cannot remove implicit system function method for generic function ");
EnvPrintRouter(theEnv,WERROR,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,WERROR,".\n");
return;
}
DeleteMethodInfo(theEnv,gfunc,&gfunc->methods[gi]);
if (gfunc->mcnt == 1)
{
rm(theEnv,(void *) gfunc->methods,(int) sizeof(DEFMETHOD));
gfunc->mcnt = 0;
gfunc->methods = NULL;
}
else
{
gfunc->mcnt--;
narr = (DEFMETHOD *) gm2(theEnv,(sizeof(DEFMETHOD) * gfunc->mcnt));
for (b = e = 0 ; b < gfunc->mcnt ; b++ , e++)
{
if (((int) b) == gi)
e++;
GenCopyMemory(DEFMETHOD,1,&narr[b],&gfunc->methods[e]);
}
rm(theEnv,(void *) gfunc->methods,(sizeof(DEFMETHOD) * (gfunc->mcnt+1)));
gfunc->methods = narr;
}
}
#endif
#if DEBUGGING_FUNCTIONS
/******************************************************
NAME : ListMethodsForGeneric
DESCRIPTION : Lists a brief description of methods
for a particular generic function
INPUTS : 1) The logical name of the output
2) Generic function to list methods for
RETURNS : The number of methods printed
SIDE EFFECTS : None
NOTES : None
******************************************************/
static long ListMethodsForGeneric(
void *theEnv,
const char *logicalName,
DEFGENERIC *gfunc)
{
long gi;
char buf[256];
for (gi = 0 ; gi < gfunc->mcnt ; gi++)
{
EnvPrintRouter(theEnv,logicalName,EnvGetDefgenericName(theEnv,(void *) gfunc));
EnvPrintRouter(theEnv,logicalName," #");
PrintMethod(theEnv,buf,255,&gfunc->methods[gi]);
EnvPrintRouter(theEnv,logicalName,buf);
EnvPrintRouter(theEnv,logicalName,"\n");
}
return((long) gfunc->mcnt);
}
/******************************************************************
NAME : DefgenericWatchAccess
DESCRIPTION : Parses a list of generic names passed by
AddWatchItem() and sets the traces accordingly
INPUTS : 1) A code indicating which trace flag is to be set
Ignored
2) The value to which to set the trace flags
3) A list of expressions containing the names
of the generics for which to set traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags set in specified generics
NOTES : Accessory function for AddWatchItem()
******************************************************************/
static unsigned DefgenericWatchAccess(
void *theEnv,
int code,
unsigned newState,
EXPRESSION *argExprs)
{
return(ConstructSetWatchAccess(theEnv,DefgenericData(theEnv)->DefgenericConstruct,newState,argExprs,
EnvGetDefgenericWatch,EnvSetDefgenericWatch));
}
/***********************************************************************
NAME : DefgenericWatchPrint
DESCRIPTION : Parses a list of generic names passed by
AddWatchItem() and displays the traces accordingly
INPUTS : 1) The logical name of the output
2) A code indicating which trace flag is to be examined
Ignored
3) A list of expressions containing the names
of the generics for which to examine traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags displayed for specified generics
NOTES : Accessory function for AddWatchItem()
***********************************************************************/
static unsigned DefgenericWatchPrint(
void *theEnv,
const char *logName,
int code,
EXPRESSION *argExprs)
{
return(ConstructPrintWatchAccess(theEnv,DefgenericData(theEnv)->DefgenericConstruct,logName,argExprs,
EnvGetDefgenericWatch,EnvSetDefgenericWatch));
}
/******************************************************************
NAME : DefmethodWatchAccess
DESCRIPTION : Parses a list of methods passed by
AddWatchItem() and sets the traces accordingly
INPUTS : 1) A code indicating which trace flag is to be set
Ignored
2) The value to which to set the trace flags
3) A list of expressions containing the methods
for which to set traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags set in specified methods
NOTES : Accessory function for AddWatchItem()
******************************************************************/
static unsigned DefmethodWatchAccess(
void *theEnv,
int code,
unsigned newState,
EXPRESSION *argExprs)
{
if (newState)
return(DefmethodWatchSupport(theEnv,"watch",NULL,newState,NULL,EnvSetDefmethodWatch,argExprs));
else
return(DefmethodWatchSupport(theEnv,"unwatch",NULL,newState,NULL,EnvSetDefmethodWatch,argExprs));
}
/***********************************************************************
NAME : DefmethodWatchPrint
DESCRIPTION : Parses a list of methods passed by
AddWatchItem() and displays the traces accordingly
INPUTS : 1) The logical name of the output
2) A code indicating which trace flag is to be examined
Ignored
3) A list of expressions containing the methods for
which to examine traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags displayed for specified methods
NOTES : Accessory function for AddWatchItem()
***********************************************************************/
static unsigned DefmethodWatchPrint(
void *theEnv,
const char *logName,
int code,
EXPRESSION *argExprs)
{
return(DefmethodWatchSupport(theEnv,"list-watch-items",logName,0,
PrintMethodWatchFlag,NULL,argExprs));
}
/*******************************************************
NAME : DefmethodWatchSupport
DESCRIPTION : Sets or displays methods specified
INPUTS : 1) The calling function name
2) The logical output name for displays
(can be NULL)
3) The new set state
4) The print function (can be NULL)
5) The trace function (can be NULL)
6) The methods expression list
RETURNS : TRUE if all OK,
FALSE otherwise
SIDE EFFECTS : Method trace flags set or displayed
NOTES : None
*******************************************************/
static unsigned DefmethodWatchSupport(
void *theEnv,
const char *funcName,
const char *logName,
unsigned newState,
void (*printFunc)(void *,const char *,void *,long),
void (*traceFunc)(void *,unsigned,void *,long),
EXPRESSION *argExprs)
{
void *theGeneric;
unsigned long theMethod = 0;
int argIndex = 2;
DATA_OBJECT genericName,methodIndex;
struct defmodule *theModule;
/* ==============================
If no methods are specified,
show the trace for all methods
in all generics
============================== */
if (argExprs == NULL)
{
SaveCurrentModule(theEnv);
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
while (theModule != NULL)
{
EnvSetCurrentModule(theEnv,(void *) theModule);
if (traceFunc == NULL)
{
EnvPrintRouter(theEnv,logName,EnvGetDefmoduleName(theEnv,(void *) theModule));
EnvPrintRouter(theEnv,logName,":\n");
}
theGeneric = EnvGetNextDefgeneric(theEnv,NULL);
while (theGeneric != NULL)
{
theMethod = EnvGetNextDefmethod(theEnv,theGeneric,0);
while (theMethod != 0)
{
if (traceFunc != NULL)
(*traceFunc)(theEnv,newState,theGeneric,theMethod);
else
{
EnvPrintRouter(theEnv,logName," ");
(*printFunc)(theEnv,logName,theGeneric,theMethod);
}
theMethod = EnvGetNextDefmethod(theEnv,theGeneric,theMethod);
}
theGeneric = EnvGetNextDefgeneric(theEnv,theGeneric);
}
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule);
}
RestoreCurrentModule(theEnv);
return(TRUE);
}
/* =========================================
Set the traces for every method specified
========================================= */
while (argExprs != NULL)
{
if (EvaluateExpression(theEnv,argExprs,&genericName))
return(FALSE);
if ((genericName.type != SYMBOL) ? TRUE :
((theGeneric = (void *)
LookupDefgenericByMdlOrScope(theEnv,DOToString(genericName))) == NULL))
{
ExpectedTypeError1(theEnv,funcName,argIndex,"generic function name");
return(FALSE);
}
if (GetNextArgument(argExprs) == NULL)
theMethod = 0;
else
{
argExprs = GetNextArgument(argExprs);
argIndex++;
if (EvaluateExpression(theEnv,argExprs,&methodIndex))
return(FALSE);
if ((methodIndex.type != INTEGER) ? FALSE :
((DOToLong(methodIndex) <= 0) ? FALSE :
(FindMethodByIndex((DEFGENERIC *) theGeneric,theMethod) != -1)))
theMethod = (long) DOToLong(methodIndex);
else
{
ExpectedTypeError1(theEnv,funcName,argIndex,"method index");
return(FALSE);
}
}
if (theMethod == 0)
{
theMethod = EnvGetNextDefmethod(theEnv,theGeneric,0);
while (theMethod != 0)
{
if (traceFunc != NULL)
(*traceFunc)(theEnv,newState,theGeneric,theMethod);
else
(*printFunc)(theEnv,logName,theGeneric,theMethod);
theMethod = EnvGetNextDefmethod(theEnv,theGeneric,theMethod);
}
}
else
{
if (traceFunc != NULL)
(*traceFunc)(theEnv,newState,theGeneric,theMethod);
else
(*printFunc)(theEnv,logName,theGeneric,theMethod);
}
argExprs = GetNextArgument(argExprs);
argIndex++;
}
return(TRUE);
}
/***************************************************
NAME : PrintMethodWatchFlag
DESCRIPTION : Displays trace value for method
INPUTS : 1) The logical name of the output
2) The generic function
3) The method index
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
***************************************************/
static void PrintMethodWatchFlag(
void *theEnv,
const char *logName,
void *theGeneric,
long theMethod)
{
char buf[60];
EnvPrintRouter(theEnv,logName,EnvGetDefgenericName(theEnv,theGeneric));
EnvPrintRouter(theEnv,logName," ");
EnvGetDefmethodDescription(theEnv,buf,59,theGeneric,theMethod);
EnvPrintRouter(theEnv,logName,buf);
if (EnvGetDefmethodWatch(theEnv,theGeneric,theMethod))
EnvPrintRouter(theEnv,logName," = on\n");
else
EnvPrintRouter(theEnv,logName," = off\n");
}
#endif
#if ! OBJECT_SYSTEM
/***************************************************
NAME : TypeCommand
DESCRIPTION : Works like "class" in COOL
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (type <primitive>)
***************************************************/
globle void TypeCommand(
void *theEnv,
DATA_OBJECT *result)
{
EvaluateExpression(theEnv,GetFirstArgument(),result);
result->value = (void *) EnvAddSymbol(theEnv,TypeName(theEnv,result->type));
result->type = SYMBOL;
}
#endif
/*#############################*/
/* Additional Access Functions */
/*#############################*/
globle SYMBOL_HN *GetDefgenericNamePointer(
void *theDefgeneric)
{
return GetConstructNamePointer((struct constructHeader *) theDefgeneric);
}
globle void SetNextDefgeneric(
void *theDefgeneric,
void *targetDefgeneric)
{
SetNextConstruct((struct constructHeader *) theDefgeneric,
(struct constructHeader *) targetDefgeneric);
}
/*##################################*/
/* Additional Environment Functions */
/*##################################*/
globle const char *EnvDefgenericModule(
void *theEnv,
void *theDefgeneric)
{
return GetConstructModuleName((struct constructHeader *) theDefgeneric);
}
globle const char *EnvGetDefgenericName(
void *theEnv,
void *theDefgeneric)
{
return GetConstructNameString((struct constructHeader *) theDefgeneric);
}
globle const char *EnvGetDefgenericPPForm(
void *theEnv,
void *theDefgeneric)
{
return GetConstructPPForm(theEnv,(struct constructHeader *) theDefgeneric);
}
globle SYMBOL_HN *EnvGetDefgenericNamePointer(
void *theEnv,
void *theDefgeneric)
{
return GetConstructNamePointer((struct constructHeader *) theDefgeneric);
}
globle void EnvSetDefgenericPPForm(
void *theEnv,
void *theDefgeneric,
const char *thePPForm)
{
SetConstructPPForm(theEnv,(struct constructHeader *) theDefgeneric,thePPForm);
}
/*#####################################*/
/* ALLOW_ENVIRONMENT_GLOBALS Functions */
/*#####################################*/
#if ALLOW_ENVIRONMENT_GLOBALS
globle void SetDefgenericPPForm(
void *theDefgeneric,
const char *thePPForm)
{
EnvSetDefgenericPPForm(GetCurrentEnvironment(),theDefgeneric,thePPForm);
}
globle const char *DefgenericModule(
void *theDefgeneric)
{
return EnvDefgenericModule(GetCurrentEnvironment(),theDefgeneric);
}
globle void *FindDefgeneric(
const char *genericModuleAndName)
{
return EnvFindDefgeneric(GetCurrentEnvironment(),genericModuleAndName);
}
globle void GetDefgenericList(
DATA_OBJECT *returnValue,
struct defmodule *theModule)
{
EnvGetDefgenericList(GetCurrentEnvironment(),returnValue,theModule);
}
globle const char *GetDefgenericName(
void *theDefgeneric)
{
return EnvGetDefgenericName(GetCurrentEnvironment(),theDefgeneric);
}
globle const char *GetDefgenericPPForm(
void *theDefgeneric)
{
return EnvGetDefgenericPPForm(GetCurrentEnvironment(),theDefgeneric);
}
globle void *GetNextDefgeneric(
void *ptr)
{
return EnvGetNextDefgeneric(GetCurrentEnvironment(),ptr);
}
globle int IsDefgenericDeletable(
void *ptr)
{
return EnvIsDefgenericDeletable(GetCurrentEnvironment(),ptr);
}
globle intBool Undefgeneric(
void *vptr)
{
return EnvUndefgeneric(GetCurrentEnvironment(),vptr);
}
globle void GetDefmethodList(
void *vgfunc,
DATA_OBJECT_PTR returnValue)
{
EnvGetDefmethodList(GetCurrentEnvironment(),vgfunc,returnValue);
}
globle void GetMethodRestrictions(
void *vgfunc,
long mi,
DATA_OBJECT *result)
{
EnvGetMethodRestrictions(GetCurrentEnvironment(),vgfunc,mi,result);
}
globle long GetNextDefmethod(
void *ptr,
long theIndex)
{
return EnvGetNextDefmethod(GetCurrentEnvironment(),ptr,theIndex);
}
globle int IsDefmethodDeletable(
void *ptr,
long theIndex)
{
return EnvIsDefmethodDeletable(GetCurrentEnvironment(),ptr,theIndex);
}
globle intBool Undefmethod(
void *vptr,
long mi)
{
return EnvUndefmethod(GetCurrentEnvironment(),vptr,mi);
}
#if DEBUGGING_FUNCTIONS
globle unsigned GetDefgenericWatch(
void *theGeneric)
{
return EnvGetDefgenericWatch(GetCurrentEnvironment(),theGeneric);
}
globle void ListDefgenerics(
const char *logicalName,
struct defmodule *theModule)
{
EnvListDefgenerics(GetCurrentEnvironment(),logicalName,theModule);
}
globle void SetDefgenericWatch(
unsigned newState,
void *theGeneric)
{
EnvSetDefgenericWatch(GetCurrentEnvironment(),newState,theGeneric);
}
globle const char *GetDefmethodPPForm(
void *ptr,
long theIndex)
{
return EnvGetDefmethodPPForm(GetCurrentEnvironment(),ptr,theIndex);
}
globle unsigned GetDefmethodWatch(
void *theGeneric,
long theIndex)
{
return EnvGetDefmethodWatch(GetCurrentEnvironment(),theGeneric,theIndex);
}
globle void ListDefmethods(
const char *logicalName,
void *vptr)
{
EnvListDefmethods(GetCurrentEnvironment(),logicalName,vptr);
}
globle void SetDefmethodWatch(
unsigned newState,
void *theGeneric,
long theIndex)
{
EnvSetDefmethodWatch(GetCurrentEnvironment(),newState,theGeneric,theIndex);
}
#endif /* DEBUGGING_FUNCTIONS */
#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS
globle void GetDefmethodDescription(
char *buf,
int buflen,
void *ptr,
long theIndex)
{
EnvGetDefmethodDescription(GetCurrentEnvironment(),buf,buflen,ptr,theIndex);
}
#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* DEFGENERIC_CONSTRUCT */
|
DrItanium/durandal
|
include/indirect/Indirector.h
|
#ifndef _indirect_indirector_h
#define _indirect_indirector_h
/*
* This file is a wrapper over the other include files that make up
* libindirect. It is meant to make libindirect easy to use
*/
#include "indirect/IndirectAnalysisUsageDeclaration.h"
#include "indirect/IndirectPasses.h"
#include "indirect/IndirectPassGenerator.h"
#include "indirect/IndirectPass.h"
#include "indirect/IndirectPassHeader.h"
#include "indirect/IndirectPassRegistry.h"
#include "indirect/IndirectUniqueIdentifier.h"
#include "indirect/RegisterIndirectPass.h"
#endif
|
DrItanium/durandal
|
include/pipeline/clips/CLIPSPipelineFunctions.h
|
#ifndef _clips_pipeline_functions_h
#define _clips_pipeline_functions_h
extern "C" void RegisterCLIPSPipelineFunctions(void* theEnv);
namespace pipeline {
namespace clips {
void initializeCLIPSIndirector();
}
}
#endif
|
DrItanium/durandal
|
include/rampancy/CompilerManager.h
|
/*
* The CompilerManager is a custom pass manager that handles both dynamic
* compilation as well as knowledge construction in addition to being a
* standard pass manager.
*
* It also provides a standard way to register compilers with CLIPS through the
* IO router system. This makes it really easy to add new compilers without any
* complex issues.
*
*/
#ifndef _rampancy_compiler_manager_h
#define _rampancy_compiler_manager_h
#include "llvm/Pass.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "rampancy/Compiler.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/StringRef.h"
namespace rampancy {
class CompilerManager {
private:
llvm::LLVMContext* context;
CLIPSEnvironment* env;
public:
CompilerManager();
~CompilerManager();
llvm::LLVMContext* getContext();
void setContext(llvm::LLVMContext* llvmContext);
CLIPSEnvironment* getEnvironment();
void setEnvironment(CLIPSEnvironment* theEnv);
llvm::Module* compile(llvm::StringRef logicalName, void* theEnv);
llvm::Module* compile(char* logicalName, int argc, char** argv);
llvm::Module* compile(llvm::StringRef logicalName, int argc, char** argv);
llvm::Module* interpret(llvm::StringRef logicalName, void* theEnv);
llvm::Module* interpret(char* logicalName, llvm::StringRef input);
llvm::Module* interpret(llvm::StringRef logicalName, llvm::StringRef input);
};
}
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSTypeBuilder.h
|
#ifndef _clips_type_builder_h
#define _clips_type_builder_h
#include "ExpertSystem/CLIPSObjectBuilder.h"
#include "llvm/Type.h"
using namespace llvm;
class CLIPSTypeBuilder : public CLIPSObjectBuilder {
public:
CLIPSTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "LLVMType");
void addFields(Type* type, KnowledgeConstructor* kc);
void build(Type* st, KnowledgeConstructor* kc);
};
class CLIPSFunctionTypeBuilder : public CLIPSTypeBuilder {
public:
CLIPSFunctionTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "FunctionType");
};
class CLIPSCompositeTypeBuilder : public CLIPSTypeBuilder {
public:
CLIPSCompositeTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "CompositeType");
};
class CLIPSSequentialTypeBuilder : public CLIPSCompositeTypeBuilder {
public:
CLIPSSequentialTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "SequentialType");
};
class CLIPSArrayTypeBuilder : public CLIPSSequentialTypeBuilder {
public:
CLIPSArrayTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "ArrayType");
};
class CLIPSPointerTypeBuilder : public CLIPSSequentialTypeBuilder {
public:
CLIPSPointerTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "PointerType");
};
class CLIPSVectorTypeBuilder : public CLIPSSequentialTypeBuilder {
public:
CLIPSVectorTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "VectorType");
};
class CLIPSStructTypeBuilder : public CLIPSCompositeTypeBuilder {
public:
CLIPSStructTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "StructType");
void addFields(StructType* st, KnowledgeConstructor* kc, char* parent);
void build(StructType* st, KnowledgeConstructor* kc, char* parent);
};
class CLIPSIntegerTypeBuilder : public CLIPSTypeBuilder {
public:
CLIPSIntegerTypeBuilder(std::string nm, FunctionNamer& namer, std::string ty = "IntegerType");
};
#endif
|
DrItanium/durandal
|
lib/electron/objrtbld.c
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* OBJECT PATTERN MATCHER MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: RETE Network Parsing Interface for Objects */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.24: Removed INCREMENTAL_RESET compilation flag. */
/* */
/* Converted INSTANCE_PATTERN_MATCHING to */
/* DEFRULE_CONSTRUCT. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Changed integer type/precision. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Support for long long integers. */
/* */
/* Added support for hashed comparisons to */
/* constants. */
/* */
/* Added support for hashed alpha memories. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if DEFRULE_CONSTRUCT && OBJECT_SYSTEM
#if (! BLOAD_ONLY) && (! RUN_TIME)
#include <string.h>
#include <stdlib.h>
#include "classcom.h"
#include "classfun.h"
#include "cstrnutl.h"
#include "constrnt.h"
#include "cstrnchk.h"
#include "cstrnops.h"
#include "drive.h"
#include "envrnmnt.h"
#include "exprnpsr.h"
#include "inscom.h"
#include "insfun.h"
#include "insmngr.h"
#include "memalloc.h"
#include "network.h"
#include "object.h"
#include "pattern.h"
#include "reteutil.h"
#include "ruledef.h"
#include "rulepsr.h"
#include "scanner.h"
#include "symbol.h"
#include "utility.h"
#endif
#include "constrct.h"
#include "objrtmch.h"
#include "objrtgen.h"
#include "objrtfnx.h"
#include "reorder.h"
#include "router.h"
#if CONSTRUCT_COMPILER && (! RUN_TIME)
#include "objrtcmp.h"
#endif
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
#include "objrtbin.h"
#endif
#define _OBJRTBLD_SOURCE_
#include "objrtbld.h"
#if ! DEFINSTANCES_CONSTRUCT
#include "extnfunc.h"
#include "classfun.h"
#include "classcom.h"
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/* =========================================
*****************************************
CONSTANTS
=========================================
***************************************** */
#define OBJECT_PATTERN_INDICATOR "object"
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
static intBool PatternParserFind(SYMBOL_HN *);
static struct lhsParseNode *ObjectLHSParse(void *,const char *,struct token *);
static intBool ReorderAndAnalyzeObjectPattern(void *,struct lhsParseNode *);
static struct patternNodeHeader *PlaceObjectPattern(void *,struct lhsParseNode *);
static OBJECT_PATTERN_NODE *FindObjectPatternNode(OBJECT_PATTERN_NODE *,struct lhsParseNode *,
OBJECT_PATTERN_NODE **,unsigned,unsigned);
static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode(void *,struct lhsParseNode *,OBJECT_PATTERN_NODE *,
OBJECT_PATTERN_NODE *,unsigned,unsigned);
static void DetachObjectPattern(void *,struct patternNodeHeader *);
static void ClearObjectPatternMatches(void *,OBJECT_ALPHA_NODE *);
static void RemoveObjectPartialMatches(void *,INSTANCE_TYPE *,struct patternNodeHeader *);
static intBool CheckDuplicateSlots(void *,struct lhsParseNode *,SYMBOL_HN *);
static struct lhsParseNode *ParseClassRestriction(void *,const char *,struct token *);
static struct lhsParseNode *ParseNameRestriction(void *,const char *,struct token *);
static struct lhsParseNode *ParseSlotRestriction(void *,const char *,struct token *,CONSTRAINT_RECORD *,int);
static CLASS_BITMAP *NewClassBitMap(void *,int,int);
static void InitializeClassBitMap(void *,CLASS_BITMAP *,int);
static void DeleteIntermediateClassBitMap(void *,CLASS_BITMAP *);
static void *CopyClassBitMap(void *,void *);
static void DeleteClassBitMap(void *,void *);
static void MarkBitMapClassesBusy(void *,BITMAP_HN *,int);
static intBool EmptyClassBitMap(CLASS_BITMAP *);
static intBool IdenticalClassBitMap(CLASS_BITMAP *,CLASS_BITMAP *);
static intBool ProcessClassRestriction(void *,CLASS_BITMAP *,struct lhsParseNode **,int);
static CONSTRAINT_RECORD *ProcessSlotRestriction(void *,CLASS_BITMAP *,SYMBOL_HN *,int *);
static void IntersectClassBitMaps(CLASS_BITMAP *,CLASS_BITMAP *);
static void UnionClassBitMaps(CLASS_BITMAP *,CLASS_BITMAP *);
static CLASS_BITMAP *PackClassBitMap(void *,CLASS_BITMAP *);
static struct lhsParseNode *FilterObjectPattern(void *,struct patternParser *,
struct lhsParseNode *,struct lhsParseNode **,
struct lhsParseNode **,struct lhsParseNode **);
static BITMAP_HN *FormSlotBitMap(void *,struct lhsParseNode *);
static struct lhsParseNode *RemoveSlotExistenceTests(void *,struct lhsParseNode *,BITMAP_HN **);
static struct lhsParseNode *CreateInitialObjectPattern(void *);
static EXPRESSION *ObjectMatchDelayParse(void *,EXPRESSION *,const char *);
static void MarkObjectPtnIncrementalReset(void *,struct patternNodeHeader *,int);
static void ObjectIncrementalReset(void *);
#endif
#if ! DEFINSTANCES_CONSTRUCT
static void ResetInitialObject(void *);
#endif
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/********************************************************
NAME : SetupObjectPatternStuff
DESCRIPTION : Installs the parsers and other items
necessary for recognizing and processing
object patterns in defrules
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Rete network interfaces for objects
initialized
NOTES : None
********************************************************/
globle void SetupObjectPatternStuff(
void *theEnv)
{
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct patternParser *newPtr;
if (ReservedPatternSymbol(theEnv,"object",NULL) == TRUE)
{
SystemError(theEnv,"OBJRTBLD",1);
EnvExitRouter(theEnv,EXIT_FAILURE);
}
AddReservedPatternSymbol(theEnv,"object",NULL);
/* ===========================================================================
The object pattern parser needs to have a higher priority than deftemplates
or regular facts so that the "object" keyword is always recognized first
=========================================================================== */
newPtr = get_struct(theEnv,patternParser);
newPtr->name = "objects";
newPtr->priority = 20;
newPtr->entityType = &InstanceData(theEnv)->InstanceInfo;
newPtr->recognizeFunction = PatternParserFind;
newPtr->parseFunction = ObjectLHSParse;
newPtr->postAnalysisFunction = ReorderAndAnalyzeObjectPattern;
newPtr->addPatternFunction = PlaceObjectPattern;
newPtr->removePatternFunction = DetachObjectPattern;
newPtr->genJNConstantFunction = NULL;
newPtr->replaceGetJNValueFunction = ReplaceGetJNObjectValue;
newPtr->genGetJNValueFunction = GenGetJNObjectValue;
newPtr->genCompareJNValuesFunction = ObjectJNVariableComparison;
newPtr->genPNConstantFunction = GenObjectPNConstantCompare;
newPtr->replaceGetPNValueFunction = ReplaceGetPNObjectValue;
newPtr->genGetPNValueFunction = GenGetPNObjectValue;
newPtr->genComparePNValuesFunction = ObjectPNVariableComparison;
newPtr->returnUserDataFunction = DeleteClassBitMap;
newPtr->copyUserDataFunction = CopyClassBitMap;
newPtr->markIRPatternFunction = MarkObjectPtnIncrementalReset;
newPtr->incrementalResetFunction = ObjectIncrementalReset;
newPtr->initialPatternFunction = CreateInitialObjectPattern;
#if CONSTRUCT_COMPILER && (! RUN_TIME)
newPtr->codeReferenceFunction = ObjectPatternNodeReference;
#else
newPtr->codeReferenceFunction = NULL;
#endif
AddPatternParser(theEnv,newPtr);
EnvDefineFunction2(theEnv,"object-pattern-match-delay",'u',
PTIEF ObjectMatchDelay,"ObjectMatchDelay",NULL);
AddFunctionParser(theEnv,"object-pattern-match-delay",ObjectMatchDelayParse);
FuncSeqOvlFlags(theEnv,"object-pattern-match-delay",FALSE,FALSE);
#endif
InstallObjectPrimitives(theEnv);
#if CONSTRUCT_COMPILER && (! RUN_TIME)
ObjectPatternsCompilerSetup(theEnv);
#endif
#if ! DEFINSTANCES_CONSTRUCT
EnvAddResetFunction(theEnv,"reset-initial-object",ResetInitialObject,0);
#endif
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
SetupObjectPatternsBload(theEnv);
#endif
}
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if ! DEFINSTANCES_CONSTRUCT
static void ResetInitialObject(
void *theEnv)
{
EXPRESSION *tmp;
DATA_OBJECT rtn;
tmp = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"make-instance"));
tmp->argList = GenConstant(theEnv,INSTANCE_NAME,(void *) DefclassData(theEnv)->INITIAL_OBJECT_SYMBOL);
tmp->argList->nextArg =
GenConstant(theEnv,DEFCLASS_PTR,(void *) LookupDefclassInScope(theEnv,INITIAL_OBJECT_CLASS_NAME));
EvaluateExpression(theEnv,tmp,&rtn);
ReturnExpression(theEnv,tmp);
}
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/*****************************************************
NAME : PatternParserFind
DESCRIPTION : Determines if a pattern CE is an
object pattern (i.e. the first field
is the constant symbol "object")
INPUTS : 1) The type of the first field
2) The value of the first field
RETURNS : TRUE if it is an object pattern,
FALSE otherwise
SIDE EFFECTS : None
NOTES : Used by AddPatternParser()
*****************************************************/
static intBool PatternParserFind(
SYMBOL_HN *value)
{
if (strcmp(ValueToString(value),OBJECT_PATTERN_INDICATOR) == 0)
return(TRUE);
return(FALSE);
}
/************************************************************************************
NAME : ObjectLHSParse
DESCRIPTION : Scans and parses an object pattern for a rule
INPUTS : 1) The logical name of the input source
2) A buffer holding the last token read
RETURNS : The address of struct lhsParseNodes, NULL on errors
SIDE EFFECTS : A series of struct lhsParseNodes are created to represent
the intermediate parse of the pattern
Pretty-print form for the pattern is saved
NOTES : Object Pattern Syntax:
(object [<class-constraint>] [<name-constraint>] <slot-constraint>*)
<class-constraint> ::= (is-a <constraint>)
<name-constraint> ::= (name <constraint>)
<slot-constraint> ::= (<slot-name> <constraint>*)
************************************************************************************/
static struct lhsParseNode *ObjectLHSParse(
void *theEnv,
const char *readSource,
struct token *lastToken)
{
struct token theToken;
struct lhsParseNode *firstNode = NULL,*lastNode = NULL,*tmpNode;
CLASS_BITMAP *clsset,*tmpset;
CONSTRAINT_RECORD *slotConstraints;
int ppbackupReqd = FALSE,multip;
/* ========================================================
Get a bitmap big enough to mark the ids of all currently
existing classes - and set all bits, since the initial
set of applicable classes is everything.
======================================================== */
clsset = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
DeleteIntermediateClassBitMap(theEnv,clsset);
return(NULL);
}
tmpset = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
IncrementIndentDepth(theEnv,7);
/* ===========================================
Parse the class, name and slot restrictions
=========================================== */
GetToken(theEnv,readSource,&theToken);
while (theToken.type != RPAREN)
{
ppbackupReqd = TRUE;
PPBackup(theEnv);
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken.printForm);
if (theToken.type != LPAREN)
{
SyntaxErrorMessage(theEnv,"object pattern");
goto ObjectLHSParseERROR;
}
GetToken(theEnv,readSource,&theToken);
if (theToken.type != SYMBOL)
{
SyntaxErrorMessage(theEnv,"object pattern");
goto ObjectLHSParseERROR;
}
if (CheckDuplicateSlots(theEnv,firstNode,(SYMBOL_HN *) theToken.value))
goto ObjectLHSParseERROR;
if (theToken.value == (void *) DefclassData(theEnv)->ISA_SYMBOL)
{
tmpNode = ParseClassRestriction(theEnv,readSource,&theToken);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
InitializeClassBitMap(theEnv,tmpset,0);
if (ProcessClassRestriction(theEnv,tmpset,&tmpNode->bottom,TRUE) == FALSE)
{
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
IntersectClassBitMaps(clsset,tmpset);
}
else if (theToken.value == (void *) DefclassData(theEnv)->NAME_SYMBOL)
{
tmpNode = ParseNameRestriction(theEnv,readSource,&theToken);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
InitializeClassBitMap(theEnv,tmpset,1);
}
else
{
slotConstraints = ProcessSlotRestriction(theEnv,clsset,(SYMBOL_HN *) theToken.value,&multip);
if (slotConstraints != NULL)
{
InitializeClassBitMap(theEnv,tmpset,1);
tmpNode = ParseSlotRestriction(theEnv,readSource,&theToken,slotConstraints,multip);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
}
else
{
InitializeClassBitMap(theEnv,tmpset,0);
tmpNode = GetLHSParseNode(theEnv);
tmpNode->slot = (SYMBOL_HN *) theToken.value;
}
}
if (EmptyClassBitMap(tmpset))
{
PrintErrorID(theEnv,"OBJRTBLD",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy ");
EnvPrintRouter(theEnv,WERROR,ValueToString(tmpNode->slot));
EnvPrintRouter(theEnv,WERROR," restriction in object pattern.\n");
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
if (tmpNode != NULL)
{
if (firstNode == NULL)
firstNode = tmpNode;
else
lastNode->right = tmpNode;
lastNode = tmpNode;
}
PPCRAndIndent(theEnv);
GetToken(theEnv,readSource,&theToken);
}
if (firstNode == NULL)
{
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
goto ObjectLHSParseERROR;
}
firstNode = GetLHSParseNode(theEnv);
firstNode->type = SF_WILDCARD;
firstNode->slot = DefclassData(theEnv)->ISA_SYMBOL;
firstNode->slotNumber = ISA_ID;
firstNode->index = 1;
}
if (ppbackupReqd)
{
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,theToken.printForm);
}
DeleteIntermediateClassBitMap(theEnv,tmpset);
clsset = PackClassBitMap(theEnv,clsset);
firstNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(firstNode->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
DecrementIndentDepth(theEnv,7);
return(firstNode);
ObjectLHSParseERROR:
DeleteIntermediateClassBitMap(theEnv,clsset);
DeleteIntermediateClassBitMap(theEnv,tmpset);
ReturnLHSParseNodes(theEnv,firstNode);
DecrementIndentDepth(theEnv,7);
return(NULL);
}
/**************************************************************
NAME : ReorderAndAnalyzeObjectPattern
DESCRIPTION : This function reexamines the object pattern
after constraint and variable analysis info
has been propagated from other patterns.
Any slots which are no longer applicable
to the pattern are eliminated from the
class set.
Also, the slot names are ordered according
to lexical value to aid in deteterming
sharing between object patterns. (The is-a
and name restrictions are always placed
first regardless of symbolic hash value.)
INPUTS : The pattern CE lhsParseNode
RETURNS : FALSE if all OK, otherwise TRUE
(e.g. all classes are eliminated as potential
matching candidates for the pattern)
SIDE EFFECTS : Slot restrictions are reordered (if necessary)
NOTES : Adds a default is-a slot if one does not
already exist
**************************************************************/
static intBool ReorderAndAnalyzeObjectPattern(
void *theEnv,
struct lhsParseNode *topNode)
{
CLASS_BITMAP *clsset,*tmpset;
EXPRESSION *rexp,*tmpmin,*tmpmax;
DEFCLASS *cls;
struct lhsParseNode *tmpNode,*subNode,*bitmap_node,*isa_node,*name_node;
register unsigned short i;
SLOT_DESC *sd;
CONSTRAINT_RECORD *crossConstraints, *theConstraint;
int incompatibleConstraint,clssetChanged = FALSE;
/* ==========================================================
Make sure that the bitmap marking which classes of object
can match the pattern is attached to the class restriction
(which will always be present and the last restriction
after the sort)
========================================================== */
topNode->right = FilterObjectPattern(theEnv,topNode->patternType,topNode->right,
&bitmap_node,&isa_node,&name_node);
if (EnvGetStaticConstraintChecking(theEnv) == FALSE)
return(FALSE);
/* ============================================
Allocate a temporary set for marking classes
============================================ */
clsset = (CLASS_BITMAP *) ValueToBitMap(bitmap_node->userData);
tmpset = NewClassBitMap(theEnv,(int) clsset->maxid,0);
/* ==========================================================
Check the allowed-values for the constraint on the is-a
slot. If there are any, make sure that only the classes
with those values as names are marked in the bitmap.
There will only be symbols in the list because the
original constraint on the is-a slot allowed only symbols.
========================================================== */
if ((isa_node == NULL) ? FALSE :
((isa_node->constraints == NULL) ? FALSE :
(isa_node->constraints->restrictionList != NULL)))
{
rexp = isa_node->constraints->restrictionList;
while (rexp != NULL)
{
cls = LookupDefclassInScope(theEnv,ValueToString(rexp->value));
if (cls != NULL)
{
if ((cls->id <= (unsigned) clsset->maxid) ? TestBitMap(clsset->map,cls->id) : FALSE)
SetBitMap(tmpset->map,cls->id);
}
rexp = rexp->nextArg;
}
clssetChanged = IdenticalClassBitMap(tmpset,clsset) ? FALSE : TRUE;
}
else
GenCopyMemory(char,tmpset->maxid / BITS_PER_BYTE + 1,tmpset->map,clsset->map);
/* ================================================================
For each of the slots (excluding name and is-a), check the total
constraints for the slot against the individual constraints
for each occurrence of the slot in the classes marked in
the bitmap. For any slot which is not compatible with
the overall constraint, clear its class's bit in the bitmap.
================================================================ */
tmpNode = topNode->right;
while (tmpNode != bitmap_node)
{
if ((tmpNode == isa_node) || (tmpNode == name_node))
{
tmpNode = tmpNode->right;
continue;
}
for (i = 0 ; i <= tmpset->maxid ; i++)
if (TestBitMap(tmpset->map,i))
{
cls = DefclassData(theEnv)->ClassIDMap[i];
sd = cls->instanceTemplate[FindInstanceTemplateSlot(theEnv,cls,tmpNode->slot)];
/* =========================================
Check the top-level lhsParseNode for type
and cardinality compatibility
========================================= */
crossConstraints = IntersectConstraints(theEnv,tmpNode->constraints,sd->constraint);
incompatibleConstraint = UnmatchableConstraint(crossConstraints);
RemoveConstraint(theEnv,crossConstraints);
if (incompatibleConstraint)
{
ClearBitMap(tmpset->map,i);
clssetChanged = TRUE;
}
else if (tmpNode->type == MF_WILDCARD)
{
/* ==========================================
Check the sub-nodes for type compatibility
========================================== */
for (subNode = tmpNode->bottom ; subNode != NULL ; subNode = subNode->right)
{
/* ========================================================
Temporarily reset cardinality of variables to
match slot so that no cardinality errors will be flagged
======================================================== */
if ((subNode->type == MF_WILDCARD) || (subNode->type == MF_VARIABLE))
{ theConstraint = subNode->constraints->multifield; }
else
{ theConstraint = subNode->constraints; }
tmpmin = theConstraint->minFields;
theConstraint->minFields = sd->constraint->minFields;
tmpmax = theConstraint->maxFields;
theConstraint->maxFields = sd->constraint->maxFields;
crossConstraints = IntersectConstraints(theEnv,theConstraint,sd->constraint);
theConstraint->minFields = tmpmin;
theConstraint->maxFields = tmpmax;
incompatibleConstraint = UnmatchableConstraint(crossConstraints);
RemoveConstraint(theEnv,crossConstraints);
if (incompatibleConstraint)
{
ClearBitMap(tmpset->map,i);
clssetChanged = TRUE;
break;
}
}
}
}
tmpNode = tmpNode->right;
}
if (clssetChanged)
{
/* =======================================================
Make sure that there are still classes of objects which
can satisfy this pattern. Otherwise, signal an error.
======================================================= */
if (EmptyClassBitMap(tmpset))
{
PrintErrorID(theEnv,"OBJRTBLD",3,TRUE);
DeleteIntermediateClassBitMap(theEnv,tmpset);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern #");
PrintLongInteger(theEnv,WERROR,(long long) topNode->pattern);
EnvPrintRouter(theEnv,WERROR,".\n");
return(TRUE);
}
clsset = PackClassBitMap(theEnv,tmpset);
DeleteClassBitMap(theEnv,(void *) bitmap_node->userData);
bitmap_node->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(bitmap_node->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
}
else
DeleteIntermediateClassBitMap(theEnv,tmpset);
return(FALSE);
}
/*****************************************************
NAME : PlaceObjectPattern
DESCRIPTION : Integrates an object pattern into the
object pattern network
INPUTS : The intermediate parse representation
of the pattern
RETURNS : The address of the new pattern
SIDE EFFECTS : Object pattern network updated
NOTES : None
*****************************************************/
static struct patternNodeHeader *PlaceObjectPattern(
void *theEnv,
struct lhsParseNode *thePattern)
{
OBJECT_PATTERN_NODE *currentLevel,*lastLevel;
struct lhsParseNode *tempPattern = NULL;
OBJECT_PATTERN_NODE *nodeSlotGroup, *newNode;
OBJECT_ALPHA_NODE *newAlphaNode;
unsigned endSlot;
BITMAP_HN *newClassBitMap,*newSlotBitMap;
struct expr *rightHash;
/*========================================================*/
/* Get the top of the object pattern network and prepare */
/* for the traversal to look for shareable pattern nodes. */
/*========================================================*/
currentLevel = ObjectNetworkPointer(theEnv);
lastLevel = NULL;
/*====================================================*/
/* Remove slot existence tests from the pattern since */
/* these are accounted for by the class bitmap and */
/* find the class and slot bitmaps. */
/*====================================================*/
rightHash = thePattern->rightHash;
newSlotBitMap = FormSlotBitMap(theEnv,thePattern->right);
thePattern->right = RemoveSlotExistenceTests(theEnv,thePattern->right,&newClassBitMap);
thePattern = thePattern->right;
/*=========================================================*/
/* Loop until all fields in the pattern have been added to */
/* the pattern network. Process the bitmap node ONLY if it */
/* is the only node in the pattern. */
/*=========================================================*/
do
{
if (thePattern->multifieldSlot)
{
tempPattern = thePattern;
thePattern = thePattern->bottom;
}
/*============================================*/
/* Determine if the last pattern field within */
/* a multifield slot is being processed. */
/*============================================*/
if (((thePattern->type == MF_WILDCARD) ||
(thePattern->type == MF_VARIABLE)) &&
(thePattern->right == NULL) && (tempPattern != NULL))
{ endSlot = TRUE; }
else
{ endSlot = FALSE; }
/*========================================*/
/* Is there a node in the pattern network */
/* that can be reused (shared)? */
/*========================================*/
newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,FALSE);
/*================================================*/
/* If the pattern node cannot be shared, then add */
/* a new pattern node to the pattern network. */
/*================================================*/
if (newNode == NULL)
{ newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,FALSE); }
if (thePattern->constantSelector != NULL)
{
currentLevel = newNode->nextLevel;
lastLevel = newNode;
newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,TRUE);
if (newNode == NULL)
{ newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,TRUE); }
}
/*=======================================================*/
/* Move on to the next field in the pattern to be added. */
/*=======================================================*/
if ((thePattern->right == NULL) && (tempPattern != NULL))
{
thePattern = tempPattern;
tempPattern = NULL;
}
lastLevel = newNode;
currentLevel = newNode->nextLevel;
thePattern = thePattern->right;
}
while ((thePattern != NULL) ? (thePattern->userData == NULL) : FALSE);
/*==================================================*/
/* Return the leaf node of the newly added pattern. */
/*==================================================*/
newAlphaNode = lastLevel->alphaNode;
while (newAlphaNode != NULL)
{
if ((newClassBitMap == newAlphaNode->classbmp) &&
(newSlotBitMap == newAlphaNode->slotbmp) &&
IdenticalExpression(newAlphaNode->header.rightHash,rightHash))
return((struct patternNodeHeader *) newAlphaNode);
newAlphaNode = newAlphaNode->nxtInGroup;
}
newAlphaNode = get_struct(theEnv,objectAlphaNode);
InitializePatternHeader(theEnv,&newAlphaNode->header);
newAlphaNode->header.rightHash = AddHashedExpression(theEnv,rightHash);
newAlphaNode->matchTimeTag = 0L;
newAlphaNode->patternNode = lastLevel;
newAlphaNode->classbmp = newClassBitMap;
IncrementBitMapCount(newClassBitMap);
MarkBitMapClassesBusy(theEnv,newClassBitMap,1);
newAlphaNode->slotbmp = newSlotBitMap;
if (newSlotBitMap != NULL)
IncrementBitMapCount(newSlotBitMap);
newAlphaNode->bsaveID = 0L;
newAlphaNode->nxtInGroup = lastLevel->alphaNode;
lastLevel->alphaNode = newAlphaNode;
newAlphaNode->nxtTerminal = ObjectNetworkTerminalPointer(theEnv);
SetObjectNetworkTerminalPointer(theEnv,newAlphaNode);
return((struct patternNodeHeader *) newAlphaNode);
}
/************************************************************************
NAME : FindObjectPatternNode
DESCRIPTION : Looks for a pattern node at a specified
level in the pattern network that can be reused (shared)
with a pattern field being added to the pattern network.
INPUTS : 1) The current layer of nodes being examined in the
object pattern network
2) The intermediate parse representation of the pattern
being added
3) A buffer for holding the first node of a group
of slots with the same name as the new node
4) An integer code indicating if this is the last
fiedl in a slot pattern or not
RETURNS : The old pattern network node matching the new node, or
NULL if there is none (nodeSlotGroup will hold the
place where to attach a new node)
SIDE EFFECTS : nodeSlotGroup set
NOTES : None
************************************************************************/
static OBJECT_PATTERN_NODE *FindObjectPatternNode(
OBJECT_PATTERN_NODE *listOfNodes,
struct lhsParseNode *thePattern,
OBJECT_PATTERN_NODE **nodeSlotGroup,
unsigned endSlot,
unsigned constantSelector)
{
struct expr *compareTest;
*nodeSlotGroup = NULL;
if (constantSelector)
{ compareTest = thePattern->constantValue; }
else if (thePattern->constantSelector != NULL)
{ compareTest = thePattern->constantSelector; }
else
{ compareTest = thePattern->networkTest; }
/*==========================================================*/
/* Loop through the nodes at the given level in the pattern */
/* network looking for a node that can be reused (shared). */
/*==========================================================*/
while (listOfNodes != NULL)
{
/*=========================================================*/
/* A object pattern node can be shared if the slot name is */
/* the same, the test is on the same field in the pattern, */
/* and the network test expressions are the same. */
/*=========================================================*/
if (((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) ?
listOfNodes->multifieldNode : (listOfNodes->multifieldNode == 0))
{
if ((thePattern->slotNumber == (int) listOfNodes->slotNameID) &&
(thePattern->index == (int) listOfNodes->whichField) &&
(thePattern->singleFieldsAfter == listOfNodes->leaveFields) &&
(endSlot == listOfNodes->endSlot) &&
IdenticalExpression(listOfNodes->networkTest,compareTest))
return(listOfNodes);
}
/*===============================================*/
/* Find the beginning of a group of nodes with */
/* the same slot name testing on the same field. */
/*===============================================*/
if ((*nodeSlotGroup == NULL) &&
(thePattern->index == (int) listOfNodes->whichField) &&
(thePattern->slotNumber == (int) listOfNodes->slotNameID))
*nodeSlotGroup = listOfNodes;
listOfNodes = listOfNodes->rightNode;
}
/*==============================================*/
/* A shareable pattern node could not be found. */
/*==============================================*/
return(NULL);
}
/*****************************************************************
NAME : CreateNewObjectPatternNode
DESCRIPTION : Creates a new pattern node and initializes
all of its values.
INPUTS : 1) The intermediate parse representation
of the new pattern node
2) A pointer to the network node after
which to add the new node
3) A pointer to the parent node on the
level above to link the new node
4) An integer code indicating if this is the last
fiedl in a slot pattern or not
RETURNS : A pointer to the new pattern node
SIDE EFFECTS : Pattern node allocated, initialized and
attached
NOTES : None
*****************************************************************/
static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode(
void *theEnv,
struct lhsParseNode *thePattern,
OBJECT_PATTERN_NODE *nodeSlotGroup,
OBJECT_PATTERN_NODE *upperLevel,
unsigned endSlot,
unsigned constantSelector)
{
OBJECT_PATTERN_NODE *newNode,*prvNode,*curNode;
newNode = get_struct(theEnv,objectPatternNode);
newNode->blocked = FALSE;
newNode->multifieldNode = FALSE;
newNode->alphaNode = NULL;
newNode->matchTimeTag = 0L;
newNode->nextLevel = NULL;
newNode->rightNode = NULL;
newNode->leftNode = NULL;
newNode->bsaveID = 0L;
if ((thePattern->constantSelector != NULL) && (! constantSelector))
{ newNode->selector = TRUE; }
else
{ newNode->selector = FALSE; }
/*===========================================================*/
/* Install the expression associated with this pattern node. */
/*===========================================================*/
if (constantSelector)
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantValue); }
else if (thePattern->constantSelector != NULL)
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantSelector); }
else
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->networkTest); }
newNode->whichField = thePattern->index;
newNode->leaveFields = thePattern->singleFieldsAfter;
/*=========================================*/
/* Install the slot name for the new node. */
/*=========================================*/
newNode->slotNameID = (unsigned) thePattern->slotNumber;
if ((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE))
newNode->multifieldNode = TRUE;
newNode->endSlot = endSlot;
/*===============================================*/
/* Set the upper level pointer for the new node. */
/*===============================================*/
newNode->lastLevel = upperLevel;
if ((upperLevel != NULL) && (upperLevel->selector))
{ AddHashedPatternNode(theEnv,upperLevel,newNode,newNode->networkTest->type,newNode->networkTest->value); }
/*==============================================*/
/* If there are no nodes with this slot name on */
/* this level, simply prepend it to the front. */
/*==============================================*/
if (nodeSlotGroup == NULL)
{
if (upperLevel == NULL)
{
newNode->rightNode = ObjectNetworkPointer(theEnv);
SetObjectNetworkPointer(theEnv,newNode);
}
else
{
newNode->rightNode = upperLevel->nextLevel;
upperLevel->nextLevel = newNode;
}
if (newNode->rightNode != NULL)
newNode->rightNode->leftNode = newNode;
return(newNode);
}
/* ===========================================================
Group this node with other nodes of the same name
testing on the same field in the pattern
on this level. This allows us to do some optimization
with constant tests on a particular slots. If we put
all constant tests for a particular slot/field group at the
end of that group, then when one of those test succeeds
during pattern-matching, we don't have to test any
more of the nodes with that slot/field name to the right.
=========================================================== */
prvNode = NULL;
curNode = nodeSlotGroup;
while ((curNode == NULL) ? FALSE :
(curNode->slotNameID == nodeSlotGroup->slotNameID) &&
(curNode->whichField == nodeSlotGroup->whichField))
{
if ((curNode->networkTest == NULL) ? FALSE :
((curNode->networkTest->type != OBJ_PN_CONSTANT) ? FALSE :
((struct ObjectCmpPNConstant *) ValueToBitMap(curNode->networkTest->value))->pass))
break;
prvNode = curNode;
curNode = curNode->rightNode;
}
if (curNode != NULL)
{
newNode->leftNode = curNode->leftNode;
newNode->rightNode = curNode;
if (curNode->leftNode != NULL)
curNode->leftNode->rightNode = newNode;
else if (curNode->lastLevel != NULL)
curNode->lastLevel->nextLevel = newNode;
else
SetObjectNetworkPointer(theEnv,newNode);
curNode->leftNode = newNode;
}
else
{
newNode->leftNode = prvNode;
prvNode->rightNode = newNode;
}
return(newNode);
}
/********************************************************
NAME : DetachObjectPattern
DESCRIPTION : Removes a pattern node and all of its
parent nodes from the pattern network. Nodes are only
removed if they are no longer shared (i.e. a pattern
node that has more than one child node is shared). A
pattern from a rule is typically removed by removing
the bottom most pattern node used by the pattern and
then removing any parent nodes which are not shared by
other patterns.
Example:
Patterns (a b c d) and (a b e f) would be represented
by the pattern net shown on the left. If (a b c d)
was detached, the resultant pattern net would be the
one shown on the right. The '=' represents an
end-of-pattern node.
a a
| |
b b
| |
c--e e
| | |
d f f
| | |
= = =
INPUTS : The pattern to be removed
RETURNS : Nothing useful
SIDE EFFECTS : All non-shared nodes associated with the
pattern are removed
NOTES : None
********************************************************/
static void DetachObjectPattern(
void *theEnv,
struct patternNodeHeader *thePattern)
{
OBJECT_ALPHA_NODE *alphaPtr,*prv,*terminalPtr;
OBJECT_PATTERN_NODE *patternPtr,*upperLevel;
/*====================================================*/
/* Get rid of any matches stored in the alpha memory. */
/*====================================================*/
alphaPtr = (OBJECT_ALPHA_NODE *) thePattern;
ClearObjectPatternMatches(theEnv,alphaPtr);
/*========================================================*/
/* Unmark the classes to which the pattern is applicable */
/* and unmark the class and slot id maps so that they can */
/* become ephemeral. */
/*========================================================*/
MarkBitMapClassesBusy(theEnv,alphaPtr->classbmp,-1);
DeleteClassBitMap(theEnv,alphaPtr->classbmp);
if (alphaPtr->slotbmp != NULL)
{ DecrementBitMapCount(theEnv,alphaPtr->slotbmp); }
/*=========================================*/
/* Only continue deleting this pattern if */
/* this is the last alpha memory attached. */
/*=========================================*/
prv = NULL;
terminalPtr = ObjectNetworkTerminalPointer(theEnv);
while (terminalPtr != alphaPtr)
{
prv = terminalPtr;
terminalPtr = terminalPtr->nxtTerminal;
}
if (prv == NULL)
{ SetObjectNetworkTerminalPointer(theEnv,terminalPtr->nxtTerminal); }
else
{ prv->nxtTerminal = terminalPtr->nxtTerminal; }
prv = NULL;
terminalPtr = alphaPtr->patternNode->alphaNode;
while (terminalPtr != alphaPtr)
{
prv = terminalPtr;
terminalPtr = terminalPtr->nxtInGroup;
}
if (prv == NULL)
{
if (alphaPtr->nxtInGroup != NULL)
{
alphaPtr->patternNode->alphaNode = alphaPtr->nxtInGroup;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
return;
}
}
else
{
prv->nxtInGroup = alphaPtr->nxtInGroup;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
return;
}
alphaPtr->patternNode->alphaNode = NULL;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
upperLevel = alphaPtr->patternNode;
if (upperLevel->nextLevel != NULL)
return;
/*==============================================================*/
/* Loop until all appropriate pattern nodes have been detached. */
/*==============================================================*/
while (upperLevel != NULL)
{
if ((upperLevel->leftNode == NULL) &&
(upperLevel->rightNode == NULL))
{
/*===============================================*/
/* Pattern node is the only node on this level. */
/* Remove it and continue detaching other nodes */
/* above this one, because no other patterns are */
/* dependent upon this node. */
/*===============================================*/
patternPtr = upperLevel;
upperLevel = patternPtr->lastLevel;
if (upperLevel == NULL)
SetObjectNetworkPointer(theEnv,NULL);
else
{
if (upperLevel->selector)
{ RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->nextLevel = NULL;
if (upperLevel->alphaNode != NULL)
upperLevel = NULL;
}
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
}
else if (upperLevel->leftNode != NULL)
{
/*====================================================*/
/* Pattern node has another pattern node which must */
/* be checked preceding it. Remove the pattern node, */
/* but do not detach any nodes above this one. */
/*====================================================*/
patternPtr = upperLevel;
if ((patternPtr->lastLevel != NULL) &&
(patternPtr->lastLevel->selector))
{ RemoveHashedPatternNode(theEnv,patternPtr->lastLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->leftNode->rightNode = upperLevel->rightNode;
if (upperLevel->rightNode != NULL)
{ upperLevel->rightNode->leftNode = upperLevel->leftNode; }
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
upperLevel = NULL;
}
else
{
/*====================================================*/
/* Pattern node has no pattern node preceding it, but */
/* does have one succeeding it. Remove the pattern */
/* node, but do not detach any nodes above this one. */
/*====================================================*/
patternPtr = upperLevel;
upperLevel = upperLevel->lastLevel;
if (upperLevel == NULL)
{ SetObjectNetworkPointer(theEnv,patternPtr->rightNode); }
else
{
if (upperLevel->selector)
{ RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->nextLevel = patternPtr->rightNode;
}
patternPtr->rightNode->leftNode = NULL;
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
upperLevel = NULL;
}
}
}
/***************************************************
NAME : ClearObjectPatternMatches
DESCRIPTION : Removes a pattern node alpha memory
from the list of partial matches
on all instances (active or
garbage collected)
INPUTS : The pattern node to remove
RETURNS : Nothing useful
SIDE EFFECTS : Pattern alpha memory removed
from all object partial match lists
NOTES : Used when a pattern is removed
***************************************************/
static void ClearObjectPatternMatches(
void *theEnv,
OBJECT_ALPHA_NODE *alphaPtr)
{
INSTANCE_TYPE *ins;
IGARBAGE *igrb;
/* =============================================
Loop through every active and queued instance
============================================= */
ins = InstanceData(theEnv)->InstanceList;
while (ins != NULL)
{
RemoveObjectPartialMatches(theEnv,(INSTANCE_TYPE *) ins,(struct patternNodeHeader *) alphaPtr);
ins = ins->nxtList;
}
/* ============================
Check for garbaged instances
============================ */
igrb = InstanceData(theEnv)->InstanceGarbageList;
while (igrb != NULL)
{
RemoveObjectPartialMatches(theEnv,(INSTANCE_TYPE *) igrb->ins,(struct patternNodeHeader *) alphaPtr);
igrb = igrb->nxt;
}
}
/***************************************************
NAME : RemoveObjectPartialMatches
DESCRIPTION : Removes a partial match from a
list of partial matches for
an instance
INPUTS : 1) The instance
2) The pattern node header
corresponding to the match
RETURNS : Nothing useful
SIDE EFFECTS : Match removed
NOTES : None
***************************************************/
static void RemoveObjectPartialMatches(
void *theEnv,
INSTANCE_TYPE *ins,
struct patternNodeHeader *phead)
{
struct patternMatch *match_before, *match_ptr;
match_before = NULL;
match_ptr = (struct patternMatch *) ins->partialMatchList;
/* =======================================
Loop through every match for the object
======================================= */
while (match_ptr != NULL)
{
if (match_ptr->matchingPattern == phead)
{
ins->busy--;
if (match_before == NULL)
{
ins->partialMatchList = (void *) match_ptr->next;
rtn_struct(theEnv,patternMatch,match_ptr);
match_ptr = (struct patternMatch *) ins->partialMatchList;
}
else
{
match_before->next = match_ptr->next;
rtn_struct(theEnv,patternMatch,match_ptr);
match_ptr = match_before->next;
}
}
else
{
match_before = match_ptr;
match_ptr = match_ptr->next;
}
}
}
/******************************************************
NAME : CheckDuplicateSlots
DESCRIPTION : Determines if a restriction has
already been defined in a pattern
INPUTS : The list of already built restrictions
RETURNS : TRUE if a definition already
exists, FALSE otherwise
SIDE EFFECTS : An error message is printed if a
duplicate is found
NOTES : None
******************************************************/
static intBool CheckDuplicateSlots(
void *theEnv,
struct lhsParseNode *nodeList,
SYMBOL_HN *slotName)
{
while (nodeList != NULL)
{
if (nodeList->slot == slotName)
{
PrintErrorID(theEnv,"OBJRTBLD",4,TRUE);
EnvPrintRouter(theEnv,WERROR,"Multiple restrictions on attribute ");
EnvPrintRouter(theEnv,WERROR,ValueToString(slotName));
EnvPrintRouter(theEnv,WERROR," not allowed.\n");
return(TRUE);
}
nodeList = nodeList->right;
}
return(FALSE);
}
/**********************************************************
NAME : ParseClassRestriction
DESCRIPTION : Parses the single-field constraint
on the class an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
RETURNS : The intermediate pattern nodes
representing the class constraint
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes allocated
NOTES : None
**********************************************************/
static struct lhsParseNode *ParseClassRestriction(
void *theEnv,
const char *readSource,
struct token *theToken)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *rln;
CONSTRAINT_RECORD *rv;
rv = GetConstraintRecord(theEnv);
rv->anyAllowed = 0;
rv->symbolsAllowed = 1;
rln = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,FALSE,rln,ISA_ID,rv,0);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,rv);
return(NULL);
}
if ((theToken->type != RPAREN) ||
(tmpNode->type == MF_WILDCARD) ||
(tmpNode->type == MF_VARIABLE))
{
PPBackup(theEnv);
if (theToken->type != RPAREN)
{
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
}
SyntaxErrorMessage(theEnv,"class restriction in object pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,rv);
return(NULL);
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/**********************************************************
NAME : ParseNameRestriction
DESCRIPTION : Parses the single-field constraint
on the name of an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
RETURNS : The intermediate pattern nodes
representing the name constraint
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes allocated
NOTES : None
**********************************************************/
static struct lhsParseNode *ParseNameRestriction(
void *theEnv,
const char *readSource,
struct token *theToken)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *rln;
CONSTRAINT_RECORD *rv;
rv = GetConstraintRecord(theEnv);
rv->anyAllowed = 0;
rv->instanceNamesAllowed = 1;
rln = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,FALSE,rln,NAME_ID,rv,0);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,rv);
return(NULL);
}
if ((theToken->type != RPAREN) ||
(tmpNode->type == MF_WILDCARD) ||
(tmpNode->type == MF_VARIABLE))
{
PPBackup(theEnv);
if (theToken->type != RPAREN)
{
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
}
SyntaxErrorMessage(theEnv,"name restriction in object pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,rv);
return(NULL);
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/***************************************************
NAME : ParseSlotRestriction
DESCRIPTION : Parses the field constraint(s)
on a slot of an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
3) Constraint record holding the
unioned constraints of all the
slots which could match the
slot pattern
4) A flag indicating if any
multifield slots match the name
RETURNS : The intermediate pattern nodes
representing the slot constraint(s)
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes
allocated
NOTES : None
***************************************************/
static struct lhsParseNode *ParseSlotRestriction(
void *theEnv,
const char *readSource,
struct token *theToken,
CONSTRAINT_RECORD *slotConstraints,
int multip)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *slotName;
slotName = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,multip,slotName,FindSlotNameID(theEnv,slotName),
slotConstraints,1);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,slotConstraints);
return(NULL);
}
if (theToken->type != RPAREN)
{
PPBackup(theEnv);
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
SyntaxErrorMessage(theEnv,"object slot pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,slotConstraints);
return(NULL);
}
if ((tmpNode->bottom == NULL) && (tmpNode->multifieldSlot))
{
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,")");
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/********************************************************
NAME : NewClassBitMap
DESCRIPTION : Creates a new bitmap large enough
to hold all ids of classes in the
system and initializes all the bits
to zero or one.
INPUTS : 1) The maximum id that will be set
in the bitmap
2) An integer code indicating if all
the bits are to be set to zero or one
RETURNS : The new bitmap
SIDE EFFECTS : BitMap allocated and initialized
NOTES : None
********************************************************/
static CLASS_BITMAP *NewClassBitMap(
void *theEnv,
int maxid,
int set)
{
register CLASS_BITMAP *bmp;
unsigned size;
if (maxid == -1)
maxid = 0;
size = sizeof(CLASS_BITMAP) +
(sizeof(char) * (maxid / BITS_PER_BYTE));
bmp = (CLASS_BITMAP *) gm2(theEnv,size);
ClearBitString((void *) bmp,size);
bmp->maxid = (unsigned short) maxid;
InitializeClassBitMap(theEnv,bmp,set);
return(bmp);
}
/***********************************************************
NAME : InitializeClassBitMap
DESCRIPTION : Initializes a bitmap to all zeroes or ones.
INPUTS : 1) The bitmap
2) An integer code indicating if all
the bits are to be set to zero or one
RETURNS : Nothing useful
SIDE EFFECTS : The bitmap is initialized
NOTES : None
***********************************************************/
static void InitializeClassBitMap(
void *theEnv,
CLASS_BITMAP *bmp,
int set)
{
register int i,bytes;
DEFCLASS *cls;
struct defmodule *currentModule;
bytes = bmp->maxid / BITS_PER_BYTE + 1;
while (bytes > 0)
{
bmp->map[bytes - 1] = (char) 0;
bytes--;
}
if (set)
{
currentModule = ((struct defmodule *) EnvGetCurrentModule(theEnv));
for (i = 0 ; i <= (int) bmp->maxid ; i++)
{
cls = DefclassData(theEnv)->ClassIDMap[i];
if ((cls != NULL) ? DefclassInScope(theEnv,cls,currentModule) : FALSE)
{
if (cls->reactive && (cls->abstract == 0))
SetBitMap(bmp->map,i);
}
}
}
}
/********************************************
NAME : DeleteIntermediateClassBitMap
DESCRIPTION : Deallocates a bitmap
INPUTS : The class set
RETURNS : Nothing useful
SIDE EFFECTS : Class set deallocated
NOTES : None
********************************************/
static void DeleteIntermediateClassBitMap(
void *theEnv,
CLASS_BITMAP *bmp)
{
rm(theEnv,(void *) bmp,ClassBitMapSize(bmp));
}
/******************************************************
NAME : CopyClassBitMap
DESCRIPTION : Increments the in use count of a
bitmap and returns the same pointer
INPUTS : The bitmap
RETURNS : The bitmap
SIDE EFFECTS : Increments the in use count
NOTES : Class sets are shared by multiple
copies of an object pattern within an
OR CE. The use count prevents having
to make duplicate copies of the bitmap
******************************************************/
static void *CopyClassBitMap(
void *theEnv,
void *gset)
{
if (gset != NULL)
IncrementBitMapCount(gset);
return(gset);
}
/**********************************************************
NAME : DeleteClassBitMap
DESCRIPTION : Deallocates a bitmap,
and decrements the busy flags of the
classes marked in the bitmap
INPUTS : The bitmap
RETURNS : Nothing useful
SIDE EFFECTS : Class set deallocated and classes unmarked
NOTES : None
**********************************************************/
static void DeleteClassBitMap(
void *theEnv,
void *gset)
{
if (gset == NULL)
return;
DecrementBitMapCount(theEnv,(BITMAP_HN *) gset);
}
/***************************************************
NAME : MarkBitMapClassesBusy
DESCRIPTION : Increments/Decrements busy counts
of all classes marked in a bitmap
INPUTS : 1) The bitmap hash node
2) 1 or -1 (to increment or
decrement class busy counts)
RETURNS : Nothing useful
SIDE EFFECTS : Bitmap class busy counts updated
NOTES : None
***************************************************/
static void MarkBitMapClassesBusy(
void *theEnv,
BITMAP_HN *bmphn,
int offset)
{
register CLASS_BITMAP *bmp;
register unsigned short i;
register DEFCLASS *cls;
/* ====================================
If a clear is in progress, we do not
have to worry about busy counts
==================================== */
if (ConstructData(theEnv)->ClearInProgress)
return;
bmp = (CLASS_BITMAP *) ValueToBitMap(bmphn);
for (i = 0 ; i <= bmp->maxid ; i++)
if (TestBitMap(bmp->map,i))
{
cls = DefclassData(theEnv)->ClassIDMap[i];
cls->busy += (unsigned int) offset;
}
}
/****************************************************
NAME : EmptyClassBitMap
DESCRIPTION : Determines if one or more bits
are marked in a bitmap
INPUTS : The bitmap
RETURNS : TRUE if the set has no bits
marked, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
****************************************************/
static intBool EmptyClassBitMap(
CLASS_BITMAP *bmp)
{
register unsigned short bytes;
bytes = (unsigned short) (bmp->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
if (bmp->map[bytes - 1] != (char) 0)
return(FALSE);
bytes--;
}
return(TRUE);
}
/***************************************************
NAME : IdenticalClassBitMap
DESCRIPTION : Determines if two bitmaps
are identical
INPUTS : 1) First bitmap
2) Second bitmap
RETURNS : TRUE if bitmaps are the same,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
static intBool IdenticalClassBitMap(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register int i;
if (cs1->maxid != cs2->maxid)
return(FALSE);
for (i = 0 ; i < (int) (cs1->maxid / BITS_PER_BYTE + 1) ; i++)
if (cs1->map[i] != cs2->map[i])
return(FALSE);
return(TRUE);
}
/*****************************************************************
NAME : ProcessClassRestriction
DESCRIPTION : Examines a class restriction and forms a bitmap
corresponding to the maximal set of classes which
can satisfy a static analysis of the restriction
INPUTS : 1) The bitmap to mark classes in
2) The lhsParseNodes of the restriction
3) A flag indicating if this is the first
non-recursive call or not
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Class bitmap set and lhsParseNodes corressponding
to constant restrictions are removed
NOTES : None
*****************************************************************/
static intBool ProcessClassRestriction(
void *theEnv,
CLASS_BITMAP *clsset,
struct lhsParseNode **classRestrictions,
int recursiveCall)
{
register struct lhsParseNode *chk,**oraddr;
CLASS_BITMAP *tmpset1,*tmpset2;
int constant_restriction = TRUE;
if (*classRestrictions == NULL)
{
if (recursiveCall)
InitializeClassBitMap(theEnv,clsset,1);
return(TRUE);
}
/* ===============================================
Determine the corresponding class set and union
it with the current total class set. If an AND
restriction is comprised entirely of symbols,
it can be removed
=============================================== */
tmpset1 = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
tmpset2 = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,0);
for (chk = *classRestrictions ; chk != NULL ; chk = chk->right)
{
if (chk->type == SYMBOL)
{
chk->value = (void *) LookupDefclassInScope(theEnv,ValueToString(chk->value));
if (chk->value == NULL)
{
PrintErrorID(theEnv,"OBJRTBLD",5,FALSE);
EnvPrintRouter(theEnv,WERROR,"Undefined class in object pattern.\n");
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
return(FALSE);
}
if (chk->negated)
{
InitializeClassBitMap(theEnv,tmpset2,1);
MarkBitMapSubclasses(tmpset2->map,(DEFCLASS *) chk->value,0);
}
else
{
InitializeClassBitMap(theEnv,tmpset2,0);
MarkBitMapSubclasses(tmpset2->map,(DEFCLASS *) chk->value,1);
}
IntersectClassBitMaps(tmpset1,tmpset2);
}
else
constant_restriction = FALSE;
}
if (EmptyClassBitMap(tmpset1))
{
PrintErrorID(theEnv,"OBJRTBLD",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy ");
EnvPrintRouter(theEnv,WERROR,"is-a restriction in object pattern.\n");
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
return(FALSE);
}
if (constant_restriction)
{
chk = *classRestrictions;
*classRestrictions = chk->bottom;
chk->bottom = NULL;
ReturnLHSParseNodes(theEnv,chk);
oraddr = classRestrictions;
}
else
oraddr = &(*classRestrictions)->bottom;
UnionClassBitMaps(clsset,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
/* =====================================
Process the next OR class restriction
===================================== */
return(ProcessClassRestriction(theEnv,clsset,oraddr,FALSE));
}
/****************************************************************
NAME : ProcessSlotRestriction
DESCRIPTION : Determines which slots could match the slot
pattern and determines the union of all
constraints for the pattern
INPUTS : 1) The class set
2) The slot name
3) A buffer to hold a flag indicating if
any multifield slots are found w/ this name
RETURNS : A union of the constraints on all the slots
which could match the slots (NULL if no
slots found)
SIDE EFFECTS : The class bitmap set is marked/cleared
NOTES : None
****************************************************************/
static CONSTRAINT_RECORD *ProcessSlotRestriction(
void *theEnv,
CLASS_BITMAP *clsset,
SYMBOL_HN *slotName,
int *multip)
{
register DEFCLASS *cls;
register int si;
CONSTRAINT_RECORD *totalConstraints = NULL,*tmpConstraints;
register unsigned i;
*multip = FALSE;
for (i = 0 ; i < CLASS_TABLE_HASH_SIZE ; i++)
for (cls = DefclassData(theEnv)->ClassTable[i] ; cls != NULL ; cls = cls->nxtHash)
{
if (TestBitMap(clsset->map,cls->id))
{
si = FindInstanceTemplateSlot(theEnv,cls,slotName);
if ((si != -1) ? cls->instanceTemplate[si]->reactive : FALSE)
{
if (cls->instanceTemplate[si]->multiple)
*multip = TRUE;
tmpConstraints =
UnionConstraints(theEnv,cls->instanceTemplate[si]->constraint,totalConstraints);
RemoveConstraint(theEnv,totalConstraints);
totalConstraints = tmpConstraints;
}
else
ClearBitMap(clsset->map,cls->id);
}
}
return(totalConstraints);
}
/****************************************************
NAME : IntersectClassBitMaps
DESCRIPTION : Bitwise-ands two bitmaps and stores
the result in the first
INPUTS : The two bitmaps
RETURNS : Nothing useful
SIDE EFFECTS : ClassBitMaps anded
NOTES : Assumes the first bitmap is at least
as large as the second
****************************************************/
static void IntersectClassBitMaps(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register unsigned short bytes;
bytes = (unsigned short) (cs2->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
cs1->map[bytes - 1] &= cs2->map[bytes - 1];
bytes--;
}
}
/****************************************************
NAME : UnionClassBitMaps
DESCRIPTION : Bitwise-ors two bitmaps and stores
the result in the first
INPUTS : The two bitmaps
RETURNS : Nothing useful
SIDE EFFECTS : ClassBitMaps ored
NOTES : Assumes the first bitmap is at least
as large as the second
****************************************************/
static void UnionClassBitMaps(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register unsigned short bytes;
bytes = (unsigned short) (cs2->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
cs1->map[bytes - 1] |= cs2->map[bytes - 1];
bytes--;
}
}
/*****************************************************
NAME : PackClassBitMap
DESCRIPTION : This routine packs a bitmap
bitmap such that at least one of
the bits in the rightmost byte is
set (i.e. the bitmap takes up
the smallest space possible).
INPUTS : The bitmap
RETURNS : The new (packed) bitmap
SIDE EFFECTS : The oldset is deallocated
NOTES : None
*****************************************************/
static CLASS_BITMAP *PackClassBitMap(
void *theEnv,
CLASS_BITMAP *oldset)
{
register unsigned short newmaxid;
CLASS_BITMAP *newset;
for (newmaxid = oldset->maxid ; newmaxid > 0 ; newmaxid--)
if (TestBitMap(oldset->map,newmaxid))
break;
if (newmaxid != oldset->maxid)
{
newset = NewClassBitMap(theEnv,(int) newmaxid,0);
GenCopyMemory(char,newmaxid / BITS_PER_BYTE + 1,newset->map,oldset->map);
DeleteIntermediateClassBitMap(theEnv,oldset);
}
else
newset = oldset;
return(newset);
}
/*****************************************************************
NAME : FilterObjectPattern
DESCRIPTION : Appends an extra node to hold the bitmap,
and finds is-a and name nodes
INPUTS : 1) The object pattern parser address
to give to a default is-a slot
2) The unfiltered slot list
3) A buffer to hold the address of
the class bitmap restriction node
4) A buffer to hold the address of
the is-a restriction node
4) A buffer to hold the address of
the name restriction node
RETURNS : The filtered slot list
SIDE EFFECTS : clsset is attached to extra slot pattern
Pointers to the is-a and name slots are also
stored (if they exist) for easy reference
NOTES : None
*****************************************************************/
static struct lhsParseNode *FilterObjectPattern(
void *theEnv,
struct patternParser *selfPatternType,
struct lhsParseNode *unfilteredSlots,
struct lhsParseNode **bitmap_slot,
struct lhsParseNode **isa_slot,
struct lhsParseNode **name_slot)
{
struct lhsParseNode *prv,*cur;
*isa_slot = NULL;
*name_slot = NULL;
/* ============================================
Create a dummy node to attach to the end
of the pattern which holds the class bitmap.
============================================ */
*bitmap_slot = GetLHSParseNode(theEnv);
(*bitmap_slot)->type = SF_WILDCARD;
(*bitmap_slot)->slot = DefclassData(theEnv)->ISA_SYMBOL;
(*bitmap_slot)->slotNumber = ISA_ID;
(*bitmap_slot)->index = 1;
(*bitmap_slot)->patternType = selfPatternType;
(*bitmap_slot)->userData = unfilteredSlots->userData;
unfilteredSlots->userData = NULL;
/* ========================
Find is-a and name nodes
======================== */
prv = NULL;
cur = unfilteredSlots;
while (cur != NULL)
{
if (cur->slot == DefclassData(theEnv)->ISA_SYMBOL)
*isa_slot = cur;
else if (cur->slot == DefclassData(theEnv)->NAME_SYMBOL)
*name_slot = cur;
prv = cur;
cur = cur->right;
}
/* ================================
Add the class bitmap conditional
element to end of pattern
================================ */
if (prv == NULL)
unfilteredSlots = *bitmap_slot;
else
prv->right = *bitmap_slot;
return(unfilteredSlots);
}
/***************************************************
NAME : FormSlotBitMap
DESCRIPTION : Examines an object pattern and
forms a minimal bitmap marking
the ids of the slots used in
the pattern
INPUTS : The intermediate parsed pattern
RETURNS : The new slot bitmap (can be NULL)
SIDE EFFECTS : Bitmap created and added to hash
table - corresponding bits set
for ids of slots used in pattern
NOTES : None
***************************************************/
static BITMAP_HN *FormSlotBitMap(
void *theEnv,
struct lhsParseNode *thePattern)
{
struct lhsParseNode *node;
int maxSlotID = -1;
unsigned size;
SLOT_BITMAP *bmp;
BITMAP_HN *hshBmp;
/* =======================================
Find the largest slot id in the pattern
======================================= */
for (node = thePattern ; node != NULL ; node = node->right)
if (node->slotNumber > maxSlotID)
maxSlotID = node->slotNumber;
/* ===================================================
If the pattern contains no slot tests or only tests
on the class or name (which do not change) do not
store a slot bitmap
=================================================== */
if ((maxSlotID == ISA_ID) || (maxSlotID == NAME_ID))
return(NULL);
/* ===================================
Initialize the bitmap to all zeroes
=================================== */
size = (sizeof(SLOT_BITMAP) +
(sizeof(char) * (maxSlotID / BITS_PER_BYTE)));
bmp = (SLOT_BITMAP *) gm2(theEnv,size);
ClearBitString((void *) bmp,size);
bmp->maxid = (unsigned short) maxSlotID;
/* ============================================
Add (retrieve) a bitmap to (from) the bitmap
hash table which has a corresponding bit set
for the id of every slot used in the pattern
============================================ */
for (node = thePattern ; node != NULL ; node = node->right)
SetBitMap(bmp->map,node->slotNumber);
hshBmp = (BITMAP_HN *) EnvAddBitMap(theEnv,(void *) bmp,SlotBitMapSize(bmp));
rm(theEnv,(void *) bmp,size);
return(hshBmp);
}
/****************************************************
NAME : RemoveSlotExistenceTests
DESCRIPTION : Removes slot existence test since
these are accounted for by class
bitmap or name slot.
INPUTS : 1) The intermediate pattern nodes
2) A buffer to hold the class bitmap
RETURNS : The filtered list
SIDE EFFECTS : Slot existence tests removed
NOTES : None
****************************************************/
static struct lhsParseNode *RemoveSlotExistenceTests(
void *theEnv,
struct lhsParseNode *thePattern,
BITMAP_HN **bmp)
{
struct lhsParseNode *tempPattern = thePattern;
struct lhsParseNode *lastPattern = NULL, *head = thePattern;
while (tempPattern != NULL)
{
/* ==========================================
Remember the class bitmap for this pattern
========================================== */
if (tempPattern->userData != NULL)
{
*bmp = (BITMAP_HN *) tempPattern->userData;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* ===========================================================
A single field slot that has no pattern network expression
associated with it can be removed (i.e. any value contained
in this slot will satisfy the pattern being matched).
=========================================================== */
else if (((tempPattern->type == SF_WILDCARD) ||
(tempPattern->type == SF_VARIABLE)) &&
(tempPattern->networkTest == NULL))
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
/* =====================================================
A multifield variable or wildcard within a multifield
slot can be removed if there are no other multifield
variables or wildcards contained in the same slot
(and the multifield has no expressions which must be
evaluated in the fact pattern network).
===================================================== */
else if (((tempPattern->type == MF_WILDCARD) || (tempPattern->type == MF_VARIABLE)) &&
(tempPattern->multifieldSlot == FALSE) &&
(tempPattern->networkTest == NULL) &&
(tempPattern->multiFieldsBefore == 0) &&
(tempPattern->multiFieldsAfter == 0))
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
/* ================================================================
A multifield wildcard or variable contained in a multifield slot
that contains no other multifield wildcards or variables, but
does have an expression that must be evaluated, can be changed
to a single field pattern node with the same expression.
================================================================ */
else if (((tempPattern->type == MF_WILDCARD) || (tempPattern->type == MF_VARIABLE)) &&
(tempPattern->multifieldSlot == FALSE) &&
(tempPattern->networkTest != NULL) &&
(tempPattern->multiFieldsBefore == 0) &&
(tempPattern->multiFieldsAfter == 0))
{
tempPattern->type = SF_WILDCARD;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* =======================================================
If we're dealing with a multifield slot with no slot
restrictions, then treat the multfield slot as a single
field slot, but attach a test which verifies that the
slot contains a zero length multifield value.
======================================================= */
else if ((tempPattern->type == MF_WILDCARD) &&
(tempPattern->multifieldSlot == TRUE) &&
(tempPattern->bottom == NULL))
{
tempPattern->type = SF_WILDCARD;
GenObjectZeroLengthTest(theEnv,tempPattern);
tempPattern->multifieldSlot = FALSE;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* ======================================================
Recursively call RemoveSlotExistenceTests for the slot
restrictions contained within a multifield slot.
====================================================== */
else if ((tempPattern->type == MF_WILDCARD) &&
(tempPattern->multifieldSlot == TRUE))
{
/* =====================================================
Add an expression to the first pattern restriction in
the multifield slot that determines whether or not
the fact's slot value contains the minimum number of
required fields to satisfy the pattern restrictions
for this slot. The length check is place before any
other tests, so that preceeding checks do not have to
determine if there are enough fields in the slot to
safely retrieve a value.
===================================================== */
GenObjectLengthTest(theEnv,tempPattern->bottom);
/* =======================================================
Remove any unneeded pattern restrictions from the slot.
======================================================= */
tempPattern->bottom = RemoveSlotExistenceTests(theEnv,tempPattern->bottom,bmp);
/* =========================================================
If the slot no longer contains any restrictions, then the
multifield slot can be completely removed. In any case,
move on to the next slot to be examined for removal.
========================================================= */
if (tempPattern->bottom == NULL)
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
else
{
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
}
/* =====================================================
If none of the other tests for removing slots or slot
restrictions apply, then move on to the next slot or
slot restriction to be tested.
===================================================== */
else
{
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
}
/* ====================================
Return the pattern with unused slots
and slot restrictions removed.
==================================== */
return(head);
}
/***************************************************
NAME : CreateInitialObjectPattern
DESCRIPTION : Creates a default object pattern
for use in defrules
INPUTS : None
RETURNS : The default initial pattern
SIDE EFFECTS : Pattern created
NOTES : The pattern created is:
(object (is-a INITIAL-OBJECT)
(name [initial-object]))
***************************************************/
static struct lhsParseNode *CreateInitialObjectPattern(
void *theEnv)
{
struct lhsParseNode *topNode;
CLASS_BITMAP *clsset;
int initialObjectClassID;
initialObjectClassID = LookupDefclassInScope(theEnv,INITIAL_OBJECT_CLASS_NAME)->id;
clsset = NewClassBitMap(theEnv,initialObjectClassID,0);
SetBitMap(clsset->map,initialObjectClassID);
clsset = PackClassBitMap(theEnv,clsset);
topNode = GetLHSParseNode(theEnv);
topNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(topNode->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
topNode->type = SF_WILDCARD;
topNode->index = 1;
topNode->slot = DefclassData(theEnv)->NAME_SYMBOL;
topNode->slotNumber = NAME_ID;
topNode->bottom = GetLHSParseNode(theEnv);
topNode->bottom->type = INSTANCE_NAME;
topNode->bottom->value = (void *) DefclassData(theEnv)->INITIAL_OBJECT_SYMBOL;
return(topNode);
}
/**************************************************************
NAME : ObjectMatchDelayParse
DESCRIPTION : Parses the object-pattern-match-delay function
INPUTS : 1) The function call expression
2) The logical name of the input source
RETURNS : The top expression with the other
action expressions attached
SIDE EFFECTS : Parses the function call and attaches
the appropriate arguments to the
top node
NOTES : None
**************************************************************/
static EXPRESSION *ObjectMatchDelayParse(
void *theEnv,
struct expr *top,
const char *infile)
{
struct token tkn;
IncrementIndentDepth(theEnv,3);
PPCRAndIndent(theEnv);
top->argList = GroupActions(theEnv,infile,&tkn,TRUE,NULL,FALSE);
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,tkn.printForm);
DecrementIndentDepth(theEnv,3);
if (top->argList == NULL)
{
ReturnExpression(theEnv,top);
return(NULL);
}
return(top);
}
/***************************************************
NAME : MarkObjectPtnIncrementalReset
DESCRIPTION : Marks/unmarks an object pattern for
incremental reset
INPUTS : 1) The object pattern alpha node
2) The value to which to set the
incremental reset flag
RETURNS : Nothing useful
SIDE EFFECTS : The pattern node is set/unset
NOTES : The pattern node can only be
set if it is a new node and
thus marked for initialization
by PlaceObjectPattern
***************************************************/
static void MarkObjectPtnIncrementalReset(
void *theEnv,
struct patternNodeHeader *thePattern,
int value)
{
if (thePattern->initialize == FALSE)
return;
thePattern->initialize = value;
}
/***********************************************************
NAME : ObjectIncrementalReset
DESCRIPTION : Performs an assert for all instances in the
system. All new patterns in the pattern
network from the new rule have been marked
as needing processing. Old patterns will
be ignored.
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : All objects driven through new patterns
NOTES : None
***********************************************************/
static void ObjectIncrementalReset(
void *theEnv)
{
INSTANCE_TYPE *ins;
for (ins = InstanceData(theEnv)->InstanceList ; ins != NULL ; ins = ins->nxtList)
ObjectNetworkAction(theEnv,OBJECT_ASSERT,(INSTANCE_TYPE *) ins,-1);
}
#endif
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSLoopBuilder.h
|
<gh_stars>1-10
#ifndef _loop_builder_h
#define _loop_builder_h
#include "ExpertSystem/CLIPSObjectBuilder.h"
#include "llvm/Analysis/LoopInfo.h"
class CLIPSLoopBuilder : public CLIPSObjectBuilder {
public:
CLIPSLoopBuilder(std::string nm, FunctionNamer& namer);
void addFields(Loop* loop, KnowledgeConstructor *kc, char* parent);
void build(Loop* loop, KnowledgeConstructor *kc, char* parent);
};
#endif
|
DrItanium/durandal
|
include/maya/libmaya.h
|
/*
maya
Copyright (c) 2012-2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _LIBMAYA_H
#define _LIBMAYA_H
extern void MayaDefinitions(void* theEnv);
#if FILE_SYSTEM_ROOTING
#define FILE_SYSTEM_ROOT_DATA USER_ENVIRONMENT_DATA + 0
typedef struct FileSystemRootData {
int rootingenabled;
char* root;
int stringlength;
int issymbol;
} FileSystemRootData;
#define FileSystemRootData(theEnv) \
((struct FileSystemRootData*) GetEnvironmentData(theEnv, FILE_SYSTEM_ROOT_DATA))
extern void DefineFSOverrideFunctions(void* theEnv);
extern int FS_RemoveFunction(void*);
extern int FS_RenameFunction(void*);
#endif /* FILE_SYSTEM_ROOTING */
#if BINARY_LOGICAL_OPERATIONS
extern void BinaryOperationsFunctionDefinitions(void *theEnv);
#endif /* BINARY_LOGICAL_OPERATIONS */
/* THIS SHOULD ALWAYS BE LAST SINCE IT HAS A TON OF CODE! */
#if ARCHITECTURE_IDENTIFICATION
/* architecture define macros */
#if defined(__theoretical__)
#define ARCH_THEORETICAL 1
#define ARCH_STRING "theoretical"
#else
#define ARCH_THEORETICAL 0
#endif
#if defined(__alpha__)
#define ARCH_ALPHA 1
#define ARCH_STRING "alpha"
#else
#define ARCH_ALPHA 0
#endif
#if defined(__i386__) || defined(i386) || defined(__i386) || defined(_M_IX86) \
|| defined(_X86_) || defined(_i386) || defined(__X86__)
#define ARCH_X86_32 1
#define ARCH_STRING "x86_32"
#else
#define ARCH_X86_32 0
#endif
#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || \
defined(__amd64__) || defined(__amd64) || defined(__x86_64)
#define ARCH_X86_64 1
#define ARCH_STRING "x86_64"
#else
#define ARCH_X86_64 0
#endif
#if defined(__sparc__)
#define ARCH_SPARC 1
#define ARCH_STRING "sparc"
#else
#define ARCH_SPARC 0
#endif
#if defined(__ia64__) || defined(_IA64) || defined(__IA64__) || defined(__ia64) \
|| defined(_M_IA64) || defined(__itanium__)
#define ARCH_ITANIUM 1
#define ARCH_STRING "Itanium"
#else
#define ARCH_ITANIUM 0
#endif
#if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
defined(__POWERPC__) || defined(_M_PPC) || defined(_ARCH_PPC)
#define ARCH_POWERPC_32 1
#define ARCH_STRING "powerpc32"
#else
#define ARCH_POWERPC_32 0
#endif
#if defined(__ppc64__)
#define ARCH_POWERPC_64 1
#define ARCH_STRING "powerpc64"
#else
#define ARCH_POWERPC_64 0
#endif
#if defined(__arm__)
#define ARCH_ARM 1
#define ARCH_STRING "arm32"
#else
#define ARCH_ARM 0
#endif
#if defined(__aarch64__)
#define ARCH_ARM64 1
#define ARCH_STRING "arm64"
#else
#define ARCH_ARM64 0
#endif
#if defined(__hppa__) || defined(_hppa)
#define ARCH_HPPA 1
#define ARCH_STRING "hppa"
#else
#define ARCH_HPPA 0
#endif
#if defined(__m68k__) || defined(M68000)
#define ARCH_M68K 1
#define ARCH_STRING "m68k"
#else
#define ARCH_M68K 0
#endif
#if defined(__mips__) || defined(__mips) || defined(__MIPS__)
#define ARCH_MIPS 1
#define ARCH_STRING "mips"
#else
#define ARCH_MIPS 0
#endif
#if defined(__sh__)
#define ARCH_SH 1
#define ARCH_STRING "sh"
#else
#define ARCH_SH 0
#endif
#if defined(__s390x__)
#define ARCH_S390X 1
#define ARCH_STRING "s390x"
#else
#define ARCH_S390X 0
#endif
#if (! ARCH_ALPHA) && (! ARCH_X86_32) && (! ARCH_X86_64) && (! ARCH_SPARC) && \
(! ARCH_ITANIUM) && (! ARCH_POWERPC_32) && (! ARCH_POWERPC_32) && (!ARCH_ARM) && \
(! ARCH_ARM64) && (! ARCH_HPPA) && (! ARCH_M68K) && (! ARCH_MIPS) && (!ARCH_SH) && \
(! ARCH_S390X) && (! ARCH_THEORETICAL)
#define ARCH_UNKNOWN 1
#define ARCH_STRING "Unknown"
#else
#define ARCH_UNKNOWN 0
#endif
extern void ArchitectureDetectionFunctionDefinitions(void* theEnv);
#endif /* ARCHITECTURE_IDENTIFICATION */
#endif
|
DrItanium/durandal
|
include/electron/genrccom.h
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/22/14 */
/* */
/* */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* 6.23: Corrected compilation errors for files */
/* generated by constructs-to-c. DR0861 */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Changed integer type/precision. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Fixed linkage issue when DEBUGGING_FUNCTIONS */
/* is set to 0 and PROFILING_FUNCTIONS is set to */
/* 1. */
/* */
/*************************************************************/
#ifndef _H_genrccom
#define _H_genrccom
#ifndef _H_constrct
#include "constrct.h"
#endif
#ifndef _H_cstrccom
#include "cstrccom.h"
#endif
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifndef _H_moduldef
#include "moduldef.h"
#endif
#ifndef _H_genrcfun
#include "genrcfun.h"
#endif
#ifndef _H_symbol
#include "symbol.h"
#endif
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _GENRCCOM_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void SetupGenericFunctions(void *);
LOCALE void *EnvFindDefgeneric(void *,const char *);
LOCALE DEFGENERIC *LookupDefgenericByMdlOrScope(void *,const char *);
LOCALE DEFGENERIC *LookupDefgenericInScope(void *,const char *);
LOCALE void *EnvGetNextDefgeneric(void *,void *);
LOCALE long EnvGetNextDefmethod(void *,void *,long);
LOCALE int EnvIsDefgenericDeletable(void *,void *);
LOCALE int EnvIsDefmethodDeletable(void *,void *,long);
LOCALE void UndefgenericCommand(void *);
LOCALE void *GetDefgenericModuleCommand(void *);
LOCALE void UndefmethodCommand(void *);
LOCALE DEFMETHOD *GetDefmethodPointer(void *,long);
LOCALE intBool EnvUndefgeneric(void *,void *);
LOCALE intBool EnvUndefmethod(void *,void *,long);
#if ! OBJECT_SYSTEM
LOCALE void TypeCommand(void *,DATA_OBJECT *);
#endif
#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS
LOCALE void EnvGetDefmethodDescription(void *,char *,size_t,void *,long);
#endif
#if DEBUGGING_FUNCTIONS
LOCALE unsigned EnvGetDefgenericWatch(void *,void *);
LOCALE void EnvSetDefgenericWatch(void *,unsigned,void *);
LOCALE unsigned EnvGetDefmethodWatch(void *,void *,long);
LOCALE void EnvSetDefmethodWatch(void *,unsigned,void *,long);
LOCALE void PPDefgenericCommand(void *);
LOCALE void PPDefmethodCommand(void *);
LOCALE void ListDefmethodsCommand(void *);
LOCALE const char *EnvGetDefmethodPPForm(void *,void *,long);
LOCALE void ListDefgenericsCommand(void *);
LOCALE void EnvListDefgenerics(void *,const char *,struct defmodule *);
LOCALE void EnvListDefmethods(void *,const char *,void *);
#endif
LOCALE void GetDefgenericListFunction(void *,DATA_OBJECT *);
LOCALE void EnvGetDefgenericList(void *,DATA_OBJECT *,struct defmodule *);
LOCALE void GetDefmethodListCommand(void *,DATA_OBJECT *);
LOCALE void EnvGetDefmethodList(void *,void *,DATA_OBJECT *);
LOCALE void GetMethodRestrictionsCommand(void *,DATA_OBJECT *);
LOCALE void EnvGetMethodRestrictions(void *,void *,long,DATA_OBJECT *);
LOCALE SYMBOL_HN *GetDefgenericNamePointer(void *);
LOCALE void SetNextDefgeneric(void *,void *);
LOCALE const char *EnvDefgenericModule(void *,void *);
LOCALE const char *EnvGetDefgenericName(void *,void *);
LOCALE const char *EnvGetDefgenericPPForm(void *,void *);
LOCALE SYMBOL_HN *EnvGetDefgenericNamePointer(void *,void *);
LOCALE void EnvSetDefgenericPPForm(void *,void *,const char *);
#if ALLOW_ENVIRONMENT_GLOBALS
LOCALE void SetDefgenericPPForm(void *,const char *);
LOCALE const char *DefgenericModule(void *);
LOCALE void *FindDefgeneric(const char *);
LOCALE void GetDefgenericList(DATA_OBJECT *,struct defmodule *);
LOCALE const char *GetDefgenericName(void *);
LOCALE const char *GetDefgenericPPForm(void *);
LOCALE void *GetNextDefgeneric(void *);
LOCALE int IsDefgenericDeletable(void *);
LOCALE intBool Undefgeneric(void *);
LOCALE void GetDefmethodList(void *,DATA_OBJECT_PTR);
LOCALE void GetMethodRestrictions(void *,long,DATA_OBJECT *);
LOCALE long GetNextDefmethod(void *,long );
LOCALE int IsDefmethodDeletable(void *,long );
LOCALE intBool Undefmethod(void *,long );
#if DEBUGGING_FUNCTIONS
LOCALE unsigned GetDefgenericWatch(void *);
LOCALE void ListDefgenerics(const char *,struct defmodule *);
LOCALE void SetDefgenericWatch(unsigned,void *);
LOCALE const char *GetDefmethodPPForm(void *,long);
LOCALE unsigned GetDefmethodWatch(void *,long);
LOCALE void ListDefmethods(const char *,void *);
LOCALE void SetDefmethodWatch(unsigned,void *,long);
#endif /* DEBUGGING_FUNCTIONS */
#if DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS
LOCALE void GetDefmethodDescription(char *,int,void *,long );
#endif /* DEBUGGING_FUNCTIONS || PROFILING_FUNCTIONS */
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_genrccom */
|
DrItanium/durandal
|
include/electron/rulebsc.h
|
<filename>include/electron/rulebsc.h
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/20/14 */
/* */
/* DEFRULE BASIC COMMANDS HEADER FILE */
/*******************************************************/
/*************************************************************/
/* Purpose: Implements core commands for the defrule */
/* construct such as clear, reset, save, undefrule, */
/* ppdefrule, list-defrules, and */
/* get-defrule-list. */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* <NAME> */
/* */
/* Revision History: */
/* */
/* 6.23: Corrected compilation errors for files */
/* generated by constructs-to-c. DR0861 */
/* */
/* Changed name of variable log to logName */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Support for join network changes. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Converted API macros to function calls. */
/* */
/* Added code to prevent a clear command from */
/* being executed during fact assertions via */
/* JoinOperationInProgress mechanism. */
/* */
/*************************************************************/
#ifndef _H_rulebsc
#define _H_rulebsc
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _RULEBSC_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void DefruleBasicCommands(void *);
LOCALE void UndefruleCommand(void *);
LOCALE intBool EnvUndefrule(void *,void *);
LOCALE void GetDefruleListFunction(void *,DATA_OBJECT_PTR);
LOCALE void EnvGetDefruleList(void *,DATA_OBJECT_PTR,void *);
LOCALE void *DefruleModuleFunction(void *);
#if DEBUGGING_FUNCTIONS
LOCALE void PPDefruleCommand(void *);
LOCALE int PPDefrule(void *,const char *,const char *);
LOCALE void ListDefrulesCommand(void *);
LOCALE void EnvListDefrules(void *,const char *,void *);
LOCALE unsigned EnvGetDefruleWatchFirings(void *,void *);
LOCALE unsigned EnvGetDefruleWatchActivations(void *,void *);
LOCALE void EnvSetDefruleWatchFirings(void *,unsigned,void *);
LOCALE void EnvSetDefruleWatchActivations(void *,unsigned,void *);
LOCALE unsigned DefruleWatchAccess(void *,int,unsigned,struct expr *);
LOCALE unsigned DefruleWatchPrint(void *,const char *,int,struct expr *);
#endif
#if ALLOW_ENVIRONMENT_GLOBALS
LOCALE void GetDefruleList(DATA_OBJECT_PTR,void *);
#if DEBUGGING_FUNCTIONS
LOCALE unsigned GetDefruleWatchActivations(void *);
LOCALE unsigned GetDefruleWatchFirings(void *);
LOCALE void ListDefrules(const char *,void *);
LOCALE void SetDefruleWatchActivations(unsigned,void *);
LOCALE void DefruleWatchFirings(unsigned,void *);
#endif
LOCALE intBool Undefrule(void *);
#endif /* ALLOW_ENVIRONMENT_GLOBALS */
#endif /* _H_rulebsc */
|
DrItanium/durandal
|
include/electron/cstrccom.h
|
<filename>include/electron/cstrccom.h<gh_stars>1-10
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/22/14 */
/* */
/* CONSTRUCT COMMAND HEADER MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* Added ConstructsDeletable function. */
/* */
/* 6.30: Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/*************************************************************/
#ifndef _H_cstrccom
#define _H_cstrccom
#ifndef _H_moduldef
#include "moduldef.h"
#endif
#ifndef _H_constrct
#include "constrct.h"
#endif
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _CSTRCCOM_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
#if (! RUN_TIME)
LOCALE void AddConstructToModule(struct constructHeader *);
#endif
LOCALE intBool DeleteNamedConstruct(void *,const char *,struct construct *);
LOCALE void *FindNamedConstruct(void *,const char *,struct construct *);
LOCALE void UndefconstructCommand(void *,const char *,struct construct *);
LOCALE int PPConstruct(void *,const char *,const char *,struct construct *);
LOCALE SYMBOL_HN *GetConstructModuleCommand(void *,const char *,struct construct *);
LOCALE struct defmodule *GetConstructModule(void *,const char *,struct construct *);
LOCALE intBool Undefconstruct(void *,void *,struct construct *);
LOCALE void SaveConstruct(void *,void *,const char *,struct construct *);
LOCALE const char *GetConstructNameString(struct constructHeader *);
LOCALE const char *EnvGetConstructNameString(void *,struct constructHeader *);
LOCALE const char *GetConstructModuleName(struct constructHeader *);
LOCALE SYMBOL_HN *GetConstructNamePointer(struct constructHeader *);
LOCALE void GetConstructListFunction(void *,const char *,DATA_OBJECT_PTR,
struct construct *);
LOCALE void GetConstructList(void *,DATA_OBJECT_PTR,struct construct *,
struct defmodule *);
LOCALE void ListConstructCommand(void *,const char *,struct construct *);
LOCALE void ListConstruct(void *,struct construct *,const char *,struct defmodule *);
LOCALE void SetNextConstruct(struct constructHeader *,struct constructHeader *);
LOCALE struct defmoduleItemHeader *GetConstructModuleItem(struct constructHeader *);
LOCALE const char *GetConstructPPForm(void *,struct constructHeader *);
LOCALE void PPConstructCommand(void *,const char *,struct construct *);
LOCALE struct constructHeader *GetNextConstructItem(void *,struct constructHeader *,int);
LOCALE struct defmoduleItemHeader *GetConstructModuleItemByIndex(void *,struct defmodule *,int);
LOCALE void FreeConstructHeaderModule(void *,struct defmoduleItemHeader *,
struct construct *);
LOCALE long DoForAllConstructs(void *,
void (*)(void *,struct constructHeader *,void *),
int,int,void *);
LOCALE void DoForAllConstructsInModule(void *,void *,
void (*)(void *,struct constructHeader *,void *),
int,int,void *);
LOCALE void InitializeConstructHeader(void *,const char *,struct constructHeader *,SYMBOL_HN *);
LOCALE void SetConstructPPForm(void *,struct constructHeader *,const char *);
LOCALE void *LookupConstruct(void *,struct construct *,const char *,intBool);
#if DEBUGGING_FUNCTIONS
LOCALE unsigned ConstructPrintWatchAccess(void *,struct construct *,const char *,
EXPRESSION *,
unsigned (*)(void *,void *),
void (*)(void *,unsigned,void *));
LOCALE unsigned ConstructSetWatchAccess(void *,struct construct *,unsigned,
EXPRESSION *,
unsigned (*)(void *,void *),
void (*)(void *,unsigned,void *));
#endif
LOCALE intBool ConstructsDeletable(void *);
#endif
|
DrItanium/durandal
|
lib/maya/binops.c
|
<filename>lib/maya/binops.c
/*
maya
Copyright (c) 2012-2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "clips.h"
#include "maya/libmaya.h"
#if BINARY_LOGICAL_OPERATIONS
static uvlong Slice(uvlong w, uvlong s, uvlong e);
static vlong RightShiftFunction(void*);
static vlong LeftShiftFunction(void*);
static vlong BinaryAndFunction(void*);
static vlong BinaryOrFunction(void*);
static vlong BinaryXorFunction(void*);
static vlong BinaryNotFunction(void*);
static vlong SliceFunction(void*);
static void Slice8Function(void*, DATA_OBJECT_PTR);
static void Slice4Function(void*, DATA_OBJECT_PTR);
static void Slice2Function(void*, DATA_OBJECT_PTR);
static vlong MergeFunction(void*);
extern void BinaryOperationsFunctionDefinitions(void* theEnv) {
EnvDefineFunction2(theEnv, "right-shift", 'g', PTIEF RightShiftFunction, "RightShiftFunction", "22i");
EnvDefineFunction2(theEnv, "left-shift", 'g', PTIEF LeftShiftFunction, "LeftShiftFunction", "22i");
EnvDefineFunction2(theEnv, "binary-and", 'g', PTIEF BinaryAndFunction, "BinaryAndFunction", "22i");
EnvDefineFunction2(theEnv, "binary-or", 'g', PTIEF BinaryOrFunction, "BinaryOrFunction", "22i");
EnvDefineFunction2(theEnv, "binary-xor", 'g', PTIEF BinaryXorFunction, "BinaryXorFunction", "22i");
EnvDefineFunction2(theEnv, "binary-not", 'g', PTIEF BinaryNotFunction, "BinaryNotFunction", "11i");
EnvDefineFunction2(theEnv, "slice", 'g', PTIEF SliceFunction, "SliceFunction", "33i");
EnvDefineFunction2(theEnv, "slice8", 'm', PTIEF Slice8Function, "Slice8Function", "11i");
EnvDefineFunction2(theEnv, "slice4", 'm', PTIEF Slice4Function, "Slice4Function", "11i");
EnvDefineFunction2(theEnv, "slice2", 'm', PTIEF Slice2Function, "Slice2Function", "11i");
EnvDefineFunction2(theEnv, "merge", 'g', PTIEF MergeFunction, "MergeFunction", "11m");
}
//use unsigned long long to ensure that logical shift is used instead of
//arithmetic shift
#define StandardFunction(name, op) \
vlong name (void* theEnv) { \
return (vlong)(EnvRtnLong(theEnv, 1) op EnvRtnLong(theEnv, 2)); \
}
StandardFunction(RightShiftFunction, >>);
StandardFunction(LeftShiftFunction, <<);
StandardFunction(BinaryAndFunction, &);
StandardFunction(BinaryOrFunction, |);
StandardFunction(BinaryXorFunction, ^);
vlong BinaryNotFunction(void* theEnv) {
return (vlong)(~(EnvRtnLong(theEnv, 1)));
}
uvlong Slice(uvlong w, uvlong s, uvlong e) {
//TODO: fix this code so that it takes the underlying platform into account
if(s == 0LL && e == 64LL) {
return w;
} else if(s <= 64LL && e <= 64LL && e > s) {
uvlong width, ff, fb;
#ifdef DEBUG
uvlong result;
#endif
width = e - s;
ff = 64LL - e;
fb = 64LL - width;
#ifdef DEBUG
result = (w << ff) >> fb;
printf("(%lld << %lld) >> %lld = %lld\n", w, ff, fb, result);
return result;
#else
return ((w << ff) >> fb);
#endif
} else {
return 0LL;
}
}
vlong SliceFunction(void* theEnv) {
uvlong w, s, e;
w = EnvRtnLong(theEnv, 1);
s = EnvRtnLong(theEnv, 2);
e = EnvRtnLong(theEnv, 3);
return (vlong)Slice(w,s,e);
}
#define SetMultifieldSlot(index, from, to) \
SetMFType(multifield, index, INTEGER); \
SetMFValue(multifield, index, EnvAddLong(theEnv, (vlong)Slice(value, from, to)))
void Slice8Function(void* theEnv, DATA_OBJECT_PTR retVal) {
void* multifield;
uvlong value;
value = EnvRtnLong(theEnv, 1);
multifield = EnvCreateMultifield(theEnv, 8);
SetMultifieldSlot(1, 0LL, 8LL);
SetMultifieldSlot(2, 8LL, 16LL);
SetMultifieldSlot(3, 16LL, 24LL);
SetMultifieldSlot(4, 24LL, 32LL);
SetMultifieldSlot(5, 32LL, 40LL);
SetMultifieldSlot(6, 40LL, 48LL);
SetMultifieldSlot(7, 48LL, 56LL);
SetMultifieldSlot(8, 56LL, 64LL);
SetpType(retVal, MULTIFIELD);
SetpValue(retVal, multifield);
SetpDOBegin(retVal, 1);
SetpDOEnd(retVal, 8);
}
void Slice4Function(void* theEnv, DATA_OBJECT_PTR retVal) {
void* multifield;
uvlong value;
value = EnvRtnLong(theEnv, 1);
multifield = EnvCreateMultifield(theEnv, 4);
SetMultifieldSlot(1, 0LL, 16LL);
SetMultifieldSlot(2, 16LL, 32LL);
SetMultifieldSlot(3, 32LL, 48LL);
SetMultifieldSlot(4, 48LL, 64LL);
SetpType(retVal, MULTIFIELD);
SetpValue(retVal, multifield);
SetpDOBegin(retVal, 1);
SetpDOEnd(retVal, 4);
}
void Slice2Function(void* theEnv, DATA_OBJECT_PTR retVal) {
void* multifield;
uvlong value;
value = EnvRtnLong(theEnv, 1);
multifield = EnvCreateMultifield(theEnv, 2);
SetMultifieldSlot(1, 0LL, 32LL);
SetMultifieldSlot(2, 32LL, 64LL);
SetpType(retVal, MULTIFIELD);
SetpValue(retVal, multifield);
SetpDOBegin(retVal, 1);
SetpDOEnd(retVal, 2);
}
vlong MergeFunction(void* theEnv) {
DATA_OBJECT arg0;
uvlong length, result;
void* multifield;
uvlong t0,t1,t2,t3,t4,t5,t6,t7;
if(EnvArgCountCheck(theEnv, "merge", EXACTLY, 1) == -1) {
return 0LL;
}
if(EnvArgTypeCheck(theEnv, "merge", 1, MULTIFIELD, &arg0) == FALSE) {
return 0LL;
}
length = (uvlong)GetDOLength(arg0);
multifield = GetValue(arg0);
result = 0LL;
switch(length) {
case 1:
return (uvlong)ValueToLong(GetMFValue(multifield, 1));
case 2:
t0 = (uvlong)ValueToLong(GetMFValue(multifield, 2));
result = (uvlong)ValueToLong(GetMFValue(multifield, 1));
result |= (t0 << 32LL);
break;
case 4:
t0 = (uvlong)ValueToLong(GetMFValue(multifield, 4));
t1 = (uvlong)ValueToLong(GetMFValue(multifield, 3));
t2 = (uvlong)ValueToLong(GetMFValue(multifield, 2));
result = (uvlong)ValueToLong(GetMFValue(multifield, 1));
result |= (t2 << 16LL);
result |= (t1 << 32LL);
result |= (t0 << 48LL);
break;
case 8:
t0 = (uvlong)ValueToLong(GetMFValue(multifield,8));
t1 = (uvlong)ValueToLong(GetMFValue(multifield,7));
t2 = (uvlong)ValueToLong(GetMFValue(multifield,6));
t3 = (uvlong)ValueToLong(GetMFValue(multifield,5));
t4 = (uvlong)ValueToLong(GetMFValue(multifield,4));
t5 = (uvlong)ValueToLong(GetMFValue(multifield,3));
t6 = (uvlong)ValueToLong(GetMFValue(multifield,2));
t7 = (uvlong)ValueToLong(GetMFValue(multifield,1));
result = t7;
result |= (t6 << 8LL);
result |= (t5 << 16LL);
result |= (t4 << 24LL);
result |= (t3 << 32LL);
result |= (t2 << 40LL);
result |= (t1 << 48LL);
result |= (t0 << 56LL);
break;
default:
return -1LL;
}
return result;
}
#undef StandardFunction
#undef SetMultifieldSlot
#endif /* BINARY_LOGICAL_OPERATIONS */
|
DrItanium/durandal
|
include/knowledge/ClassSelector.h
|
<reponame>DrItanium/durandal
#ifndef CLASS_SELECTOR_H_
#define CLASS_SELECTOR_H_
#include "llvm/IR/Module.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Constant.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/ADT/Optional.h"
namespace knowledge {
template<typename T>
struct ElectronClassNameSelector {
static void selectName(llvm::raw_string_ostream& str) {
str << "";
}
};
#define X(__, type, className, ___) \
template<> \
struct ElectronClassNameSelector<type> { \
static void selectName(llvm::raw_string_ostream& str) { \
str << className ; \
} \
};
#include "knowledge/EngineNodes.def"
#undef X
}
#endif // CLASS_SELECTOR_H_
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSModuleBuilder.h
|
<reponame>DrItanium/durandal
#ifndef _clips_module_builder_h
#define _clips_module_builder_h
#include "ExpertSystem/CLIPSObjectBuilder.h"
using namespace llvm;
class CLIPSModuleBuilder : public CLIPSObjectBuilder {
public:
CLIPSModuleBuilder(std::string nm, std::string ty = "LLVMModule");
void build(Module* mod, KnowledgeConstructor* kc);
void addFields(Module* mod, KnowledgeConstructor* kc);
};
#endif
|
DrItanium/durandal
|
include/knowledge/Engine.h
|
<reponame>DrItanium/durandal<gh_stars>1-10
#ifndef _ENGINE_H_
#define _ENGINE_H_
#include "llvm/IR/Module.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/LoopPass.h"
extern "C" void RegisterEngineBookkeeping(void* theEnv);
namespace knowledge {
bool convert(void* env, llvm::BasicBlock* blk, llvm::BasicBlockPass* pass);
bool convert(void* env, llvm::Function* fn, llvm::FunctionPass* pass);
bool convert(void* env, llvm::Module* mod, llvm::ModulePass* pass);
bool convert(void* env, llvm::Region* region, llvm::RegionPass* pass);
bool convert(void* env, llvm::Loop* loop, llvm::LoopPass* pass);
}
#endif
|
DrItanium/durandal
|
include/knowledge/FunctionKnowledgeConversionPass.h
|
<reponame>DrItanium/durandal
#ifndef _function_knoledge_conversion_pass_h
#define _function_knoledge_conversion_pass_h
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Analysis/LoopInfo.h"
extern "C" {
#include "clips.h"
}
namespace knowledge {
struct FunctionKnowledgeConversionPass : public llvm::FunctionPass {
static char ID;
private:
void* theEnv;
/*
bool skipRegions;
bool skipLoops;
*/
bool runOnFunctionImpl(llvm::Function& fn);
public:
FunctionKnowledgeConversionPass() : FunctionPass(ID) {
theEnv = CreateEnvironment();
}
~FunctionKnowledgeConversionPass() {
DestroyEnvironment(theEnv);
theEnv = 0;
}
/*
void setSkipRegions(bool sRegions);
void setSkipLoops(bool sLoops);
virtual void getAnalysisUsage(AnalysisUsage &info) const {
if(!skipRegions) {
info.addRequired<LoopInfo>();
}
if(!skipLoops) {
info.addRequired<RegionInfo>();
}
}
*/
virtual bool runOnFunction(llvm::Function& fn) {
return runOnFunctionImpl(fn);
}
};
}
#endif
|
DrItanium/durandal
|
include/indirect/RegisterIndirectPass.h
|
#ifndef _register_indirect_pass_h
#define _register_indirect_pass_h
/* IndirectRegisterPass is a class used to register indirect passes in a fashion
* similar to how llvm::RegisterPass works.
*/
#include "llvm/Pass.h"
#include "indirect/IndirectPassHeader.h"
namespace indirect {
class RegisterIndirectPass : public llvm::PassInfo {
public:
RegisterIndirectPass(IndirectPassHeader* header);
RegisterIndirectPass(const char* passArg, const char* passName,
bool cfgOnly = false, bool isAnalysis = false);
};
}
#endif
|
DrItanium/durandal
|
include/indirect/IndirectPass.h
|
<filename>include/indirect/IndirectPass.h
#ifndef _indirect_pass_h
#define _indirect_pass_h
#include "indirect/IndirectPassHeader.h"
#include "llvm/Pass.h"
/* This class is meant to interface with the different template pass classes to
* provide the indirection functionality without having to reinvent the wheel
* for each pass.
*/
namespace indirect {
class IndirectPass {
private:
IndirectPassHeader* header;
public:
IndirectPass();
~IndirectPass();
void setIndirectPassHeader(IndirectPassHeader* header);
IndirectPassHeader* getIndirectPassHeader();
void applyIndirectAnalysisUsage(llvm::AnalysisUsage& usage) const;
};
}
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/KnowledgeConstructor.h
|
<filename>include/obsolete/ExpertSystem/KnowledgeConstructor.h<gh_stars>1-10
#ifndef _knowledge_construction_pass_h
#define _knowledge_construction_pass_h
#include "llvm/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Casting.h"
#include "llvm/Instruction.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Argument.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/User.h"
#include "llvm/Value.h"
#include "llvm/Type.h"
#include "llvm/BasicBlock.h"
#include "llvm/Analysis/RegionIterator.h"
#include "llvm/Operator.h"
#include "llvm/Metadata.h"
#include "llvm/InlineAsm.h"
#include "llvm/Argument.h"
#include "llvm/Constant.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/GlobalValue.h"
#include "llvm/GlobalAlias.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Operator.h"
#include "llvm/Function.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Value.h"
#include "ExpertSystem/Types.h"
#include "ExpertSystem/FunctionNamer.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include <string>
using namespace llvm;
class KnowledgeConstructor {
llvm::DenseMap<PointerAddress, std::string>* instances;
llvm::raw_string_ostream* instanceStream;
std::string* tmp;
PointerAddress moduleCount;
public:
KnowledgeConstructor();
~KnowledgeConstructor();
void resetInstanceStream();
llvm::DenseMap<PointerAddress, std::string>* getInstances();
std::string getInstancesAsString();
PointerAddress getModuleCount();
void addToInstanceStream(std::string &instance);
void registerInstance(PointerAddress ptrAddress, std::string &instance);
void addToKnowledgeBase(PointerAddress ptrAddress, std::string &instance);
std::string route(Value* val, FunctionNamer& namer, char* parent);
std::string route(Value* val, FunctionNamer& namer);
std::string route(User* user, FunctionNamer& namer, char* parent);
std::string route(Constant* cnst, FunctionNamer& namer);
std::string route(Constant* cnst, FunctionNamer& namer, char* parent);
std::string route(Instruction* inst, FunctionNamer& namer, char* parent);
std::string route(Type* t, FunctionNamer& namer);
std::string route(Operator* op, FunctionNamer& namer);
std::string route(Operator* op, FunctionNamer& namer, char* parent);
std::string route(BasicBlock* bb, FunctionNamer& namer, char* parent, bool constructInstructions = true);
std::string route(Region* region, FunctionNamer& namer, char* parent);
std::string route(Argument* arg, FunctionNamer& namer, char* parent);
std::string route(Loop* loop, FunctionNamer& namer, char* parent);
std::string route(MDString* mds, FunctionNamer& namer, char* parent);
std::string route(MDNode* mdn, FunctionNamer& namer, char* parent);
std::string route(InlineAsm* iasm, FunctionNamer& namer, char* parent);
void route(RegionInfo& ri, FunctionNamer& namer, char* parent);
void route(LoopInfo& li, FunctionNamer& namer, char* parent);
void updateFunctionContents(Function& fn, FunctionNamer& namer);
void route(Function& fn, LoopInfo& li, RegionInfo& ri);
void route(Function& fn, RegionInfo& ri);
void route(Function& fn, LoopInfo& ri);
void route(Function& fn);
std::string route(Module* module);
};
#endif
|
DrItanium/durandal
|
include/electron/sysdep.h
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* SYSTEM DEPENDENT HEADER FILE */
/*******************************************************/
/*************************************************************/
/* Purpose: Isolation of system dependent routines. */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.23: Modified GenOpen to check the file length */
/* against the system constant FILENAME_MAX. */
/* */
/* 6.24: Support for run-time programs directly passing */
/* the hash tables for initialization. */
/* */
/* Made gensystem functional for Xcode. */
/* */
/* Added BeforeOpenFunction and AfterOpenFunction */
/* hooks. */
/* */
/* Added environment parameter to GenClose. */
/* Added environment parameter to GenOpen. */
/* */
/* Updated UNIX_V gentime functionality. */
/* */
/* Removed GenOpen check against FILENAME_MAX. */
/* */
/* 6.30: Changed integer type/precision. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, IBM_ICB, IBM_TBC, IBM_ZTC, and */
/* IBM_SC). */
/* */
/* Renamed IBM_MSC and WIN_MVC compiler flags */
/* and IBM_GCC to WIN_GCC. */
/* */
/* Added LINUX and DARWIN compiler flags. */
/* */
/* Removed HELP_FUNCTIONS compilation flag and */
/* associated functionality. */
/* */
/* Removed EMACS_EDITOR compilation flag and */
/* associated functionality. */
/* */
/* Combined BASIC_IO and EXT_IO compilation */
/* flags into the single IO_FUNCTIONS flag. */
/* */
/* Changed the EX_MATH compilation flag to */
/* EXTENDED_MATH_FUNCTIONS. */
/* */
/* Support for typed EXTERNAL_ADDRESS. */
/* */
/* GenOpen function checks for UTF-8 Byte Order */
/* Marker. */
/* */
/* Added gengetchar, genungetchar, genprintfile, */
/* genstrcpy, genstrncpy, genstrcat, genstrncat, */
/* and gensprintf functions. */
/* */
/* Added SetJmpBuffer function. */
/* */
/* Added environment argument to genexit. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/*************************************************************/
#ifndef _H_sysdep
#define _H_sysdep
#ifndef _H_symbol
#include "symbol.h"
#endif
#ifndef _STDIO_INCLUDED_
#define _STDIO_INCLUDED_
#include <stdio.h>
#endif
#include <setjmp.h>
#if WIN_MVC
#include <dos.h>
#endif
#ifdef LOCALE
#undef LOCALE
#endif
#ifdef _SYSDEP_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif
LOCALE void InitializeEnvironment(void);
LOCALE void EnvInitializeEnvironment(void *,struct symbolHashNode **,struct floatHashNode **,
struct integerHashNode **,struct bitMapHashNode **,
struct externalAddressHashNode **);
LOCALE void SetRedrawFunction(void *,void (*)(void *));
LOCALE void SetPauseEnvFunction(void *,void (*)(void *));
LOCALE void SetContinueEnvFunction(void *,void (*)(void *,int));
LOCALE void (*GetRedrawFunction(void *))(void *);
LOCALE void (*GetPauseEnvFunction(void *))(void *);
LOCALE void (*GetContinueEnvFunction(void *))(void *,int);
LOCALE void RerouteStdin(void *,int,char *[]);
LOCALE double gentime(void);
LOCALE void gensystem(void *theEnv);
LOCALE int GenOpenReadBinary(void *,const char *,const char *);
LOCALE void GetSeekCurBinary(void *,long);
LOCALE void GetSeekSetBinary(void *,long);
LOCALE void GenTellBinary(void *,long *);
LOCALE void GenCloseBinary(void *);
LOCALE void GenReadBinary(void *,void *,size_t);
LOCALE FILE *GenOpen(void *,const char *,const char *);
LOCALE int GenClose(void *,FILE *);
LOCALE void genexit(void *,int);
LOCALE int genrand(void);
LOCALE void genseed(int);
LOCALE int genremove(const char *);
LOCALE int genrename(const char *,const char *);
LOCALE char *gengetcwd(char *,int);
LOCALE void GenWrite(void *,size_t,FILE *);
LOCALE int (*EnvSetBeforeOpenFunction(void *,int (*)(void *)))(void *);
LOCALE int (*EnvSetAfterOpenFunction(void *,int (*)(void *)))(void *);
LOCALE int gensprintf(char *,const char *,...);
LOCALE char *genstrcpy(char *,const char *);
LOCALE char *genstrncpy(char *,const char *,size_t);
LOCALE char *genstrcat(char *,const char *);
LOCALE char *genstrncat(char *,const char *,size_t);
LOCALE void SetJmpBuffer(void *,jmp_buf *);
LOCALE void genprintfile(void *,FILE *,const char *);
LOCALE int gengetchar(void *);
LOCALE int genungetchar(void *,int);
#if FILE_SYSTEM_ROOTING
LOCALE int _GenOpenReadBinary(void *,const char *,const char *);
LOCALE FILE *_GenOpen(void *,const char *,const char *);
#endif
#endif /* _H_sysdep */
|
DrItanium/durandal
|
include/rampancy/Cortex.h
|
<gh_stars>1-10
#ifndef _rampancy_cortex_h
#define _rampancy_cortex_h
#include "rampancy/CompilerManager.h"
#include "rampancy/Compiler.h"
#include "rampancy/CompilerRegistry.h"
#include "llvm/Function.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
namespace rampancy {
class Cortex {
CLIPSEnvironment* env;
llvm::LLVMContext* context;
CompilerManager* manager;
public:
Cortex(void* theEnv = 0);
~Cortex();
static Cortex* getRampantCortex();
llvm::LLVMContext* getContext();
void setContext(llvm::LLVMContext* llvmContext);
CLIPSEnvironment* getEnvironment();
void setEnvironment(CLIPSEnvironment* env);
void compileToKnowledge(void* theEnv);
void interpretToKnowledge(void* theEnv);
llvm::Module* compile(llvm::StringRef logicalName, void* theEnv);
llvm::Module* interpret(llvm::StringRef logicalName, void* theEnv);
llvm::Module* compile(char* logicalName, int argc, char** argv);
llvm::Module* compile(llvm::StringRef logicalName,
int argc, char** argv);
llvm::Module* interpret(llvm::StringRef logicalName,
llvm::StringRef input);
llvm::Module* interpret(char* logicalName, llvm::StringRef input);
void convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module);
void convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module, void* theEnv);
};
}
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSObjectBuilder.h
|
<filename>include/obsolete/ExpertSystem/CLIPSObjectBuilder.h<gh_stars>1-10
#ifndef _clips_object_builder_h
#define _clips_object_builder_h
#include <string.h>
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/StringRef.h"
#include "ExpertSystem/Types.h"
#include "ExpertSystem/FunctionNamer.h"
#include "ExpertSystem/KnowledgeConstructor.h"
using namespace llvm;
class CLIPSObjectBuilder {
private:
bool converted;
bool opened;
bool closed;
std::string name;
std::string type;
std::string tmp;
raw_string_ostream* stream;
FunctionNamer* namer;
public:
CLIPSObjectBuilder(std::string n, std::string t, FunctionNamer& uidCreator);
CLIPSObjectBuilder(std::string n, std::string t);
~CLIPSObjectBuilder();
std::string getCompletedString();
std::string& getName();
std::string& getType();
FunctionNamer& getNamer();
raw_string_ostream& getStream();
bool isOpen();
bool isClosed();
bool isKnowledge();
void setParent(char* p);
void setParent(const char* p);
void setPointer(PointerAddress v);
void addField(const char* n, unsigned v);
void addField(const char* n, PointerAddress v);
void addField(const char* n, int v);
void addField(const char* n, float v);
void addField(const char* n, double v);
void addField(const char* n, char* v);
void addField(const char* n, const char* v);
void addField(const char* n, std::string v);
void addField(const char* n, llvm::StringRef ref);
void addField(const char* n, bool v);
void addField(const char* n, uint64_t v);
#if !defined(__APPLE__)
void addField(const char* n, int64_t v);
#endif
void addStringField(const char* n, const std::string& str);
void addTrueField(const char* n);
void addFalseField(const char* n);
void openField(const char* name);
void appendValue(unsigned v);
void appendValue(PointerAddress v);
void appendValue(int v);
void appendValue(float v);
void appendValue(double v);
void appendValue(char* v);
void appendValue(const char* v);
void appendValue(std::string v);
void appendValue(llvm::StringRef ref);
void appendValue(bool v);
void appendValue(uint64_t v);
#if !defined(__APPLE__)
void appendValue(int64_t v);
#endif
void appendTrue();
void appendFalse();
void closeField();
void open();
void close();
void convertToKnowledge(void* theEnv);
void addFields(PointerAddress pointer, KnowledgeConstructor* kc, char* parent);
};
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSInstructionBuilder.h
|
<reponame>DrItanium/durandal
#ifndef _instruction_construction_h
#define _instruction_construction_h
#include "ExpertSystem/CLIPSUserBuilder.h"
#include "llvm/Instruction.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
class CLIPSInstructionBuilder : public CLIPSUserBuilder {
public:
CLIPSInstructionBuilder(std::string nm, std::string ty, FunctionNamer& namer) : CLIPSUserBuilder(nm, ty, namer) { }
void addFields(Instruction* instruction, KnowledgeConstructor *kc, char* parent, bool addDestinationRegisters = true);
void build(Instruction* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSPHINodeBuilder : public CLIPSInstructionBuilder {
public:
CLIPSPHINodeBuilder(std::string nm, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, "PhiNode", namer) { }
void addFields(PHINode* instruction, KnowledgeConstructor *kc, char* parent);
void build(PHINode* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSStoreInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSStoreInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, "StoreInstruction", namer) { }
void addFields(StoreInst* target, KnowledgeConstructor *kc, char* parent);
void build(StoreInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSBinaryOperatorBuilder : public CLIPSInstructionBuilder {
public:
CLIPSBinaryOperatorBuilder(std::string nm, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, "BinaryOperator", namer) { }
void addFields(BinaryOperator* target, KnowledgeConstructor *kc, char* parent);
void build(BinaryOperator* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSCallInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSCallInstructionBuilder(std::string nm, FunctionNamer& namer, std::string ty = "CallInstruction") : CLIPSInstructionBuilder(nm, ty, namer) { }
void addFields(CallInst* target, KnowledgeConstructor *kc, char* parent);
void build(CallInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSCompareInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSCompareInstructionBuilder(std::string nm, FunctionNamer& namer, std::string ty = "CompareInstruction") : CLIPSInstructionBuilder(nm, ty, namer) { }
void addFields(CmpInst* target, KnowledgeConstructor *kc, char* parent);
void build(CmpInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSFPCompareInstructionBuilder : public CLIPSCompareInstructionBuilder {
public:
CLIPSFPCompareInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSCompareInstructionBuilder(nm, namer, "FloatingPointCompareInstruction") { }
void addFields(FCmpInst* target, KnowledgeConstructor *kc, char* parent);
void build(FCmpInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSIntCompareInstructionBuilder : public CLIPSCompareInstructionBuilder {
public:
CLIPSIntCompareInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSCompareInstructionBuilder(nm, namer, "IntegerCompareInstruction") { }
void addFields(ICmpInst* target, KnowledgeConstructor *kc, char* parent);
void build(ICmpInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSGetElementPtrInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSGetElementPtrInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, "GetElementPointerInstruction", namer) { }
void addFields(GetElementPtrInst* target, KnowledgeConstructor *kc, char* parent);
void build(GetElementPtrInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSTerminatorInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSTerminatorInstructionBuilder(std::string nm, std::string ty, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, ty, namer) { }
void addFields(TerminatorInst* target, KnowledgeConstructor *kc, char* parent);
void build(TerminatorInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSBranchInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSBranchInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "BranchInstruction", namer) { }
void addFields(BranchInst* inst, KnowledgeConstructor *kc, char* parent);
void build(BranchInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSIndirectBranchInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSIndirectBranchInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "IndirectBranchInstruction", namer) { }
void addFields(IndirectBrInst* inst, KnowledgeConstructor *kc, char* parent);
void build(IndirectBrInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSInvokeInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
//this is different from a call instruction because there are two extra
//arguments that define the normal and exception jump points
public:
CLIPSInvokeInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "InvokeInstruction", namer) { }
void addFields(InvokeInst* target, KnowledgeConstructor *kc, char* parent);
void build(InvokeInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSResumeInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSResumeInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "ResumeInstruction", namer) { }
void addFields(ResumeInst* inst, KnowledgeConstructor *kc, char* parent);
void build(ResumeInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSReturnInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSReturnInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "ReturnInstruction", namer) { }
void addFields(ReturnInst* inst, KnowledgeConstructor *kc, char* parent);
void build(ReturnInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSSwitchInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSSwitchInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "SwitchInstruction", namer) { }
void addFields(SwitchInst* inst, KnowledgeConstructor *kc, char* parent);
void build(SwitchInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSUnreachableInstructionBuilder : public CLIPSTerminatorInstructionBuilder {
public:
CLIPSUnreachableInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSTerminatorInstructionBuilder(nm, "UnreachableInstruction", namer) { }
void addFields(UnreachableInst* instruction, KnowledgeConstructor *kc, char* parent);
void build(UnreachableInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSSelectInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSSelectInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, "SelectInstruction", namer) { }
void addFields(SelectInst* inst, KnowledgeConstructor *kc, char* parent);
void build(SelectInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSUnaryInstructionBuilder : public CLIPSInstructionBuilder {
public:
CLIPSUnaryInstructionBuilder(std::string nm, std::string ty, FunctionNamer& namer) : CLIPSInstructionBuilder(nm, ty, namer) { }
void addFields(UnaryInstruction* inst, KnowledgeConstructor *kc, char* parent);
void build(UnaryInstruction* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSAllocaInstructionBuilder : public CLIPSUnaryInstructionBuilder {
public:
CLIPSAllocaInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSUnaryInstructionBuilder(nm, "AllocaInstruction", namer) { }
void addFields(AllocaInst* inst, KnowledgeConstructor *kc, char* parent);
void build(AllocaInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSCastInstructionBuilder : public CLIPSUnaryInstructionBuilder {
public:
CLIPSCastInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSUnaryInstructionBuilder(nm, "CastInstruction", namer) { }
void addFields(CastInst* inst, KnowledgeConstructor *kc, char* parent);
void build(CastInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSExtractValueInstructionBuilder : public CLIPSUnaryInstructionBuilder {
public:
CLIPSExtractValueInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSUnaryInstructionBuilder(nm, "ExtractValueInstruction", namer) { }
void addFields(ExtractValueInst* inst, KnowledgeConstructor *kc, char* parent);
void build(ExtractValueInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSLoadInstructionBuilder : public CLIPSUnaryInstructionBuilder {
public:
CLIPSLoadInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSUnaryInstructionBuilder(nm, "LoadInstruction", namer) { }
void addFields(LoadInst* inst, KnowledgeConstructor *kc, char* parent);
void build(LoadInst* instruction, KnowledgeConstructor *kc, char* parent);
};
class CLIPSVAArgInstructionBuilder : public CLIPSUnaryInstructionBuilder {
public:
CLIPSVAArgInstructionBuilder(std::string nm, FunctionNamer& namer) : CLIPSUnaryInstructionBuilder(nm, "VAArgInstruction", namer) { }
void addFields(VAArgInst* inst, KnowledgeConstructor *kc, char* parent);
void build(VAArgInst* instruction, KnowledgeConstructor *kc, char* parent);
};
#endif
|
DrItanium/durandal
|
include/pipeline/clips/CLIPSPass.h
|
<filename>include/pipeline/clips/CLIPSPass.h
#ifndef _clips_pass_h
#define _clips_pass_h
namespace pipeline {
namespace clips {
class CLIPSPass {
private:
void* envPtr;
public:
CLIPSPass();
~CLIPSPass();
void setEnvironment(void* theEnv);
void* getEnvironment();
};
}
}
#endif
|
DrItanium/durandal
|
include/rampancy/ClangCompiler.h
|
#ifndef _rampancy_clang_compiler_h
#define _rampancy_clang_compiler_h
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Module.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "ExpertSystem/KnowledgeConstructor.h"
#include "ExpertSystem/FunctionNamer.h"
#include "ExpertSystem/KnowledgeConstructionEngine.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "rampancy/Compiler.h"
using namespace clang;
using namespace clang::driver;
namespace rampancy {
struct ClangCompilerGlobals {
//HACK HACK!
//Used to get around the fact that we may not have immediate access to
//arg0. Thus we need to register this at program startup
static const char* argv0;
};
class ClangCompiler : public Compiler {
public:
static char ID;
ClangCompiler();
using Compiler::compile;
using Compiler::interpret;
virtual llvm::Module* compile();
virtual llvm::Module* compile(int argc, char** argv);
virtual llvm::Module* interpret();
virtual llvm::Module* interpret(llvm::StringRef input);
};
}
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSConstantBuilder.h
|
#ifndef _constant_construction_h
#define _constant_construction_h
#include <string.h>
#include "ExpertSystem/CLIPSUserBuilder.h"
#include "llvm/Constant.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/GlobalValue.h"
#include "llvm/GlobalAlias.h"
using namespace llvm;
class CLIPSConstantBuilder : public CLIPSUserBuilder {
public:
CLIPSConstantBuilder(std::string nm, std::string ty, FunctionNamer& namer);
void addFields(Constant* cnst, KnowledgeConstructor* kc, char* parent);
void build(Constant* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSBlockAddressBuilder : public CLIPSConstantBuilder {
public:
CLIPSBlockAddressBuilder(std::string nm, FunctionNamer& namer);
void addFields(BlockAddress* addr, KnowledgeConstructor* kc, char* parent);
void build(BlockAddress* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantAggregateZeroBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantAggregateZeroBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantAggregateZero* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantAggregateZero* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantArrayBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantArrayBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantArray* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantArray* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantExpressionBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantExpressionBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantExpr* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantExpr* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSConstantFloatingPointBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantFloatingPointBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantFP* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantFP* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantIntegerBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantIntegerBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantInt* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantInt* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantPointerNullBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantPointerNullBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantPointerNull* addr, KnowledgeConstructor *kc, char* parent);
void build(ConstantPointerNull* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSConstantStructBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantStructBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantStruct* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantStruct* cnst, KnowledgeConstructor* kc, char* parent);
};
class CLIPSConstantVectorBuilder : public CLIPSConstantBuilder {
public:
CLIPSConstantVectorBuilder(std::string nm, FunctionNamer& namer);
void addFields(ConstantVector* addr, KnowledgeConstructor* kc, char* parent);
void build(ConstantVector* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSGlobalValueBuilder : public CLIPSConstantBuilder
{
public:
CLIPSGlobalValueBuilder(std::string nm, std::string ty, FunctionNamer& namer);
void addFields(GlobalValue* addr, KnowledgeConstructor *kc, char* parent);
void build(GlobalValue* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSGlobalAliasBuilder : public CLIPSGlobalValueBuilder {
public:
CLIPSGlobalAliasBuilder(std::string nm, FunctionNamer& namer);
void addFields(GlobalAlias* addr, KnowledgeConstructor *kc, char* parent);
void build(GlobalAlias* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSGlobalVariableBuilder : public CLIPSGlobalValueBuilder {
public:
CLIPSGlobalVariableBuilder(std::string nm, FunctionNamer& namer);
void addFields(GlobalVariable* addr, KnowledgeConstructor *kc, char* parent);
void build(GlobalVariable* cnst, KnowledgeConstructor *kc, char* parent);
};
class CLIPSUndefValueBuilder : public CLIPSConstantBuilder {
public:
CLIPSUndefValueBuilder(std::string nm, FunctionNamer& namer);
void addFields(UndefValue* addr, KnowledgeConstructor *kc, char* parent);
void build(UndefValue* cnst, KnowledgeConstructor *kc, char* parent);
};
/*
* This does not exist in my version of LLVM so...yeah it's commented out for
* the time being
* -<NAME> 5/20/2012 @ 1746
class CLIPSBinaryConstantExpressionBuilder : public CLIPSConstantExpressionBuilder
{
public:
CLIPSBinaryConstantExpressionBuilder(std::string nm, FunctionNamer& namer) : CLIPSConstantExpressionBuilder(nm, "BinaryConstantExpression", namer) { }
void addFields(BinaryConstantExpr* addr, char* parent)
{
CLIPSConstantBuilder::addFields((Constant*)addr, parent);
}
void imbueKnowledge(BinaryConstantExpr* addr)
{
CLIPSConstantBuilder::imbueKnowledge((Constant*)addr);
}
};
class CLIPSCompareConstantExpressionBuilder : public CLIPSConstantExpressionBuilder
{
public:
CLIPSCompareConstantExpressionBuilder(std::string nm, FunctionNamer& namer) : CLIPSConstantExpressionBuilder(nm, "CompareConstantExpression", namer) { }
void addFields(CompareConstantExpr* addr, char* parent)
{
CLIPSConstantBuilder::addFields((Constant*)addr, parent);
addField("ActualPredicate", addr->predicate);
}
void imbueKnowledge(CompareConstantExpr* addr)
{
CLIPSConstantBuilder::imbueKnowledge((Constant*)addr);
}
};
*/
/* ConstantDataSequential doesn't exist in llvm 3.0 :/
* But I have a feeling it is in newer versions of LLVM so I'm keeping the code
* here for those newer versions
* - <NAME> 5/20/2012 @ 1726 PST
class CLIPSConstantDataSequentialBuilder : public CLIPSConstantBuilder
{
public:
CLIPSConstantDataSequentialBuilder(std::string nm, FunctionNamer& namer) : CLIPSConstantBuilder(nm, "ConstantDataSequential", namer) { }
void addFields(ConstantDataSequential* addr, char* parent);
void imbueKnowledge(ConstantDataSequential* addr)
{
CLIPSConstantBuilder::imbueKnowledge((Constant*)addr);
send("put-ElementType", Route(addr->getElementType()));
}
};
*/
#endif
|
DrItanium/durandal
|
include/rampancy/CompilerRegistry.h
|
<reponame>DrItanium/durandal
#ifndef _rampancy_compiler_registry_h
#define _rampancy_compiler_registry_h
#include "llvm/ADT/StringRef.h"
#include "rampancy/Compiler.h"
#include "llvm/ADT/StringMap.h"
namespace rampancy {
class CompilerRegistry {
typedef llvm::StringMap<rampancy::Compiler*> StringMapType;
StringMapType compilerStringMap;
public:
CompilerRegistry() { }
~CompilerRegistry();
static CompilerRegistry* getCompilerRegistry();
Compiler* getCompiler(char* logicalName) const;
Compiler* getCompiler(llvm::StringRef logicalName) const;
void registerCompiler(char* logicalName, Compiler* compiler);
void registerCompiler(llvm::StringRef logicalName, Compiler* compiler);
void unregisterCompiler(char* logicalName);
void unregisterCompiler(llvm::StringRef logicalName);
};
}
#endif
|
DrItanium/durandal
|
include/rampancy/LLVMIRCompiler.h
|
<reponame>DrItanium/durandal
#ifndef _rampancy_llvm_ir_compiler_h
#define _rampancy_llvm_ir_compiler_h
#include "llvm/Module.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/IRReader.h"
#include "ExpertSystem/KnowledgeConstructor.h"
#include "ExpertSystem/FunctionNamer.h"
#include "ExpertSystem/KnowledgeConstructionEngine.h"
#include "ExpertSystem/CLIPSEnvironment.h"
#include "rampancy/Compiler.h"
namespace rampancy {
class LLVMIRCompiler : public Compiler {
public:
LLVMIRCompiler();
using Compiler::compile;
using Compiler::interpret;
virtual llvm::Module* compile();
virtual llvm::Module* compile(int argc, char** argv);
llvm::Module* compile(const std::string &fileName,
llvm::SMDiagnostic &err);
virtual llvm::Module* interpret();
virtual llvm::Module* interpret(llvm::StringRef input);
};
}
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSBasicBlockBuilder.h
|
#ifndef _clips_basic_block_builder_h
#define _clips_basic_block_builder_h
#include "ExpertSystem/CLIPSValueBuilder.h"
#include "llvm/BasicBlock.h"
using namespace llvm;
class CLIPSBasicBlockBuilder : public CLIPSValueBuilder {
public:
CLIPSBasicBlockBuilder(std::string nm, FunctionNamer& namer);
void addFields(BasicBlock* bb, KnowledgeConstructor* kc, char* parent,
bool constructInstructions = true);
void build(BasicBlock* bb, KnowledgeConstructor* kc, char* parent,
bool constructInstructions = true);
};
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSArgumentBuilder.h
|
<gh_stars>1-10
#ifndef _argument_builder_h
#define _argument_builder_h
#include "ExpertSystem/CLIPSValueBuilder.h"
#include "ExpertSystem/KnowledgeConstructor.h"
#include "llvm/Argument.h"
using namespace llvm;
class CLIPSArgumentBuilder : public CLIPSValueBuilder {
public:
CLIPSArgumentBuilder(std::string nm, FunctionNamer& namer);
void addFields(Argument* arg, KnowledgeConstructor* kc, char* parent);
void build(Argument* arg, KnowledgeConstructor* kc, char* parent);
};
#endif
|
DrItanium/durandal
|
include/obsolete/ExpertSystem/CLIPSValueBuilder.h
|
#ifndef _clips_value_builder_h
#define _clips_value_builder_h
#include "llvm/Value.h"
#include "ExpertSystem/CLIPSObjectBuilder.h"
using namespace llvm;
class CLIPSValueBuilder : public CLIPSObjectBuilder {
public:
CLIPSValueBuilder(std::string nm, std::string ty, FunctionNamer& namer);
void setType(Type* t, KnowledgeConstructor* kc);
void addFields(Value* val, KnowledgeConstructor* kc, char* parent);
void build(Value* val, KnowledgeConstructor* kc, char* parent);
};
#endif
|
JankoLancer/uptime
|
ios/Classes/UptimePlugin.h
|
<gh_stars>1-10
#import <Flutter/Flutter.h>
@interface UptimePlugin : NSObject<FlutterPlugin>
@end
|
TriHardStudios/TSA-Software-2019
|
Acrylic_Backend/UserInput/GLFWBackend.h
|
//
// Created by <NAME> on 3/11/20.
//
#ifndef ACRYLIC2D_GLFWBACKEND_H
#define ACRYLIC2D_GLFWBACKEND_H
#include "WindowBackend.hpp"
class GLFWBackend: public WindowBackend<void (GLFWwindow*, int, int, int, int),
void(GLFWwindow*, int, int, int), void(GLFWwindow*, double, double)> {
std::map<KeyTriple, KeyTriple> modMap = {};
static Keyboard<void (GLFWwindow*, int, int, int, int)> keyboard;
static Mouse<void (GLFWwindow*, int, int, int), void(GLFWwindow*, double, double)> mouse;
public:
void setOnKey(void (*)(GLFWwindow*, int, int, int, int)) override;
void setOnMouseButton(void (*)(GLFWwindow*, int, int, int)) override;
void setOnMouseMove(void (*)(GLFWwindow*, double, double)) override;
void addToKeyMap(int, int, int, KeyTriple) override;
static void keyFunc(GLFWwindow*, int, int, int, int);
static void mouseButtonFunc(GLFWwindow*, int, int, int);
static void mouseMoveFunc(GLFWwindow*, double, double);
KeyTriple convertKeyToA2DCode(int, int, int) override;
void init();
};
#endif //ACRYLIC2D_GLFWBACKEND_H
|
TriHardStudios/TSA-Software-2019
|
Acrylic_Backend/Timers/acrylic_frameTimer.h
|
<filename>Acrylic_Backend/Timers/acrylic_frameTimer.h<gh_stars>1-10
#ifndef PLEXI_FRAMETIMER_H
#define PLEXI_FRAMETIMER_H
#include <chrono>
namespace A2D::Timers{
class FrameTimer {
public:
std::chrono::time_point<std::chrono::system_clock> start;
void startTimer();
double getTime();
double getFPS(unsigned frames);
};
}
#endif //PLEXI_FRAMETIMER_H
|
TriHardStudios/TSA-Software-2019
|
Acrylic_Backend/BackendAPIs/AcrylicSaveEngine/FileSystemBackend/acrylic_bitmap.h
|
<filename>Acrylic_Backend/BackendAPIs/AcrylicSaveEngine/FileSystemBackend/acrylic_bitmap.h
#ifndef ACRYLIC_BITMAP_H
#define ACRYLIC_BITMAP_H
#include <iostream>
#include <fstream>
#include <string>
#include <ths/log.hpp>
namespace A2D::Filesystem::Loaders::Bitmaps {
struct Image
{
int height;
int width;
int length;
int bytes;
unsigned char * imageData;//Sorry, I renamed this so that it would be more clear and not confused with the main struct
explicit Image(const std::filesystem::path FileName);
explicit Image(std::string DirectFile);
//uint32_t Convert();
void Default();
void PrintInfo();
void Print();
char GetPixelValue(int x,int y,int P) //P 0=red 1=green 2=blue 3=alpha
{
return imageData[(x + (y * width)) * bytes + P ];
}
void SetPixelValue(int x, int y, int P, char v) //P 0=red 1=green 2=blue 3=alpha
{
imageData[(x + (y * width)) * bytes + P] = v;
}
void Write(const std::string& FileName);
};
}
#endif //ACRYLIC_BITMAP_H
|
TriHardStudios/TSA-Software-2019
|
Acrylic_Backend/acrylic_random.h
|
<reponame>TriHardStudios/TSA-Software-2019
//
// Created by coolh on 1/8/2020.
//
// Copyright (c) 2014, <NAME> <<EMAIL>>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Universität Bremen nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/* Author: <NAME> */
#ifndef ACRYLIC2D_ACRYLIC_RANDOM_H
#define ACRYLIC2D_ACRYLIC_RANDOM_H
#include <iostream>
#include <cstdlib>
#include <tuple>
#include <glm/glm.hpp>
#include <random>
namespace A2D::Random {
class Random {
Random() {}
public:
static glm::vec3 ranRGB();
glm::vec3 ranHSV();
static glm::vec3 RGBtoHSV(glm::vec3 rgb);
static glm::vec3 HSVtoRGB(glm::vec3 hsv);
int WeightedRandom(int Weights[]);
};
// glm::vec3 ranRGB();
}
#endif
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/plugins/crypto_native/aes_cbc_neon.h
|
/*
*------------------------------------------------------------------
* Copyright (c) 2020 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*------------------------------------------------------------------
*/
#ifdef __aarch64__
static_always_inline void
aes_cbc_dec (u8x16 * k, u8 * src, u8 * dst, u8 * iv, int count, int rounds)
{
u8x16 r0, r1, r2, r3, c0, c1, c2, c3, f;
f = vld1q_u8 (iv);
while (count >= 64)
{
c0 = r0 = vld1q_u8 (src);
c1 = r1 = vld1q_u8 (src + 16);
c2 = r2 = vld1q_u8 (src + 32);
c3 = r3 = vld1q_u8 (src + 48);
for (int i = 0; i < rounds - 1; i++)
{
r0 = vaesimcq_u8 (vaesdq_u8 (r0, k[i]));
r1 = vaesimcq_u8 (vaesdq_u8 (r1, k[i]));
r2 = vaesimcq_u8 (vaesdq_u8 (r2, k[i]));
r3 = vaesimcq_u8 (vaesdq_u8 (r3, k[i]));
}
r0 = vaesdq_u8 (r0, k[rounds - 1]) ^ k[rounds];
r1 = vaesdq_u8 (r1, k[rounds - 1]) ^ k[rounds];
r2 = vaesdq_u8 (r2, k[rounds - 1]) ^ k[rounds];
r3 = vaesdq_u8 (r3, k[rounds - 1]) ^ k[rounds];
vst1q_u8 (dst, r0 ^ f);
vst1q_u8 (dst + 16, r1 ^ c0);
vst1q_u8 (dst + 32, r2 ^ c1);
vst1q_u8 (dst + 48, r3 ^ c2);
f = c3;
src += 64;
dst += 64;
count -= 64;
}
while (count >= 16)
{
c0 = r0 = vld1q_u8 (src);
for (int i = 0; i < rounds - 1; i++)
r0 = vaesimcq_u8 (vaesdq_u8 (r0, k[i]));
r0 = vaesdq_u8 (r0, k[rounds - 1]) ^ k[rounds];
vst1q_u8 (dst, r0 ^ f);
f = c0;
src += 16;
dst += 16;
count -= 16;
}
}
static_always_inline u32
aesni_ops_enc_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
u32 n_ops, aes_key_size_t ks)
{
crypto_native_main_t *cm = &crypto_native_main;
crypto_native_per_thread_data_t *ptd =
vec_elt_at_index (cm->per_thread_data, vm->thread_index);
int rounds = AES_KEY_ROUNDS (ks);
u8 dummy[8192];
u32 i, j, count, n_left = n_ops;
u32x4 dummy_mask = { };
u32x4 len = { };
vnet_crypto_key_index_t key_index[4];
u8 *src[4] = { };
u8 *dst[4] = { };
u8x16 r[4] = { };
u8x16 k[15][4] = { };
for (i = 0; i < 4; i++)
key_index[i] = ~0;
more:
for (i = 0; i < 4; i++)
if (len[i] == 0)
{
if (n_left == 0)
{
/* no more work to enqueue, so we are enqueueing dummy buffer */
src[i] = dst[i] = dummy;
len[i] = sizeof (dummy);
dummy_mask[i] = 0;
}
else
{
if (ops[0]->flags & VNET_CRYPTO_OP_FLAG_INIT_IV)
{
r[i] = ptd->cbc_iv[i];
vst1q_u8 (ops[0]->iv, r[i]);
ptd->cbc_iv[i] = vaeseq_u8 (r[i], r[i]);
}
else
r[i] = vld1q_u8 (ops[0]->iv);
src[i] = ops[0]->src;
dst[i] = ops[0]->dst;
len[i] = ops[0]->len;
dummy_mask[i] = ~0;
if (key_index[i] != ops[0]->key_index)
{
aes_cbc_key_data_t *kd;
key_index[i] = ops[0]->key_index;
kd = (aes_cbc_key_data_t *) cm->key_data[key_index[i]];
for (j = 0; j < rounds + 1; j++)
k[j][i] = kd->encrypt_key[j];
}
ops[0]->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
n_left--;
ops++;
}
}
count = u32x4_min_scalar (len);
ASSERT (count % 16 == 0);
for (i = 0; i < count; i += 16)
{
r[0] ^= vld1q_u8 (src[0] + i);
r[1] ^= vld1q_u8 (src[1] + i);
r[2] ^= vld1q_u8 (src[2] + i);
r[3] ^= vld1q_u8 (src[3] + i);
for (j = 0; j < rounds - 1; j++)
{
r[0] = vaesmcq_u8 (vaeseq_u8 (r[0], k[j][0]));
r[1] = vaesmcq_u8 (vaeseq_u8 (r[1], k[j][1]));
r[2] = vaesmcq_u8 (vaeseq_u8 (r[2], k[j][2]));
r[3] = vaesmcq_u8 (vaeseq_u8 (r[3], k[j][3]));
}
r[0] = vaeseq_u8 (r[0], k[j][0]) ^ k[rounds][0];
r[1] = vaeseq_u8 (r[1], k[j][1]) ^ k[rounds][1];
r[2] = vaeseq_u8 (r[2], k[j][2]) ^ k[rounds][2];
r[3] = vaeseq_u8 (r[3], k[j][3]) ^ k[rounds][3];
vst1q_u8 (dst[0] + i, r[0]);
vst1q_u8 (dst[1] + i, r[1]);
vst1q_u8 (dst[2] + i, r[2]);
vst1q_u8 (dst[3] + i, r[3]);
}
for (i = 0; i < 4; i++)
{
src[i] += count;
dst[i] += count;
len[i] -= count;
}
if (n_left > 0)
goto more;
if (!u32x4_is_all_zero (len & dummy_mask))
goto more;
return n_ops;
}
static_always_inline u32
aesni_ops_dec_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
u32 n_ops, aes_key_size_t ks)
{
crypto_native_main_t *cm = &crypto_native_main;
int rounds = AES_KEY_ROUNDS (ks);
vnet_crypto_op_t *op = ops[0];
aes_cbc_key_data_t *kd = (aes_cbc_key_data_t *) cm->key_data[op->key_index];
u32 n_left = n_ops;
ASSERT (n_ops >= 1);
decrypt:
aes_cbc_dec (kd->decrypt_key, op->src, op->dst, op->iv, op->len, rounds);
op->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
if (--n_left)
{
op += 1;
kd = (aes_cbc_key_data_t *) cm->key_data[op->key_index];
goto decrypt;
}
return n_ops;
}
#endif
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/plugins/crypto_native/aes_cbc_aesni.h
|
<filename>src/plugins/crypto_native/aes_cbc_aesni.h<gh_stars>1-10
/*
*------------------------------------------------------------------
* Copyright (c) 2020 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*------------------------------------------------------------------
*/
#ifdef __x86_64__
static_always_inline u8x16 __clib_unused
xor3 (u8x16 a, u8x16 b, u8x16 c)
{
#if __AVX512F__
return (u8x16) _mm_ternarylogic_epi32 ((__m128i) a, (__m128i) b,
(__m128i) c, 0x96);
#endif
return a ^ b ^ c;
}
#if __VAES__
static_always_inline __m512i
xor3_x4 (__m512i a, __m512i b, __m512i c)
{
return _mm512_ternarylogic_epi32 (a, b, c, 0x96);
}
static_always_inline __m512i
aes_block_load_x4 (u8 * src[], int i)
{
__m512i r = { };
r = _mm512_inserti64x2 (r, (__m128i) aes_block_load (src[0] + i), 0);
r = _mm512_inserti64x2 (r, (__m128i) aes_block_load (src[1] + i), 1);
r = _mm512_inserti64x2 (r, (__m128i) aes_block_load (src[2] + i), 2);
r = _mm512_inserti64x2 (r, (__m128i) aes_block_load (src[3] + i), 3);
return r;
}
static_always_inline void
aes_block_store_x4 (u8 * dst[], int i, __m512i r)
{
aes_block_store (dst[0] + i, (u8x16) _mm512_extracti64x2_epi64 (r, 0));
aes_block_store (dst[1] + i, (u8x16) _mm512_extracti64x2_epi64 (r, 1));
aes_block_store (dst[2] + i, (u8x16) _mm512_extracti64x2_epi64 (r, 2));
aes_block_store (dst[3] + i, (u8x16) _mm512_extracti64x2_epi64 (r, 3));
}
#endif
static_always_inline void __clib_unused
aes_cbc_dec (u8x16 * k, u8 * src, u8 * dst, u8 * iv, int count,
aes_key_size_t rounds)
{
u8x16 r0, r1, r2, r3, c0, c1, c2, c3, f;
int i;
f = aes_block_load (iv);
while (count >= 64)
{
_mm_prefetch (src + 128, _MM_HINT_T0);
_mm_prefetch (dst + 128, _MM_HINT_T0);
c0 = aes_block_load (src);
c1 = aes_block_load (src + 16);
c2 = aes_block_load (src + 32);
c3 = aes_block_load (src + 48);
r0 = c0 ^ k[0];
r1 = c1 ^ k[0];
r2 = c2 ^ k[0];
r3 = c3 ^ k[0];
for (i = 1; i < rounds; i++)
{
r0 = aes_dec_round (r0, k[i]);
r1 = aes_dec_round (r1, k[i]);
r2 = aes_dec_round (r2, k[i]);
r3 = aes_dec_round (r3, k[i]);
}
r0 = aes_dec_last_round (r0, k[i]);
r1 = aes_dec_last_round (r1, k[i]);
r2 = aes_dec_last_round (r2, k[i]);
r3 = aes_dec_last_round (r3, k[i]);
aes_block_store (dst, r0 ^ f);
aes_block_store (dst + 16, r1 ^ c0);
aes_block_store (dst + 32, r2 ^ c1);
aes_block_store (dst + 48, r3 ^ c2);
f = c3;
count -= 64;
src += 64;
dst += 64;
}
while (count > 0)
{
c0 = aes_block_load (src);
r0 = c0 ^ k[0];
for (i = 1; i < rounds; i++)
r0 = aes_dec_round (r0, k[i]);
r0 = aes_dec_last_round (r0, k[i]);
aes_block_store (dst, r0 ^ f);
f = c0;
count -= 16;
src += 16;
dst += 16;
}
}
#ifdef __VAES__
static_always_inline void
vaes_cbc_dec (__m512i * k, u8 * src, u8 * dst, u8 * iv, int count,
aes_key_size_t rounds)
{
__m512i permute = { 6, 7, 8, 9, 10, 11, 12, 13 };
__m512i r0, r1, r2, r3, c0, c1, c2, c3, f = { };
__mmask8 m;
int i, n_blocks = count >> 4;
f = _mm512_mask_loadu_epi64 (f, 0xc0, (__m512i *) (iv - 48));
while (n_blocks >= 16)
{
c0 = _mm512_loadu_si512 ((__m512i *) src);
c1 = _mm512_loadu_si512 ((__m512i *) (src + 64));
c2 = _mm512_loadu_si512 ((__m512i *) (src + 128));
c3 = _mm512_loadu_si512 ((__m512i *) (src + 192));
r0 = c0 ^ k[0];
r1 = c1 ^ k[0];
r2 = c2 ^ k[0];
r3 = c3 ^ k[0];
for (i = 1; i < rounds; i++)
{
r0 = _mm512_aesdec_epi128 (r0, k[i]);
r1 = _mm512_aesdec_epi128 (r1, k[i]);
r2 = _mm512_aesdec_epi128 (r2, k[i]);
r3 = _mm512_aesdec_epi128 (r3, k[i]);
}
r0 = _mm512_aesdeclast_epi128 (r0, k[i]);
r1 = _mm512_aesdeclast_epi128 (r1, k[i]);
r2 = _mm512_aesdeclast_epi128 (r2, k[i]);
r3 = _mm512_aesdeclast_epi128 (r3, k[i]);
r0 ^= _mm512_permutex2var_epi64 (f, permute, c0);
_mm512_storeu_si512 ((__m512i *) dst, r0);
r1 ^= _mm512_permutex2var_epi64 (c0, permute, c1);
_mm512_storeu_si512 ((__m512i *) (dst + 64), r1);
r2 ^= _mm512_permutex2var_epi64 (c1, permute, c2);
_mm512_storeu_si512 ((__m512i *) (dst + 128), r2);
r3 ^= _mm512_permutex2var_epi64 (c2, permute, c3);
_mm512_storeu_si512 ((__m512i *) (dst + 192), r3);
f = c3;
n_blocks -= 16;
src += 256;
dst += 256;
}
while (n_blocks > 0)
{
m = (1 << (n_blocks * 2)) - 1;
c0 = _mm512_mask_loadu_epi64 (c0, m, (__m512i *) src);
f = _mm512_permutex2var_epi64 (f, permute, c0);
r0 = c0 ^ k[0];
for (i = 1; i < rounds; i++)
r0 = _mm512_aesdec_epi128 (r0, k[i]);
r0 = _mm512_aesdeclast_epi128 (r0, k[i]);
_mm512_mask_storeu_epi64 ((__m512i *) dst, m, r0 ^ f);
f = c0;
n_blocks -= 4;
src += 64;
dst += 64;
}
}
#endif
#ifdef __VAES__
#define N 16
#define u32xN u32x16
#define u32xN_min_scalar u32x16_min_scalar
#define u32xN_is_all_zero u32x16_is_all_zero
#else
#define N 4
#define u32xN u32x4
#define u32xN_min_scalar u32x4_min_scalar
#define u32xN_is_all_zero u32x4_is_all_zero
#endif
static_always_inline u32
aesni_ops_enc_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
u32 n_ops, aes_key_size_t ks)
{
crypto_native_main_t *cm = &crypto_native_main;
crypto_native_per_thread_data_t *ptd =
vec_elt_at_index (cm->per_thread_data, vm->thread_index);
int rounds = AES_KEY_ROUNDS (ks);
u8 dummy[8192];
u32 i, j, count, n_left = n_ops;
u32xN dummy_mask = { };
u32xN len = { };
vnet_crypto_key_index_t key_index[N];
u8 *src[N] = { };
u8 *dst[N] = { };
/* *INDENT-OFF* */
union
{
u8x16 x1[N];
__m512i x4[N / 4];
} r = { }, k[15] = { };
/* *INDENT-ON* */
for (i = 0; i < N; i++)
key_index[i] = ~0;
more:
for (i = 0; i < N; i++)
if (len[i] == 0)
{
if (n_left == 0)
{
/* no more work to enqueue, so we are enqueueing dummy buffer */
src[i] = dst[i] = dummy;
len[i] = sizeof (dummy);
dummy_mask[i] = 0;
}
else
{
if (ops[0]->flags & VNET_CRYPTO_OP_FLAG_INIT_IV)
{
r.x1[i] = ptd->cbc_iv[i];
aes_block_store (ops[0]->iv, r.x1[i]);
ptd->cbc_iv[i] = aes_enc_round (r.x1[i], r.x1[i]);
}
else
r.x1[i] = aes_block_load (ops[0]->iv);
src[i] = ops[0]->src;
dst[i] = ops[0]->dst;
len[i] = ops[0]->len;
dummy_mask[i] = ~0;
if (key_index[i] != ops[0]->key_index)
{
aes_cbc_key_data_t *kd;
key_index[i] = ops[0]->key_index;
kd = (aes_cbc_key_data_t *) cm->key_data[key_index[i]];
for (j = 0; j < rounds + 1; j++)
k[j].x1[i] = kd->encrypt_key[j];
}
ops[0]->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
n_left--;
ops++;
}
}
count = u32xN_min_scalar (len);
ASSERT (count % 16 == 0);
for (i = 0; i < count; i += 16)
{
#ifdef __VAES__
r.x4[0] = xor3_x4 (r.x4[0], aes_block_load_x4 (src, i), k[0].x4[0]);
r.x4[1] = xor3_x4 (r.x4[1], aes_block_load_x4 (src, i), k[0].x4[1]);
r.x4[2] = xor3_x4 (r.x4[2], aes_block_load_x4 (src, i), k[0].x4[2]);
r.x4[3] = xor3_x4 (r.x4[3], aes_block_load_x4 (src, i), k[0].x4[3]);
for (j = 1; j < rounds; j++)
{
r.x4[0] = _mm512_aesenc_epi128 (r.x4[0], k[j].x4[0]);
r.x4[1] = _mm512_aesenc_epi128 (r.x4[1], k[j].x4[1]);
r.x4[2] = _mm512_aesenc_epi128 (r.x4[2], k[j].x4[2]);
r.x4[3] = _mm512_aesenc_epi128 (r.x4[3], k[j].x4[3]);
}
r.x4[0] = _mm512_aesenclast_epi128 (r.x4[0], k[j].x4[0]);
r.x4[1] = _mm512_aesenclast_epi128 (r.x4[1], k[j].x4[1]);
r.x4[2] = _mm512_aesenclast_epi128 (r.x4[2], k[j].x4[2]);
r.x4[3] = _mm512_aesenclast_epi128 (r.x4[3], k[j].x4[3]);
aes_block_store_x4 (dst, i, r.x4[0]);
aes_block_store_x4 (dst + 4, i, r.x4[1]);
aes_block_store_x4 (dst + 8, i, r.x4[2]);
aes_block_store_x4 (dst + 12, i, r.x4[3]);
#else
r.x1[0] = xor3 (r.x1[0], aes_block_load (src[0] + i), k[0].x1[0]);
r.x1[1] = xor3 (r.x1[1], aes_block_load (src[1] + i), k[0].x1[1]);
r.x1[2] = xor3 (r.x1[2], aes_block_load (src[2] + i), k[0].x1[2]);
r.x1[3] = xor3 (r.x1[3], aes_block_load (src[3] + i), k[0].x1[3]);
for (j = 1; j < rounds; j++)
{
r.x1[0] = aes_enc_round (r.x1[0], k[j].x1[0]);
r.x1[1] = aes_enc_round (r.x1[1], k[j].x1[1]);
r.x1[2] = aes_enc_round (r.x1[2], k[j].x1[2]);
r.x1[3] = aes_enc_round (r.x1[3], k[j].x1[3]);
}
r.x1[0] = aes_enc_last_round (r.x1[0], k[j].x1[0]);
r.x1[1] = aes_enc_last_round (r.x1[1], k[j].x1[1]);
r.x1[2] = aes_enc_last_round (r.x1[2], k[j].x1[2]);
r.x1[3] = aes_enc_last_round (r.x1[3], k[j].x1[3]);
aes_block_store (dst[0] + i, r.x1[0]);
aes_block_store (dst[1] + i, r.x1[1]);
aes_block_store (dst[2] + i, r.x1[2]);
aes_block_store (dst[3] + i, r.x1[3]);
#endif
}
for (i = 0; i < N; i++)
{
src[i] += count;
dst[i] += count;
len[i] -= count;
}
if (n_left > 0)
goto more;
if (!u32xN_is_all_zero (len & dummy_mask))
goto more;
return n_ops;
}
static_always_inline u32
aesni_ops_dec_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
u32 n_ops, aes_key_size_t ks)
{
crypto_native_main_t *cm = &crypto_native_main;
int rounds = AES_KEY_ROUNDS (ks);
vnet_crypto_op_t *op = ops[0];
aes_cbc_key_data_t *kd = (aes_cbc_key_data_t *) cm->key_data[op->key_index];
u32 n_left = n_ops;
ASSERT (n_ops >= 1);
decrypt:
#ifdef __VAES__
vaes_cbc_dec (kd->decrypt_key, op->src, op->dst, op->iv, op->len, rounds);
#else
aes_cbc_dec (kd->decrypt_key, op->src, op->dst, op->iv, op->len, rounds);
#endif
op->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
if (--n_left)
{
op += 1;
kd = (aes_cbc_key_data_t *) cm->key_data[op->key_index];
goto decrypt;
}
return n_ops;
}
#endif
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/vppinfra/time.c
|
/*
* Copyright (c) 2015 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Copyright (c) 2005 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <vppinfra/os.h>
#include <vppinfra/time.h>
#include <vppinfra/format.h>
#include <vppinfra/cpu.h>
#include <math.h>
#ifdef CLIB_UNIX
#include <math.h>
#include <sys/time.h>
#include <fcntl.h>
/* Not very accurate way of determining cpu clock frequency
for unix. Better to use /proc/cpuinfo on linux. */
static f64
estimate_clock_frequency (f64 sample_time)
{
f64 time_now, time_start, time_limit, freq;
u64 t[2];
time_start = time_now = unix_time_now ();
time_limit = time_now + sample_time;
t[0] = clib_cpu_time_now ();
while (time_now < time_limit)
time_now = unix_time_now ();
t[1] = clib_cpu_time_now ();
freq = (t[1] - t[0]) / (time_now - time_start);
return freq;
}
/* Fetch cpu frequency via parseing /proc/cpuinfo.
Only works for Linux. */
static f64
clock_frequency_from_proc_filesystem (void)
{
f64 cpu_freq = 1e9; /* better than 40... */
f64 ppc_timebase = 0; /* warnings be gone */
int fd;
unformat_input_t input;
/* $$$$ aarch64 kernel doesn't report "cpu MHz" */
#if defined(__aarch64__)
return 0.0;
#endif
cpu_freq = 0;
fd = open ("/proc/cpuinfo", 0);
if (fd < 0)
return cpu_freq;
unformat_init_clib_file (&input, fd);
ppc_timebase = 0;
while (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (&input, "cpu MHz : %f", &cpu_freq))
cpu_freq *= 1e6;
else if (unformat (&input, "timebase : %f", &ppc_timebase))
;
else
unformat_skip_line (&input);
}
unformat_free (&input);
close (fd);
/* Override CPU frequency with time base for PPC. */
if (ppc_timebase != 0)
cpu_freq = ppc_timebase;
return cpu_freq;
}
/* Fetch cpu frequency via reading /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
Only works for Linux. */
static f64
clock_frequency_from_sys_filesystem (void)
{
f64 cpu_freq = 0.0;
int fd;
unformat_input_t input;
/* Time stamp always runs at max frequency. */
cpu_freq = 0;
fd = open ("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", 0);
if (fd < 0)
goto done;
unformat_init_clib_file (&input, fd);
(void) unformat (&input, "%f", &cpu_freq);
cpu_freq *= 1e3; /* measured in kHz */
unformat_free (&input);
close (fd);
done:
return cpu_freq;
}
f64
os_cpu_clock_frequency (void)
{
#if defined (__aarch64__)
/* The system counter increments at a fixed frequency. It is distributed
* to each core which has registers for reading the current counter value
* as well as the clock frequency. The system counter is not clocked at
* the same frequency as the core. */
u64 hz;
asm volatile ("mrs %0, cntfrq_el0":"=r" (hz));
return (f64) hz;
#endif
f64 cpu_freq;
#ifdef __x86_64__
u32 __clib_unused eax = 0, ebx = 0, ecx = 0, edx = 0;
clib_get_cpuid (0x00, &eax, &ebx, &ecx, &edx);
if (eax >= 0x15)
{
u32 max_leaf = eax;
/*
CPUID Leaf 0x15 - Time Stamp Counter and Nominal Core Crystal Clock Info
eax - denominator of the TSC/”core crystal clock” ratio
ebx - numerator of the TSC/”core crystal clock” ratio
ecx - nominal frequency of the core crystal clock in Hz
edx - reseved
*/
clib_get_cpuid (0x15, &eax, &ebx, &ecx, &edx);
if (ebx && ecx)
return ecx * ebx / eax;
if (max_leaf >= 0x16)
{
/*
CPUID Leaf 0x16 - Processor Frequency Information Leaf
eax - Bits 15 - 00: Processor Base Frequency (in MHz).
*/
clib_get_cpuid (0x16, &eax, &ebx, &ecx, &edx);
if (eax)
return 1e6 * (eax & 0xffff);
}
}
#endif
/* If we have an invariant TSC, use it to estimate the clock frequency */
if (clib_cpu_supports_invariant_tsc ())
return estimate_clock_frequency (1e-3);
/* Next, try /sys version. */
cpu_freq = clock_frequency_from_sys_filesystem ();
if (cpu_freq != 0)
return cpu_freq;
/* Next try /proc version. */
cpu_freq = clock_frequency_from_proc_filesystem ();
if (cpu_freq != 0)
return cpu_freq;
/* If /proc/cpuinfo fails (e.g. not running on Linux) fall back to
gettimeofday based estimated clock frequency. */
return estimate_clock_frequency (1e-3);
}
#endif /* CLIB_UNIX */
/* Initialize time. */
void
clib_time_init (clib_time_t * c)
{
clib_memset (c, 0, sizeof (c[0]));
c->clocks_per_second = os_cpu_clock_frequency ();
/*
* Sporadic reports of os_cpu_clock_frequency() returning 0.0
* in highly parallel container environments.
* To avoid immediate division by zero:
* Step 1: try estimate_clock_frequency().
* Step 2: give up. Pretend we have a 2gHz clock.
*/
if (PREDICT_FALSE (c->clocks_per_second == 0.0))
{
c->clocks_per_second = estimate_clock_frequency (1e-3);
if (c->clocks_per_second == 0.0)
{
clib_warning ("os_cpu_clock_frequency() returned 0.0, use 2e9...");
c->clocks_per_second = 2e9;
}
}
c->seconds_per_clock = 1 / c->clocks_per_second;
c->log2_clocks_per_second = min_log2_u64 ((u64) c->clocks_per_second);
/* Verify frequency every 16 sec */
c->log2_clocks_per_frequency_verify = c->log2_clocks_per_second + 4;
c->last_verify_reference_time = unix_time_now ();
c->init_reference_time = c->last_verify_reference_time;
c->last_cpu_time = clib_cpu_time_now ();
c->init_cpu_time = c->last_verify_cpu_time = c->last_cpu_time;
c->total_cpu_time = 0ULL;
/*
* Use exponential smoothing, with a half-life of 1 minute
* reported_rate(t) = reported_rate(t-1) * K + rate(t)*(1-K)
* where K = e**(-1.0/3.75);
* 15 samples in 4 minutes
* 7.5 samples in 2 minutes,
* 3.75 samples in 1 minute, etc.
*/
c->damping_constant = exp (-1.0 / 3.75);
}
void
clib_time_verify_frequency (clib_time_t * c)
{
f64 now_reference, delta_reference, delta_reference_max;
u64 delta_clock;
f64 new_clocks_per_second, delta;
/* Ask the kernel and the CPU what time it is... */
now_reference = unix_time_now ();
c->last_cpu_time = clib_cpu_time_now ();
/* Calculate a new clock rate sample */
delta_reference = now_reference - c->last_verify_reference_time;
delta_clock = c->last_cpu_time - c->last_verify_cpu_time;
c->last_verify_cpu_time = c->last_cpu_time;
c->last_verify_reference_time = now_reference;
/*
* Is the reported reference interval non-positive,
* or off by a factor of two - or 8 seconds - whichever is larger?
* Someone reset the clock behind our back.
*/
delta_reference_max = (f64) (2ULL << c->log2_clocks_per_frequency_verify) /
(f64) (1ULL << c->log2_clocks_per_second);
delta_reference_max = delta_reference_max > 8.0 ? delta_reference_max : 8.0;
/* Ignore this sample */
if (delta_reference <= 0.0 || delta_reference > delta_reference_max)
return;
/*
* Reject large frequency changes, another consequence of
* system clock changes particularly with old kernels.
*/
new_clocks_per_second = ((f64) delta_clock) / delta_reference;
/* Compute abs(rate change) */
delta = new_clocks_per_second - c->clocks_per_second;
if (delta < 0.0)
delta = -delta;
/* If rate change > 1%, reject this sample */
if (PREDICT_FALSE ((delta / c->clocks_per_second) > .01))
{
clib_warning ("Rejecting large frequency change of %.2f%%",
(delta / c->clocks_per_second) * 100.0);
return;
}
/* Add sample to the exponentially-smoothed rate */
c->clocks_per_second = c->clocks_per_second * c->damping_constant +
(1.0 - c->damping_constant) * new_clocks_per_second;
c->seconds_per_clock = 1.0 / c->clocks_per_second;
/*
* Recalculate total_cpu_time based on the kernel timebase, and
* the calculated clock rate
*/
c->total_cpu_time =
(now_reference - c->init_reference_time) * c->clocks_per_second;
}
u8 *
format_clib_time (u8 * s, va_list * args)
{
clib_time_t *c = va_arg (*args, clib_time_t *);
int verbose = va_arg (*args, int);
f64 now, reftime, delta_reftime_in_seconds, error;
/* Compute vpp elapsed time from the CPU clock */
reftime = unix_time_now ();
now = clib_time_now (c);
s = format (s, "Time now %.6f", now);
if (verbose == 0)
return s;
/* And also from the kernel */
delta_reftime_in_seconds = reftime - c->init_reference_time;
error = now - delta_reftime_in_seconds;
s = format (s, ", reftime %.6f, error %.6f, clocks/sec %.6f",
delta_reftime_in_seconds, error, c->clocks_per_second);
return (s);
}
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/plugins/srv6-mobile/node.c
|
/*
* Copyright (c) 2019 Arrcus Inc and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vppinfra/error.h>
#include <vppinfra/hash.h>
#include <srv6-mobile/mobile.h>
extern ip6_address_t sr_pr_encaps_src;
typedef struct
{
ip6_address_t src, dst;
ip6_address_t sr_prefix;
u16 sr_prefixlen;
u32 teid;
} srv6_end_rewrite_trace_t;
static u16 srh_tagfield[256] = {
/* 0 */
0x0,
/* 1 : Echo Request */
0x0004,
/* 2 : Echo Reply */
0x0008,
/* 3 - 7 */
0x0, 0x0, 0x0, 0x0, 0x0,
/* 8 - 15 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* 16 - 23 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* 24 - 25 */
0x0, 0x0,
/* 26 : Error Indication */
0x0002,
/* 27 - 31 */
0x0, 0x0, 0x0, 0x0, 0x0,
/* 32 - 247 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* 248 - 253 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* 254 : End Maker */
0x0001,
/* 255 : G_PDU */
0x0
};
static u8 *
format_srv6_end_rewrite_trace (u8 * s, va_list * args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
srv6_end_rewrite_trace_t *t = va_arg (*args, srv6_end_rewrite_trace_t *);
return format (s, "SRv6-END-rewrite: src %U dst %U\n\tTEID: 0x%x",
format_ip4_address, &t->src, format_ip4_address, &t->dst,
clib_net_to_host_u32 (t->teid));
}
static u8 *
format_srv6_end_rewrite_trace6 (u8 * s, va_list * args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
srv6_end_rewrite_trace_t *t = va_arg (*args, srv6_end_rewrite_trace_t *);
return format (s,
"SRv6-END-rewrite: src %U dst %U\n\tTEID: 0x%x\n\tsr_prefix: %U/%d",
format_ip6_address, &t->src, format_ip6_address, &t->dst,
clib_net_to_host_u32 (t->teid), format_ip6_address,
&t->sr_prefix, t->sr_prefixlen);
}
#define foreach_srv6_end_v4_error \
_(M_GTP4_E_PACKETS, "srv6 End.M.GTP4.E packets") \
_(M_GTP4_E_BAD_PACKETS, "srv6 End.M.GTP4.E bad packets")
#define foreach_srv6_t_v4_d_error \
_(M_GTP4_D_PACKETS, "srv6 T.M.GTP4.D packets") \
_(M_GTP4_D_BAD_PACKETS, "srv6 T.M.GTP4.D bad packets")
#define foreach_srv6_end_v6_e_error \
_(M_GTP6_E_PACKETS, "srv6 End.M.GTP6.E packets") \
_(M_GTP6_E_BAD_PACKETS, "srv6 End.M.GTP6.E bad packets")
#define foreach_srv6_end_v6_d_error \
_(M_GTP6_D_PACKETS, "srv6 End.M.GTP6.D packets") \
_(M_GTP6_D_BAD_PACKETS, "srv6 End.M.GTP6.D bad packets")
#define foreach_srv6_end_v6_d_di_error \
_(M_GTP6_D_DI_PACKETS, "srv6 End.M.GTP6.D.DI packets") \
_(M_GTP6_D_DI_BAD_PACKETS, "srv6 End.M.GTP6.D.DI bad packets")
typedef enum
{
#define _(sym,str) SRV6_END_ERROR_##sym,
foreach_srv6_end_v4_error
#undef _
SRV6_END_N_V4_ERROR,
} srv6_end_error_v4_t;
typedef enum
{
#define _(sym,str) SRV6_T_ERROR_##sym,
foreach_srv6_t_v4_d_error
#undef _
SRV6_T_N_V4_D_ERROR,
} srv6_t_error_v4_d_t;
typedef enum
{
#define _(sym,str) SRV6_END_ERROR_##sym,
foreach_srv6_end_v6_e_error
#undef _
SRV6_END_N_V6_E_ERROR,
} srv6_end_error_v6_e_t;
typedef enum
{
#define _(sym,str) SRV6_END_ERROR_##sym,
foreach_srv6_end_v6_d_error
#undef _
SRV6_END_N_V6_D_ERROR,
} srv6_end_error_v6_d_t;
typedef enum
{
#define _(sym,str) SRV6_END_ERROR_##sym,
foreach_srv6_end_v6_d_di_error
#undef _
SRV6_END_N_V6_D_DI_ERROR,
} srv6_end_error_v6_d_di_t;
static char *srv6_end_error_v4_strings[] = {
#define _(sym,string) string,
foreach_srv6_end_v4_error
#undef _
};
static char *srv6_t_error_v4_d_strings[] = {
#define _(sym,string) string,
foreach_srv6_t_v4_d_error
#undef _
};
static char *srv6_end_error_v6_e_strings[] = {
#define _(sym,string) string,
foreach_srv6_end_v6_e_error
#undef _
};
static char *srv6_end_error_v6_d_strings[] = {
#define _(sym,string) string,
foreach_srv6_end_v6_d_error
#undef _
};
static char *srv6_end_error_v6_d_di_strings[] = {
#define _(sym,string) string,
foreach_srv6_end_v6_d_di_error
#undef _
};
typedef enum
{
SRV6_END_M_GTP4_E_NEXT_DROP,
SRV6_END_M_GTP4_E_NEXT_LOOKUP,
SRV6_END_M_GTP4_E_N_NEXT,
} srv6_end_m_gtp4_e_next_t;
typedef enum
{
SRV6_T_M_GTP4_D_NEXT_DROP,
SRV6_T_M_GTP4_D_NEXT_LOOKUP,
SRV6_T_M_GTP4_D_N_NEXT,
} srv6_T_m_gtp4_d_next_t;
typedef enum
{
SRV6_END_M_GTP6_E_NEXT_DROP,
SRV6_END_M_GTP6_E_NEXT_LOOKUP,
SRV6_END_M_GTP6_E_N_NEXT,
} srv6_end_m_gtp6_e_next_t;
typedef enum
{
SRV6_END_M_GTP6_D_NEXT_DROP,
SRV6_END_M_GTP6_D_NEXT_LOOKUP,
SRV6_END_M_GTP6_D_N_NEXT,
} srv6_end_m_gtp6_d_next_t;
typedef enum
{
SRV6_END_M_GTP6_D_DI_NEXT_DROP,
SRV6_END_M_GTP6_D_DI_NEXT_LOOKUP,
SRV6_END_M_GTP6_D_DI_N_NEXT,
} srv6_end_m_gtp6_d_di_next_t;
static inline u16
hash_uword_to_u16 (uword * key)
{
u16 *val;
val = (u16 *) key;
#if uword_bits == 64
return val[0] ^ val[1] ^ val[2] ^ val[3];
#else
return val[0] ^ val[1];
#endif
}
static inline u8
gtpu_type_get (u16 tag)
{
u16 val;
val = clib_net_to_host_u16 (tag);
if (val & SRH_TAG_ECHO_REPLY)
return GTPU_TYPE_ECHO_REPLY;
else if (val & SRH_TAG_ECHO_REQUEST)
return GTPU_TYPE_ECHO_REQUEST;
else if (val & SRH_TAG_ERROR_INDICATION)
return GTPU_TYPE_ERROR_INDICATION;
else if (val & SRH_TAG_END_MARKER)
return GTPU_TYPE_END_MARKER;
return GTPU_TYPE_GTPU;
}
// Function for SRv6 GTP4.E function.
VLIB_NODE_FN (srv6_end_m_gtp4_e) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
srv6_end_main_v4_t *sm = &srv6_end_main_v4;
ip6_sr_main_t *sm2 = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
u32 thread_index = vm->thread_index;
u32 good_n = 0, bad_n = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_sr_localsid_t *ls0;
srv6_end_gtp4_param_t *ls_param;
ip6srv_combo_header_t *ip6srv0;
ip6_address_t src0, dst0;
ip4_gtpu_header_t *hdr0 = NULL;
uword len0;
u32 next0 = SRV6_END_M_GTP4_E_NEXT_LOOKUP;
// defaults
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
ls0 =
pool_elt_at_index (sm2->localsids,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ls_param = (srv6_end_gtp4_param_t *) ls0->plugin_mem;
ip6srv0 = vlib_buffer_get_current (b0);
src0 = ip6srv0->ip.src_address;
dst0 = ip6srv0->ip.dst_address;
len0 = vlib_buffer_length_in_chain (vm, b0);
if ((ip6srv0->ip.protocol == IPPROTO_IPV6_ROUTE
&& len0 <
sizeof (ip6srv_combo_header_t) + ip6srv0->sr.length * 8)
|| (len0 < sizeof (ip6_header_t)))
{
next0 = SRV6_END_M_GTP4_E_NEXT_DROP;
bad_n++;
}
else
{
u8 gtpu_type = 0;
u16 tag = 0;
u32 teid = 0;
u8 *teid8p = (u8 *) & teid;
u8 qfi = 0;
u16 seq = 0;
u32 index;
u32 offset, shift;
u32 hdrlen = 0;
uword key;
u16 port;
ip4_address_t dst4;
void *p;
// we need to be sure there is enough space before
// ip6srv0 header, there is some extra space
// in the pre_data area for this kind of
// logic
// jump over variable length data
// not sure about the length
if (ip6srv0->ip.protocol == IPPROTO_IPV6_ROUTE)
{
tag = ip6srv0->sr.tag;
vlib_buffer_advance (b0,
(word) sizeof (ip6srv_combo_header_t) +
ip6srv0->sr.length * 8);
}
else
{
vlib_buffer_advance (b0, (word) sizeof (ip6_header_t));
}
// get length of encapsulated IPv6 packet (the remaining part)
p = vlib_buffer_get_current (b0);
len0 = vlib_buffer_length_in_chain (vm, b0);
offset = ls0->localsid_len / 8;
shift = ls0->localsid_len % 8;
gtpu_type = gtpu_type_get (tag);
if (PREDICT_TRUE (shift == 0))
{
clib_memcpy_fast (&dst4.as_u8[0], &dst0.as_u8[offset], 4);
qfi = dst0.as_u8[offset + 4];
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
clib_memcpy_fast (&seq, &dst0.as_u8[offset + 5], 2);
}
else
{
clib_memcpy_fast (teid8p, &dst0.as_u8[offset + 5], 4);
}
}
else
{
u8 *sp;
for (index = 0; index < 4; index++)
{
dst4.as_u8[index] = dst0.as_u8[offset + index] << shift;
dst4.as_u8[index] |=
dst0.as_u8[offset + index + 1] >> (8 - shift);
}
qfi |= dst0.as_u8[offset + 4] << shift;
qfi |= dst0.as_u8[offset + 5] >> (8 - shift);
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
sp = (u8 *) & seq;
for (index = 0; index < 2; index++)
{
sp[index] = dst0.as_u8[offset + 5 + index] << shift;
sp[index] |=
dst0.as_u8[offset + 6 + index] >> (8 - shift);
}
}
else
{
for (index = 0; index < 4; index++)
{
*teid8p = dst0.as_u8[offset + 5 + index] << shift;
*teid8p |=
dst0.as_u8[offset + 6 + index] >> (8 - shift);
teid8p++;
}
}
}
if (qfi)
{
hdrlen =
sizeof (gtpu_exthdr_t) + sizeof (gtpu_pdu_session_t);
}
else if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
hdrlen = sizeof (gtpu_exthdr_t);
}
len0 += hdrlen;
hdrlen += sizeof (ip4_gtpu_header_t);
// IPv4 GTP-U header creation.
vlib_buffer_advance (b0, -(word) hdrlen);
hdr0 = vlib_buffer_get_current (b0);
clib_memcpy_fast (hdr0, &sm->cache_hdr,
sizeof (ip4_gtpu_header_t));
hdr0->ip4.dst_address.as_u32 = dst4.as_u32;
hdr0->gtpu.teid = teid;
hdr0->gtpu.length = clib_host_to_net_u16 (len0);
hdr0->gtpu.type = gtpu_type;
if (qfi)
{
u8 type = 0;
gtpu_pdu_session_t *sess;
hdr0->gtpu.ver_flags |= GTPU_EXTHDR_FLAG;
hdr0->gtpu.ext->seq = 0;
hdr0->gtpu.ext->npdu_num = 0;
hdr0->gtpu.ext->nextexthdr = GTPU_EXTHDR_PDU_SESSION;
type = qfi & SRV6_PDU_SESSION_U_BIT_MASK;
qfi =
((qfi & SRV6_PDU_SESSION_QFI_MASK) >> 2) |
((qfi & SRV6_PDU_SESSION_R_BIT_MASK) << 5);
sess =
(gtpu_pdu_session_t *) (((char *) hdr0) +
sizeof (ip4_gtpu_header_t) +
sizeof (gtpu_exthdr_t));
sess->exthdrlen = 1;
sess->type = type;
sess->spare = 0;
sess->u.val = qfi;
sess->nextexthdr = 0;
}
if (gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
hdr0->gtpu.ver_flags |= GTPU_SEQ_FLAG;
hdr0->gtpu.ext->seq = seq;
hdr0->gtpu.ext->npdu_num = 0;
hdr0->gtpu.ext->nextexthdr = 0;
}
offset = ls_param->v4src_position / 8;
shift = ls_param->v4src_position % 8;
if (PREDICT_TRUE (shift == 0))
{
for (index = 0; index < 4; index++)
{
hdr0->ip4.src_address.as_u8[index] =
src0.as_u8[offset + index];
}
}
else
{
for (index = 0; index < 4; index++)
{
hdr0->ip4.src_address.as_u8[index] =
src0.as_u8[offset + index] << shift;
hdr0->ip4.src_address.as_u8[index] |=
src0.as_u8[offset + index + 1] >> (8 - shift);
}
}
key = hash_memory (p, len0, 0);
port = hash_uword_to_u16 (&key);
hdr0->udp.src_port = port;
hdr0->udp.length = clib_host_to_net_u16 (len0 +
sizeof (udp_header_t) +
sizeof
(gtpu_header_t));
hdr0->ip4.length = clib_host_to_net_u16 (len0 +
sizeof
(ip4_gtpu_header_t));
hdr0->ip4.checksum = ip4_header_checksum (&hdr0->ip4);
good_n++;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
srv6_end_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy (tr->src.as_u8, hdr0->ip4.src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy (tr->dst.as_u8, hdr0->ip4.dst_address.as_u8,
sizeof (tr->dst.as_u8));
tr->teid = hdr0->gtpu.teid;
}
}
vlib_increment_combined_counter
(((next0 ==
SRV6_END_M_GTP4_E_NEXT_DROP) ? &(sm2->sr_ls_invalid_counters) :
&(sm2->sr_ls_valid_counters)), thread_index,
ls0 - sm2->localsids, 1, vlib_buffer_length_in_chain (vm, b0));
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sm->end_m_gtp4_e_node_index,
SRV6_END_ERROR_M_GTP4_E_BAD_PACKETS, bad_n);
vlib_node_increment_counter (vm, sm->end_m_gtp4_e_node_index,
SRV6_END_ERROR_M_GTP4_E_PACKETS, good_n);
return frame->n_vectors;
}
// Function for SRv6 GTP4.D function.
VLIB_NODE_FN (srv6_t_m_gtp4_d) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
srv6_t_main_v4_decap_t *sm = &srv6_t_main_v4_decap;
ip6_sr_main_t *sm2 = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
u32 good_n = 0, bad_n = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_sr_sl_t *sl0;
srv6_end_gtp4_param_t *ls_param;
ip4_header_t *ip4;
uword len0;
u32 next0 = SRV6_T_M_GTP4_D_NEXT_LOOKUP;
// defaults
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm2->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ls_param = (srv6_end_gtp4_param_t *) sl0->plugin_mem;
len0 = vlib_buffer_length_in_chain (vm, b0);
ip4 = vlib_buffer_get_current (b0);
if (ip4->protocol != IP_PROTOCOL_UDP
|| len0 < sizeof (ip4_gtpu_header_t))
{
next0 = SRV6_T_M_GTP4_D_NEXT_DROP;
bad_n++;
}
else
{
uword *p;
ip6_sr_policy_t *sr_policy = NULL;
ip6_sr_sl_t *sl = NULL;
u32 *sl_index;
u32 hdr_len;
ip4_gtpu_header_t *hdr;
ip4_address_t src, dst;
u8 *srcp, *dstp;
ip6_header_t *encap = NULL;
ip6_address_t seg;
ip6_address_t src6;
u8 gtpu_type;
u32 teid;
u8 *teidp;
u8 qfi = 0;
u8 *qfip = NULL;
u16 seq = 0;
u8 *seqp;
u32 offset, shift, index;
ip6srv_combo_header_t *ip6srv;
gtpu_pdu_session_t *sess = NULL;
// Decap from GTP-U.
hdr = (ip4_gtpu_header_t *) ip4;
hdr_len = sizeof (ip4_gtpu_header_t);
teid = hdr->gtpu.teid;
teidp = (u8 *) & teid;
seqp = (u8 *) & seq;
gtpu_type = hdr->gtpu.type;
if (hdr->gtpu.ver_flags & (GTPU_EXTHDR_FLAG | GTPU_SEQ_FLAG))
{
// Extention header.
hdr_len += sizeof (gtpu_exthdr_t);
seq = hdr->gtpu.ext->seq;
if (hdr->gtpu.ext->nextexthdr == GTPU_EXTHDR_PDU_SESSION)
{
// PDU Session Container.
sess =
(gtpu_pdu_session_t *) (((char *) hdr) + hdr_len);
qfi = sess->u.val & ~GTPU_PDU_SESSION_P_BIT_MASK;
qfip = (u8 *) & qfi;
hdr_len += sizeof (gtpu_pdu_session_t);
if (sess->u.val & GTPU_PDU_SESSION_P_BIT_MASK)
{
hdr_len += sizeof (gtpu_paging_policy_t);
}
}
}
src = hdr->ip4.src_address;
srcp = (u8 *) & src;
dst = hdr->ip4.dst_address;
dstp = (u8 *) & dst;
seg = ls_param->sr_prefix;
offset = ls_param->sr_prefixlen / 8;
shift = ls_param->sr_prefixlen % 8;
if (PREDICT_TRUE (shift == 0))
{
clib_memcpy_fast (&seg.as_u8[offset], dstp, 4);
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg.as_u8[offset + 4] = qfi;
}
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
clib_memcpy_fast (&seg.as_u8[offset + 5], seqp, 2);
}
else
{
clib_memcpy_fast (&seg.as_u8[offset + 5], teidp, 4);
}
}
else
{
for (index = 0; index < 4; index++)
{
seg.as_u8[offset + index] |= dstp[index] >> shift;
seg.as_u8[offset + index + 1] |=
dstp[index] << (8 - shift);
}
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg.as_u8[offset + 4] |= qfi >> shift;
seg.as_u8[offset + 5] |= qfi << (8 - shift);
}
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
for (index = 0; index < 2; index++)
{
seg.as_u8[offset + 5 + index] |=
seqp[index] >> shift;
seg.as_u8[offset + 6 + index] |=
seqp[index] << (8 - shift);
}
}
else
{
for (index = 0; index < 4; index++)
{
seg.as_u8[offset + index + 5] |=
teidp[index] >> shift;
seg.as_u8[offset + index + 6] |=
teidp[index] << (8 - shift);
}
}
}
src6 = ls_param->v6src_prefix;
offset = ls_param->v6src_prefixlen / 8;
shift = ls_param->v6src_prefixlen % 8;
if (PREDICT_TRUE (shift == 0))
{
clib_memcpy_fast (&src6.as_u8[offset], srcp, 4);
}
else
{
for (index = 0; index < 4; index++)
{
src6.as_u8[offset + index] |= srcp[offset] >> shift;
src6.as_u8[offset + index + 1] |=
srcp[offset] << (8 - shift);
}
}
vlib_buffer_advance (b0, (word) hdr_len);
// Encap to SRv6.
if (PREDICT_TRUE (gtpu_type == GTPU_TYPE_GTPU))
{
encap = vlib_buffer_get_current (b0);
}
len0 = vlib_buffer_length_in_chain (vm, b0);
p =
mhash_get (&sm2->sr_policies_index_hash,
&ls_param->sr_prefix);
if (p)
{
sr_policy = pool_elt_at_index (sm2->sr_policies, p[0]);
}
if (sr_policy)
{
vec_foreach (sl_index, sr_policy->segments_lists)
{
sl = pool_elt_at_index (sm2->sid_lists, *sl_index);
if (sl != NULL)
break;
}
}
if (sl)
{
hdr_len = sizeof (ip6srv_combo_header_t);
hdr_len += vec_len (sl->segments) * sizeof (ip6_address_t);
hdr_len += sizeof (ip6_address_t);
}
else
{
hdr_len = sizeof (ip6_header_t);
if (PREDICT_FALSE (gtpu_type != GTPU_TYPE_GTPU))
{
hdr_len += sizeof (ip6_sr_header_t);
hdr_len += sizeof (ip6_address_t);
}
}
vlib_buffer_advance (b0, -(word) hdr_len);
ip6srv = vlib_buffer_get_current (b0);
if (sl)
{
clib_memcpy_fast (ip6srv, sl->rewrite,
vec_len (sl->rewrite));
if (vec_len (sl->segments) > 1)
{
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments_left += 1;
ip6srv->sr.last_entry += 1;
ip6srv->sr.length += sizeof (ip6_address_t) / 8;
ip6srv->sr.segments[0] = seg;
clib_memcpy_fast (&ip6srv->sr.segments[1],
(u8 *) (sl->rewrite +
sizeof (ip6_header_t) +
sizeof (ip6_sr_header_t)),
vec_len (sl->segments) *
sizeof (ip6_address_t));
}
else
{
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
ip6srv->sr.type = ROUTING_HEADER_TYPE_SR;
ip6srv->sr.segments_left = 1;
ip6srv->sr.last_entry = 0;
ip6srv->sr.length =
((sizeof (ip6_sr_header_t) +
sizeof (ip6_address_t)) / 8) - 1;
ip6srv->sr.flags = 0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments[0] = seg;
if (vec_len (sl->segments))
{
ip6srv->sr.segments[1] = sl->segments[0];
ip6srv->sr.length += sizeof (ip6_address_t) / 8;
ip6srv->sr.last_entry++;
}
}
if (PREDICT_TRUE (encap != NULL))
{
if (ls_param->nhtype == SRV6_NHTYPE_NONE)
{
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) == 6)
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
else
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV4)
{
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 4)
{
// Bad encap packet.
next0 = SRV6_T_M_GTP4_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV6)
{
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 6)
{
// Bad encap packet.
next0 = SRV6_T_M_GTP4_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_NON_IP)
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
}
else
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
}
else
{
clib_memcpy_fast (ip6srv, &sm->cache_hdr,
sizeof (ip6_header_t));
ip6srv->ip.dst_address = seg;
if (PREDICT_FALSE (gtpu_type != GTPU_TYPE_GTPU))
{
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments_left = 0;
ip6srv->sr.last_entry = 0;
ip6srv->sr.length = sizeof (ip6_address_t) / 8;
ip6srv->sr.segments[0] = seg;
}
else
{
if (ls_param->nhtype == SRV6_NHTYPE_NONE)
{
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) == 6)
ip6srv->ip.protocol = IP_PROTOCOL_IPV6;
else
ip6srv->ip.protocol = IP_PROTOCOL_IP_IN_IP;
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV4)
{
ip6srv->ip.protocol = IP_PROTOCOL_IP_IN_IP;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 4)
{
// Bad encap packet.
next0 = SRV6_T_M_GTP4_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV6)
{
ip6srv->ip.protocol = IP_PROTOCOL_IPV6;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 6)
{
// Bad encap packet.
next0 = SRV6_T_M_GTP4_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_NON_IP)
{
ip6srv->ip.protocol = IP_PROTOCOL_NONE;
}
}
}
ip6srv->ip.src_address = src6;
ip6srv->ip.payload_length =
clib_host_to_net_u16 (len0 + hdr_len - sizeof (ip6_header_t));
good_n++;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
srv6_end_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy (tr->src.as_u8, ip6srv->ip.src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy (tr->dst.as_u8, ip6srv->ip.dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
DONE:
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sm->t_m_gtp4_d_node_index,
SRV6_T_ERROR_M_GTP4_D_BAD_PACKETS, bad_n);
vlib_node_increment_counter (vm, sm->t_m_gtp4_d_node_index,
SRV6_T_ERROR_M_GTP4_D_PACKETS, good_n);
return frame->n_vectors;
}
VLIB_REGISTER_NODE (srv6_end_m_gtp4_e) =
{
.name = "srv6-end-m-gtp4-e",.vector_size = sizeof (u32),.format_trace =
format_srv6_end_rewrite_trace,.type = VLIB_NODE_TYPE_INTERNAL,.n_errors =
ARRAY_LEN (srv6_end_error_v4_strings),.error_strings =
srv6_end_error_v4_strings,.n_next_nodes =
SRV6_END_M_GTP4_E_N_NEXT,.next_nodes =
{
[SRV6_END_M_GTP4_E_NEXT_DROP] = "error-drop",
[SRV6_END_M_GTP4_E_NEXT_LOOKUP] = "ip4-lookup",}
,};
VLIB_REGISTER_NODE (srv6_t_m_gtp4_d) =
{
.name = "srv6-t-m-gtp4-d",.vector_size = sizeof (u32),.format_trace =
format_srv6_end_rewrite_trace,.type = VLIB_NODE_TYPE_INTERNAL,.n_errors =
ARRAY_LEN (srv6_t_error_v4_d_strings),.error_strings =
srv6_t_error_v4_d_strings,.n_next_nodes =
SRV6_T_M_GTP4_D_N_NEXT,.next_nodes =
{
[SRV6_T_M_GTP4_D_NEXT_DROP] = "error-drop",
[SRV6_T_M_GTP4_D_NEXT_LOOKUP] = "ip6-lookup",}
,};
// Function for SRv6 GTP6.E function
VLIB_NODE_FN (srv6_end_m_gtp6_e) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
srv6_end_main_v6_t *sm = &srv6_end_main_v6;
ip6_sr_main_t *sm2 = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
u32 thread_index = vm->thread_index;
u32 good_n = 0, bad_n = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_sr_localsid_t *ls0;
ip6srv_combo_header_t *ip6srv0;
ip6_address_t dst0, src0, seg0;
ip6_gtpu_header_t *hdr0 = NULL;
uword len0;
uword key;
u16 port;
u16 tag;
void *p;
u32 next0 = SRV6_END_M_GTP6_E_NEXT_LOOKUP;
// defaults
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
ls0 =
pool_elt_at_index (sm2->localsids,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ip6srv0 = vlib_buffer_get_current (b0);
dst0 = ip6srv0->ip.dst_address;
src0 = ip6srv0->ip.src_address;
seg0 = ip6srv0->sr.segments[0];
tag = ip6srv0->sr.tag;
len0 = vlib_buffer_length_in_chain (vm, b0);
if ((ip6srv0->ip.protocol != IPPROTO_IPV6_ROUTE)
|| (len0 <
sizeof (ip6srv_combo_header_t) + 8 * ip6srv0->sr.length))
{
next0 = SRV6_END_M_GTP6_E_NEXT_DROP;
bad_n++;
}
else
{
// we need to be sure there is enough space before
// ip6srv0 header, there is some extra space
// in the pre_data area for this kind of
// logic
// jump over variable length data
// not sure about the length
vlib_buffer_advance (b0, (word) sizeof (ip6srv_combo_header_t) +
ip6srv0->sr.length * 8);
// get length of encapsulated IPv6 packet (the remaining part)
p = vlib_buffer_get_current (b0);
len0 = vlib_buffer_length_in_chain (vm, b0);
u32 teid = 0;
u8 *teid8p = (u8 *) & teid;
u8 qfi = 0;
u16 seq = 0;
u8 gtpu_type = 0;
u16 index;
u16 offset, shift;
u32 hdrlen = 0;
index = ls0->localsid_len;
index += 8;
offset = index / 8;
shift = index % 8;
gtpu_type = gtpu_type_get (tag);
if (PREDICT_TRUE (shift == 0))
{
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
clib_memcpy_fast (&seq, &dst0.as_u8[offset], 2);
}
else
{
clib_memcpy_fast (teid8p, &dst0.as_u8[offset], 4);
}
qfi = dst0.as_u8[offset + 4];
}
else
{
u8 *sp;
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
sp = (u8 *) & seq;
for (index = 0; index < 2; index++)
{
sp[index] = dst0.as_u8[offset + index] << shift;
sp[index] |=
dst0.as_u8[offset + index + 1] >> (8 - shift);
}
}
else
{
for (index = 0; index < 4; index++)
{
*teid8p = dst0.as_u8[offset + index] << shift;
*teid8p |=
dst0.as_u8[offset + index + 1] >> (8 - shift);
teid8p++;
}
}
qfi |= dst0.as_u8[offset + 4] << shift;
qfi |= dst0.as_u8[offset + 5] >> (8 - shift);
}
if (qfi)
{
hdrlen =
sizeof (gtpu_exthdr_t) + sizeof (gtpu_pdu_session_t);
}
else if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
hdrlen = sizeof (gtpu_exthdr_t);
}
len0 += hdrlen;
hdrlen += sizeof (ip6_gtpu_header_t);
vlib_buffer_advance (b0, -(word) hdrlen);
hdr0 = vlib_buffer_get_current (b0);
clib_memcpy_fast (hdr0, &sm->cache_hdr,
sizeof (ip6_gtpu_header_t));
hdr0->gtpu.teid = teid;
hdr0->gtpu.length = clib_host_to_net_u16 (len0);
hdr0->gtpu.type = gtpu_type;
if (qfi)
{
u8 type = 0;
gtpu_pdu_session_t *sess;
hdr0->gtpu.ver_flags |= GTPU_EXTHDR_FLAG;
hdr0->gtpu.ext->seq = 0;
hdr0->gtpu.ext->npdu_num = 0;
hdr0->gtpu.ext->nextexthdr = GTPU_EXTHDR_PDU_SESSION;
type = qfi & SRV6_PDU_SESSION_U_BIT_MASK;
qfi =
((qfi & SRV6_PDU_SESSION_QFI_MASK) >> 2) |
((qfi & SRV6_PDU_SESSION_R_BIT_MASK) << 5);
sess =
(gtpu_pdu_session_t *) (((char *) hdr0) +
sizeof (ip6_gtpu_header_t) +
sizeof (gtpu_exthdr_t));
sess->exthdrlen = 1;
sess->type = type;
sess->spare = 0;
sess->u.val = qfi;
sess->nextexthdr = 0;
}
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
hdr0->gtpu.ver_flags |= GTPU_SEQ_FLAG;
hdr0->gtpu.ext->seq = seq;
hdr0->gtpu.ext->npdu_num = 0;
hdr0->gtpu.ext->nextexthdr = 0;
}
hdr0->udp.length = clib_host_to_net_u16 (len0 +
sizeof (udp_header_t) +
sizeof
(gtpu_header_t));
clib_memcpy_fast (hdr0->ip6.src_address.as_u8, src0.as_u8,
sizeof (ip6_address_t));
clib_memcpy_fast (hdr0->ip6.dst_address.as_u8, &seg0.as_u8,
sizeof (ip6_address_t));
hdr0->ip6.payload_length = clib_host_to_net_u16 (len0 +
sizeof
(udp_header_t)
+
sizeof
(gtpu_header_t));
// UDP source port.
key = hash_memory (p, len0, 0);
port = hash_uword_to_u16 (&key);
hdr0->udp.src_port = port;
good_n++;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
srv6_end_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy (tr->src.as_u8, hdr0->ip6.src_address.as_u8,
sizeof (ip6_address_t));
clib_memcpy (tr->dst.as_u8, hdr0->ip6.dst_address.as_u8,
sizeof (ip6_address_t));
tr->teid = hdr0->gtpu.teid;
}
}
vlib_increment_combined_counter
(((next0 ==
SRV6_END_M_GTP6_E_NEXT_DROP) ? &(sm2->sr_ls_invalid_counters) :
&(sm2->sr_ls_valid_counters)), thread_index,
ls0 - sm2->localsids, 1, vlib_buffer_length_in_chain (vm, b0));
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sm->end_m_gtp6_e_node_index,
SRV6_END_ERROR_M_GTP6_E_BAD_PACKETS, bad_n);
vlib_node_increment_counter (vm, sm->end_m_gtp6_e_node_index,
SRV6_END_ERROR_M_GTP6_E_PACKETS, good_n);
return frame->n_vectors;
}
// Function for SRv6 GTP6.D function
VLIB_NODE_FN (srv6_end_m_gtp6_d) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
srv6_end_main_v6_decap_t *sm = &srv6_end_main_v6_decap;
ip6_sr_main_t *sm2 = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
u32 thread_index = vm->thread_index;
u32 good_n = 0, bad_n = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_sr_localsid_t *ls0;
srv6_end_gtp6_param_t *ls_param;
ip6_gtpu_header_t *hdr0 = NULL;
uword len0;
ip6_address_t seg0, src0;
u32 teid = 0;
u8 *teidp;
u8 gtpu_type = 0;
u8 qfi;
u8 *qfip = NULL;
u16 seq = 0;
u8 *seqp;
u32 offset, shift;
u32 hdrlen;
ip6_header_t *encap = NULL;
gtpu_pdu_session_t *sess = NULL;
u32 next0 = SRV6_END_M_GTP6_D_NEXT_LOOKUP;
// defaults
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
ls0 =
pool_elt_at_index (sm2->localsids,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ls_param = (srv6_end_gtp6_param_t *) ls0->plugin_mem;
hdr0 = vlib_buffer_get_current (b0);
hdrlen = sizeof (ip6_gtpu_header_t);
len0 = vlib_buffer_length_in_chain (vm, b0);
if ((hdr0->ip6.protocol != IP_PROTOCOL_UDP)
|| (hdr0->udp.dst_port !=
clib_host_to_net_u16 (SRV6_GTP_UDP_DST_PORT))
|| (len0 < sizeof (ip6_gtpu_header_t)))
{
next0 = SRV6_END_M_GTP6_D_NEXT_DROP;
bad_n++;
}
else
{
seg0 = ls_param->sr_prefix;
src0 = hdr0->ip6.src_address;
gtpu_type = hdr0->gtpu.type;
teid = hdr0->gtpu.teid;
teidp = (u8 *) & teid;
seqp = (u8 *) & seq;
if (hdr0->gtpu.ver_flags & (GTPU_EXTHDR_FLAG | GTPU_SEQ_FLAG))
{
// Extention header.
hdrlen += sizeof (gtpu_exthdr_t);
seq = hdr0->gtpu.ext->seq;
if (hdr0->gtpu.ext->nextexthdr == GTPU_EXTHDR_PDU_SESSION)
{
// PDU Session Container.
sess =
(gtpu_pdu_session_t *) (((char *) hdr0) +
sizeof (ip6_gtpu_header_t) +
sizeof (gtpu_exthdr_t));
qfi = sess->u.val & ~GTPU_PDU_SESSION_P_BIT_MASK;
qfip = (u8 *) & qfi;
hdrlen += sizeof (gtpu_pdu_session_t);
if (sess->u.val & GTPU_PDU_SESSION_P_BIT_MASK)
{
hdrlen += sizeof (gtpu_paging_policy_t);
}
}
}
offset = ls_param->sr_prefixlen / 8;
shift = ls_param->sr_prefixlen % 8;
offset += 1;
if (PREDICT_TRUE (shift == 0))
{
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
clib_memcpy_fast (&seg0.as_u8[offset], seqp, 2);
}
else
{
clib_memcpy_fast (&seg0.as_u8[offset], teidp, 4);
}
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg0.as_u8[offset + 4] = qfi;
}
}
else
{
int idx;
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
for (idx = 0; idx < 2; idx++)
{
seg0.as_u8[offset + idx] |= seqp[idx] >> shift;
seg0.as_u8[offset + idx + 1] |=
seqp[idx] << (8 - shift);
}
}
else
{
for (idx = 0; idx < 4; idx++)
{
seg0.as_u8[offset + idx] |= teidp[idx] >> shift;
seg0.as_u8[offset + idx + 1] |=
teidp[idx] << (8 - shift);
}
}
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & ~GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg0.as_u8[offset + 4] |= qfi >> shift;
seg0.as_u8[offset + 5] |= qfi << (8 - shift);
}
}
// jump over variable length data
vlib_buffer_advance (b0, (word) hdrlen);
// get length of encapsulated IPv6 packet (the remaining part)
len0 = vlib_buffer_length_in_chain (vm, b0);
if (PREDICT_TRUE (gtpu_type == GTPU_TYPE_GTPU))
{
encap = vlib_buffer_get_current (b0);
}
uword *p;
ip6srv_combo_header_t *ip6srv;
ip6_sr_policy_t *sr_policy = NULL;
ip6_sr_sl_t *sl = NULL;
u32 *sl_index;
u32 hdr_len;
p =
mhash_get (&sm2->sr_policies_index_hash,
&ls_param->sr_prefix);
if (p)
{
sr_policy = pool_elt_at_index (sm2->sr_policies, p[0]);
}
if (sr_policy)
{
vec_foreach (sl_index, sr_policy->segments_lists)
{
sl = pool_elt_at_index (sm2->sid_lists, *sl_index);
if (sl != NULL)
break;
}
}
if (sl)
{
hdr_len = sizeof (ip6srv_combo_header_t);
hdr_len += vec_len (sl->segments) * sizeof (ip6_address_t);
hdr_len += sizeof (ip6_address_t);
}
else
{
hdr_len = sizeof (ip6_header_t);
if (PREDICT_FALSE (gtpu_type) != GTPU_TYPE_GTPU)
{
hdr_len += sizeof (ip6_sr_header_t);
hdr_len += sizeof (ip6_address_t);
}
}
// jump back to data[0] or pre_data if required
vlib_buffer_advance (b0, -(word) hdr_len);
ip6srv = vlib_buffer_get_current (b0);
if (sl)
{
clib_memcpy_fast (ip6srv, sl->rewrite,
vec_len (sl->rewrite));
if (vec_len (sl->segments) > 1)
{
ip6srv->ip.src_address = src0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments_left += 1;
ip6srv->sr.last_entry += 1;
ip6srv->sr.length += sizeof (ip6_address_t) / 8;
ip6srv->sr.segments[0] = seg0;
clib_memcpy_fast (&ip6srv->sr.segments[1],
(u8 *) (sl->rewrite +
sizeof (ip6_header_t) +
sizeof (ip6_sr_header_t)),
vec_len (sl->segments) *
sizeof (ip6_address_t));
}
else
{
ip6srv->ip.src_address = src0;
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
ip6srv->sr.type = ROUTING_HEADER_TYPE_SR;
ip6srv->sr.segments_left = 1;
ip6srv->sr.last_entry = 0;
ip6srv->sr.length =
((sizeof (ip6_sr_header_t) +
sizeof (ip6_address_t)) / 8) - 1;
ip6srv->sr.flags = 0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments[0] = seg0;
if (vec_len (sl->segments))
{
ip6srv->sr.segments[1] = sl->segments[0];
ip6srv->sr.last_entry++;
ip6srv->sr.length += sizeof (ip6_address_t) / 8;
}
}
if (PREDICT_TRUE (encap != NULL))
{
if (ls_param->nhtype == SRV6_NHTYPE_NONE)
{
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) == 6)
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
else
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV4)
{
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 4)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV6)
{
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 6)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_NON_IP)
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
}
else
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
}
else
{
clib_memcpy_fast (ip6srv, &sm->cache_hdr,
sizeof (ip6_header_t));
ip6srv->ip.src_address = src0;
ip6srv->ip.dst_address = seg0;
if (PREDICT_FALSE (gtpu_type) != GTPU_TYPE_GTPU)
{
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments_left = 0;
ip6srv->sr.last_entry = 0;
ip6srv->sr.length = sizeof (ip6_address_t) / 8;
ip6srv->sr.segments[0] = seg0;
}
else
{
if (ls_param->nhtype == SRV6_NHTYPE_NONE)
{
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 6)
ip6srv->ip.protocol = IP_PROTOCOL_IP_IN_IP;
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV4)
{
ip6srv->ip.protocol = IP_PROTOCOL_IP_IN_IP;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 4)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV6)
{
ip6srv->ip.protocol = IP_PROTOCOL_IPV6;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label)
>> 28) != 6)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_NON_IP)
{
ip6srv->ip.protocol = IP_PROTOCOL_NONE;
}
}
}
ip6srv->ip.payload_length =
clib_host_to_net_u16 (len0 + hdr_len - sizeof (ip6_header_t));
good_n++;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
srv6_end_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy (tr->src.as_u8, ip6srv->ip.src_address.as_u8,
sizeof (ip6_address_t));
clib_memcpy (tr->dst.as_u8, ip6srv->ip.dst_address.as_u8,
sizeof (ip6_address_t));
tr->teid = teid;
clib_memcpy (tr->sr_prefix.as_u8, ls_param->sr_prefix.as_u8,
sizeof (ip6_address_t));
tr->sr_prefixlen = ls_param->sr_prefixlen;
}
}
DONE:
vlib_increment_combined_counter
(((next0 ==
SRV6_END_M_GTP6_D_NEXT_DROP) ? &(sm2->sr_ls_invalid_counters) :
&(sm2->sr_ls_valid_counters)), thread_index,
ls0 - sm2->localsids, 1, vlib_buffer_length_in_chain (vm, b0));
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sm->end_m_gtp6_d_node_index,
SRV6_END_ERROR_M_GTP6_D_BAD_PACKETS, bad_n);
vlib_node_increment_counter (vm, sm->end_m_gtp6_d_node_index,
SRV6_END_ERROR_M_GTP6_D_PACKETS, good_n);
return frame->n_vectors;
}
// Function for SRv6 GTP6.D.DI function
VLIB_NODE_FN (srv6_end_m_gtp6_d_di) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
srv6_end_main_v6_decap_di_t *sm = &srv6_end_main_v6_decap_di;
ip6_sr_main_t *sm2 = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
u32 thread_index = vm->thread_index;
srv6_end_gtp6_param_t *ls_param;
u32 good_n = 0, bad_n = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_sr_localsid_t *ls0;
ip6_gtpu_header_t *hdr0 = NULL;
uword len0;
ip6_address_t dst0;
ip6_address_t src0;
ip6_address_t seg0;
u32 teid = 0;
u8 *teidp;
u8 gtpu_type = 0;
u8 qfi = 0;
u8 *qfip = NULL;
u16 seq = 0;
u8 *seqp;
u32 offset, shift;
u32 hdrlen;
ip6_header_t *encap = NULL;
gtpu_pdu_session_t *sess;
u32 next0 = SRV6_END_M_GTP6_D_DI_NEXT_LOOKUP;
// defaults
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
ls0 =
pool_elt_at_index (sm2->localsids,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ls_param = (srv6_end_gtp6_param_t *) ls0->plugin_mem;
hdr0 = vlib_buffer_get_current (b0);
hdrlen = sizeof (ip6_gtpu_header_t);
len0 = vlib_buffer_length_in_chain (vm, b0);
if ((hdr0->ip6.protocol != IP_PROTOCOL_UDP)
|| (hdr0->udp.dst_port !=
clib_host_to_net_u16 (SRV6_GTP_UDP_DST_PORT))
|| (len0 < sizeof (ip6_gtpu_header_t)))
{
next0 = SRV6_END_M_GTP6_D_DI_NEXT_DROP;
bad_n++;
}
else
{
dst0 = hdr0->ip6.dst_address;
src0 = hdr0->ip6.src_address;
gtpu_type = hdr0->gtpu.type;
seg0 = ls_param->sr_prefix;
teid = hdr0->gtpu.teid;
teidp = (u8 *) & teid;
seqp = (u8 *) & seq;
if (hdr0->gtpu.ver_flags & (GTPU_EXTHDR_FLAG | GTPU_SEQ_FLAG))
{
// Extention header.
hdrlen += sizeof (gtpu_exthdr_t);
seq = hdr0->gtpu.ext->seq;
if (hdr0->gtpu.ext->nextexthdr == GTPU_EXTHDR_PDU_SESSION)
{
// PDU Session Container.
sess =
(gtpu_pdu_session_t *) (((char *) hdr0) + hdrlen);
qfi = sess->u.val & ~GTPU_PDU_SESSION_P_BIT_MASK;
qfip = &qfi;
hdrlen += sizeof (gtpu_pdu_session_t);
if (sess->u.val & GTPU_PDU_SESSION_P_BIT_MASK)
{
hdrlen += sizeof (gtpu_paging_policy_t);
}
}
}
offset = ls_param->sr_prefixlen / 8;
shift = ls_param->sr_prefixlen % 8;
offset += 1;
if (PREDICT_TRUE (shift == 0))
{
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
clib_memcpy_fast (&seg0.as_u8[offset], seqp, 2);
}
else
{
clib_memcpy_fast (&seg0.as_u8[offset], teidp, 4);
}
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg0.as_u8[offset + 4] = qfi;
}
}
else
{
int idx;
if (gtpu_type == GTPU_TYPE_ECHO_REQUEST
|| gtpu_type == GTPU_TYPE_ECHO_REPLY
|| gtpu_type == GTPU_TYPE_ERROR_INDICATION)
{
for (idx = 0; idx < 2; idx++)
{
seg0.as_u8[offset + idx] |= seqp[idx] >> shift;
seg0.as_u8[offset + idx + 1] |=
seqp[idx] << (8 - shift);
}
}
else
{
for (idx = 0; idx < 4; idx++)
{
seg0.as_u8[offset + idx] |= teidp[idx] >> shift;
seg0.as_u8[offset + idx + 1] |=
teidp[idx] << (8 - shift);
}
}
if (qfip)
{
qfi =
((qfi & GTPU_PDU_SESSION_QFI_MASK) << 2) |
((qfi & GTPU_PDU_SESSION_R_BIT_MASK) >> 5);
if (sess->type)
{
qfi |= SRV6_PDU_SESSION_U_BIT_MASK;
}
seg0.as_u8[offset + 4] |= qfi >> shift;
seg0.as_u8[offset + 5] |= qfi << (8 - shift);
}
}
// jump over variable length data
vlib_buffer_advance (b0, (word) hdrlen);
// get length of encapsulated IPv6 packet (the remaining part)
len0 = vlib_buffer_length_in_chain (vm, b0);
if (PREDICT_TRUE (gtpu_type == GTPU_TYPE_GTPU))
{
encap = vlib_buffer_get_current (b0);
}
uword *p;
ip6srv_combo_header_t *ip6srv;
ip6_sr_policy_t *sr_policy = NULL;
ip6_sr_sl_t *sl = NULL;
u32 *sl_index;
u32 hdr_len;
p =
mhash_get (&sm2->sr_policies_index_hash,
&ls_param->sr_prefix);
if (p)
{
sr_policy = pool_elt_at_index (sm2->sr_policies, p[0]);
}
if (sr_policy)
{
vec_foreach (sl_index, sr_policy->segments_lists)
{
sl = pool_elt_at_index (sm2->sid_lists, *sl_index);
if (sl != NULL)
break;
}
}
hdr_len = sizeof (ip6srv_combo_header_t);
if (sl)
hdr_len += vec_len (sl->segments) * sizeof (ip6_address_t);
hdr_len += sizeof (ip6_address_t) * 2;
// jump back to data[0] or pre_data if required
vlib_buffer_advance (b0, -(word) hdr_len);
ip6srv = vlib_buffer_get_current (b0);
if (sl)
{
clib_memcpy_fast (ip6srv, sl->rewrite,
vec_len (sl->rewrite));
if (vec_len (sl->segments) > 1)
{
ip6srv->ip.src_address = src0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments_left += 2;
ip6srv->sr.last_entry += 2;
ip6srv->sr.length += ((sizeof (ip6_address_t) * 2) / 8);
ip6srv->sr.segments[0] = dst0;
ip6srv->sr.segments[1] = seg0;
clib_memcpy_fast (&ip6srv->sr.segments[2],
(u8 *) (sl->rewrite +
sizeof (ip6_header_t) +
sizeof (ip6_sr_header_t)),
vec_len (sl->segments) *
sizeof (ip6_address_t));
}
else
{
ip6srv->ip.src_address = src0;
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
ip6srv->sr.type = ROUTING_HEADER_TYPE_SR;
ip6srv->sr.segments_left = 2;
ip6srv->sr.last_entry = 1;
ip6srv->sr.length =
((sizeof (ip6_sr_header_t) +
2 * sizeof (ip6_address_t)) / 8) - 1;
ip6srv->sr.flags = 0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments[0] = dst0;
ip6srv->sr.segments[1] = seg0;
if (vec_len (sl->segments))
{
ip6srv->sr.segments[2] = sl->segments[0];
ip6srv->sr.last_entry++;
ip6srv->sr.length += sizeof (ip6_address_t) / 8;
}
}
}
else
{
clib_memcpy_fast (ip6srv, &sm->cache_hdr,
sizeof (ip6_header_t));
ip6srv->ip.src_address = src0;
ip6srv->ip.dst_address = seg0;
ip6srv->sr.type = ROUTING_HEADER_TYPE_SR;
ip6srv->sr.segments_left = 1;
ip6srv->sr.last_entry = 0;
ip6srv->sr.length =
((sizeof (ip6_sr_header_t) +
sizeof (ip6_address_t)) / 8) - 1;
ip6srv->sr.flags = 0;
ip6srv->sr.tag =
clib_host_to_net_u16 (srh_tagfield[gtpu_type]);
ip6srv->sr.segments[0] = dst0;
}
ip6srv->ip.payload_length =
clib_host_to_net_u16 (len0 + hdr_len - sizeof (ip6_header_t));
ip6srv->ip.protocol = IP_PROTOCOL_IPV6_ROUTE;
if (PREDICT_TRUE (encap != NULL))
{
if (ls_param->nhtype == SRV6_NHTYPE_NONE)
{
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label) >>
28) == 6)
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
else
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV4)
{
ip6srv->sr.protocol = IP_PROTOCOL_IP_IN_IP;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label) >>
28) != 4)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_DI_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_IPV6)
{
ip6srv->sr.protocol = IP_PROTOCOL_IPV6;
if ((clib_net_to_host_u32
(encap->ip_version_traffic_class_and_flow_label) >>
28) != 6)
{
// Bad encap packet.
next0 = SRV6_END_M_GTP6_D_DI_NEXT_DROP;
bad_n++;
goto DONE;
}
}
else if (ls_param->nhtype == SRV6_NHTYPE_NON_IP)
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
}
else
{
ip6srv->sr.protocol = IP_PROTOCOL_NONE;
}
good_n++;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
srv6_end_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy (tr->src.as_u8, ip6srv->ip.src_address.as_u8,
sizeof (ip6_address_t));
clib_memcpy (tr->dst.as_u8, ip6srv->ip.dst_address.as_u8,
sizeof (ip6_address_t));
tr->teid = teid;
clib_memcpy (tr->sr_prefix.as_u8, ls_param->sr_prefix.as_u8,
sizeof (ip6_address_t));
tr->sr_prefixlen = ls_param->sr_prefixlen;
}
}
DONE:
vlib_increment_combined_counter
(((next0 ==
SRV6_END_M_GTP6_D_DI_NEXT_DROP) ?
&(sm2->sr_ls_invalid_counters) : &(sm2->sr_ls_valid_counters)),
thread_index, ls0 - sm2->localsids, 1,
vlib_buffer_length_in_chain (vm, b0));
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sm->end_m_gtp6_d_di_node_index,
SRV6_END_ERROR_M_GTP6_D_DI_BAD_PACKETS, bad_n);
vlib_node_increment_counter (vm, sm->end_m_gtp6_d_di_node_index,
SRV6_END_ERROR_M_GTP6_D_DI_PACKETS, good_n);
return frame->n_vectors;
}
VLIB_REGISTER_NODE (srv6_end_m_gtp6_e) =
{
.name = "srv6-end-m-gtp6-e",.vector_size = sizeof (u32),.format_trace =
format_srv6_end_rewrite_trace6,.type = VLIB_NODE_TYPE_INTERNAL,.n_errors =
ARRAY_LEN (srv6_end_error_v6_e_strings),.error_strings =
srv6_end_error_v6_e_strings,.n_next_nodes =
SRV6_END_M_GTP6_E_N_NEXT,.next_nodes =
{
[SRV6_END_M_GTP6_E_NEXT_DROP] = "error-drop",
[SRV6_END_M_GTP6_E_NEXT_LOOKUP] = "ip6-lookup",}
,};
VLIB_REGISTER_NODE (srv6_end_m_gtp6_d) =
{
.name = "srv6-end-m-gtp6-d",.vector_size = sizeof (u32),.format_trace =
format_srv6_end_rewrite_trace6,.type = VLIB_NODE_TYPE_INTERNAL,.n_errors =
ARRAY_LEN (srv6_end_error_v6_d_strings),.error_strings =
srv6_end_error_v6_d_strings,.n_next_nodes =
SRV6_END_M_GTP6_D_N_NEXT,.next_nodes =
{
[SRV6_END_M_GTP6_D_NEXT_DROP] = "error-drop",
[SRV6_END_M_GTP6_D_NEXT_LOOKUP] = "ip6-lookup",}
,};
VLIB_REGISTER_NODE (srv6_end_m_gtp6_d_di) =
{
.name = "srv6-end-m-gtp6-d-di",.vector_size = sizeof (u32),.format_trace =
format_srv6_end_rewrite_trace6,.type = VLIB_NODE_TYPE_INTERNAL,.n_errors =
ARRAY_LEN (srv6_end_error_v6_d_di_strings),.error_strings =
srv6_end_error_v6_d_di_strings,.n_next_nodes =
SRV6_END_M_GTP6_D_DI_N_NEXT,.next_nodes =
{
[SRV6_END_M_GTP6_D_DI_NEXT_DROP] = "error-drop",
[SRV6_END_M_GTP6_D_DI_NEXT_LOOKUP] = "ip6-lookup",}
,};
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/vppinfra/cpu.c
|
<filename>src/vppinfra/cpu.c
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <vppinfra/clib.h>
#include <vppinfra/format.h>
#include <vppinfra/cpu.h>
#define foreach_x86_cpu_uarch \
_(0x06, 0x9e, "Kaby Lake", "Kaby Lake DT/H/S/X") \
_(0x06, 0x8e, "Kaby Lake", "Kaby Lake Y/U") \
_(0x06, 0x8c, "Tiger Lake", "Tiger Lake U") \
_(0x06, 0x86, "Tremont", "Elkhart Lake") \
_(0x06, 0x85, "Knights Mill", "Knights Mill") \
_(0x06, 0x7e, "Ice Lake", "Ice Lake U") \
_(0x06, 0x7d, "Ice Lake", "Ice Lake Y") \
_(0x06, 0x7a, "Goldmont Plus", "Gemini Lake") \
_(0x06, 0x6c, "Ice Lake", "Ice Lake SP") \
_(0x06, 0x6a, "Ice Lake", "Ice Lake DE") \
_(0x06, 0x66, "Cannon Lake", "Cannon Lake U") \
_(0x06, 0x5f, "Goldmont", "Denverton") \
_(0x06, 0x5e, "Skylake", "Skylake DT/H/S") \
_(0x06, 0x5c, "Goldmont", "Apollo Lake") \
_(0x06, 0x5a, "Silvermont", "Moorefield") \
_(0x06, 0x57, "Knights Landing", "Knights Landing") \
_(0x06, 0x56, "Broadwell", "Broadwell DE") \
_(0x06, 0x55, "Skylake", "Skylake X/SP") \
_(0x06, 0x4f, "Broadwell", "Broadwell EP/EX") \
_(0x06, 0x4e, "Skylake", "Skylake Y/U") \
_(0x06, 0x4d, "Silvermont", "Rangeley") \
_(0x06, 0x4c, "Airmont", "Braswell") \
_(0x06, 0x47, "Broadwell", "Broadwell H") \
_(0x06, 0x46, "Haswell", "Crystalwell") \
_(0x06, 0x45, "Haswell", "Haswell ULT") \
_(0x06, 0x3f, "Haswell", "Haswell E") \
_(0x06, 0x3e, "Ivy Bridge", "Ivy Bridge E/EN/EP") \
_(0x06, 0x3d, "Broadwell", "Broadwell U") \
_(0x06, 0x3c, "Haswell", "Haswell") \
_(0x06, 0x3a, "Ivy Bridge", "IvyBridge") \
_(0x06, 0x37, "Silvermont", "BayTrail") \
_(0x06, 0x36, "Saltwell", "Cedarview,Centerton") \
_(0x06, 0x35, "Saltwell", "Cloverview") \
_(0x06, 0x2f, "Westmere", "Westmere EX") \
_(0x06, 0x2e, "Nehalem", "Nehalem EX") \
_(0x06, 0x2d, "Sandy Bridge", "SandyBridge E/EN/EP") \
_(0x06, 0x2c, "Westmere", "Westmere EP/EX,Gulftown") \
_(0x06, 0x2a, "Sandy Bridge", "Sandy Bridge") \
_(0x06, 0x27, "Saltwell", "Medfield") \
_(0x06, 0x26, "Bonnell", "Tunnel Creek") \
_(0x06, 0x25, "Westmere", "Arrandale,Clarksdale") \
_(0x06, 0x1e, "Nehalem", "Clarksfield,Lynnfield,Jasper Forest") \
_(0x06, 0x1d, "Penryn", "Dunnington") \
_(0x06, 0x1c, "Bonnell", "Pineview,Silverthorne") \
_(0x06, 0x1a, "Nehalem", "Nehalem EP,Bloomfield)") \
_(0x06, 0x17, "Penryn", "Yorkfield,Wolfdale,Penryn,Harpertown")
/* _(implementor-id, part-id, vendor-name, cpu-name, show CPU pass as string) */
#define foreach_aarch64_cpu_uarch \
_(0x41, 0xd03, "ARM", "Cortex-A53", 0) \
_(0x41, 0xd07, "ARM", "Cortex-A57", 0) \
_(0x41, 0xd08, "ARM", "Cortex-A72", 0) \
_(0x41, 0xd09, "ARM", "Cortex-A73", 0) \
_(0x43, 0x0a1, "Marvell", "THUNDERX CN88XX", 0) \
_(0x43, 0x0a2, "Marvell", "OCTEON TX CN81XX", 0) \
_(0x43, 0x0a3, "Marvell", "OCTEON TX CN83XX", 0) \
_(0x43, 0x0af, "Marvell", "THUNDERX2 CN99XX", 1) \
_(0x43, 0x0b1, "Marvell", "OCTEON TX2 CN98XX", 1) \
_(0x43, 0x0b2, "Marvell", "OCTEON TX2 CN96XX", 1)
u8 *
format_cpu_uarch (u8 * s, va_list * args)
{
#if __x86_64__
u32 __attribute__ ((unused)) eax, ebx, ecx, edx;
u8 model, family, stepping;
if (__get_cpuid (1, &eax, &ebx, &ecx, &edx) == 0)
return format (s, "unknown (missing cpuid)");
model = ((eax >> 4) & 0x0f) | ((eax >> 12) & 0xf0);
family = (eax >> 8) & 0x0f;
stepping = eax & 0x0f;
#define _(f,m,a,c) if ((model == m) && (family == f)) return \
format(s, "[0x%x] %s ([0x%02x] %s) stepping 0x%x", f, a, m, c, stepping);
foreach_x86_cpu_uarch
#undef _
return format (s, "unknown (family 0x%02x model 0x%02x)", family, model);
#elif __aarch64__
int fd;
unformat_input_t input;
u32 implementer, primary_part_number, variant, revision;
fd = open ("/proc/cpuinfo", 0);
if (fd < 0)
return format (s, "unknown");
unformat_init_clib_file (&input, fd);
while (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (&input, "CPU implementer%_: 0x%x", &implementer))
;
else if (unformat (&input, "CPU part%_: 0x%x", &primary_part_number))
;
else if (unformat (&input, "CPU variant%_: 0x%x", &variant))
;
else if (unformat (&input, "CPU revision%_: %u", &revision))
;
else
unformat_skip_line (&input);
}
unformat_free (&input);
close (fd);
#define _(i,p,a,c,_format) if ((implementer == i) && (primary_part_number == p)){ \
if (_format)\
return format(s, "%s (%s PASS %c%u)", a, c, 'A'+variant, revision);\
else {\
if (implementer == 0x43)\
variant++; \
return format (s, "%s (%s PASS %u.%u)", a, c, variant, revision);}}
foreach_aarch64_cpu_uarch
#undef _
return format (s, "unknown (implementer 0x%02x part 0x%03x PASS %u.%u)",
implementer, primary_part_number, variant, revision);
#else /* ! __x86_64__ */
return format (s, "unknown");
#endif
}
u8 *
format_cpu_model_name (u8 * s, va_list * args)
{
#if __x86_64__
u32 __attribute__ ((unused)) eax, ebx, ecx, edx;
u8 *name = 0;
u32 *name_u32;
if (__get_cpuid (1, &eax, &ebx, &ecx, &edx) == 0)
return format (s, "unknown (missing cpuid)");
__get_cpuid (0x80000000, &eax, &ebx, &ecx, &edx);
if (eax < 0x80000004)
return format (s, "unknown (missing ext feature)");
vec_validate (name, 48);
name_u32 = (u32 *) name;
__get_cpuid (0x80000002, &eax, &ebx, &ecx, &edx);
name_u32[0] = eax;
name_u32[1] = ebx;
name_u32[2] = ecx;
name_u32[3] = edx;
__get_cpuid (0x80000003, &eax, &ebx, &ecx, &edx);
name_u32[4] = eax;
name_u32[5] = ebx;
name_u32[6] = ecx;
name_u32[7] = edx;
__get_cpuid (0x80000004, &eax, &ebx, &ecx, &edx);
name_u32[8] = eax;
name_u32[9] = ebx;
name_u32[10] = ecx;
name_u32[11] = edx;
s = format (s, "%s", name);
vec_free (name);
return s;
#elif defined(__aarch64__)
return format (s, "armv8");
#else /* ! __x86_64__ */
return format (s, "unknown");
#endif
}
static inline char const *
flag_skip_prefix (char const *flag, const char *pfx, int len)
{
if (0 == strncmp (flag, pfx, len - 1))
return flag + len - 1;
return flag;
}
u8 *
format_cpu_flags (u8 * s, va_list * args)
{
#if defined(__x86_64__)
#define _(flag, func, reg, bit) \
if (clib_cpu_supports_ ## flag()) \
s = format (s, "%s ", flag_skip_prefix(#flag, "x86_", sizeof("x86_")));
foreach_x86_64_flags return s;
#undef _
#elif defined(__aarch64__)
#define _(flag, bit) \
if (clib_cpu_supports_ ## flag()) \
s = format (s, "%s ", flag_skip_prefix(#flag, "aarch64_", sizeof("aarch64_")));
foreach_aarch64_flags return s;
#undef _
#else /* ! ! __x86_64__ && ! __aarch64__ */
return format (s, "unknown");
#endif
}
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/vnet/udp/udp.c
|
<gh_stars>10-100
/*
* Copyright (c) 2016-2019 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file
udp state machine, etc.
*/
#include <vnet/udp/udp.h>
#include <vnet/session/session.h>
#include <vnet/dpo/load_balance.h>
#include <vnet/fib/ip4_fib.h>
udp_main_t udp_main;
udp_connection_t *
udp_connection_alloc (u32 thread_index)
{
udp_main_t *um = &udp_main;
udp_connection_t *uc;
u32 will_expand = 0;
pool_get_aligned_will_expand (um->connections[thread_index], will_expand,
CLIB_CACHE_LINE_BYTES);
if (PREDICT_FALSE (will_expand))
{
clib_spinlock_lock_if_init (&udp_main.peekers_write_locks
[thread_index]);
pool_get_aligned (udp_main.connections[thread_index], uc,
CLIB_CACHE_LINE_BYTES);
clib_spinlock_unlock_if_init (&udp_main.peekers_write_locks
[thread_index]);
}
else
{
pool_get_aligned (um->connections[thread_index], uc,
CLIB_CACHE_LINE_BYTES);
}
clib_memset (uc, 0, sizeof (*uc));
uc->c_c_index = uc - um->connections[thread_index];
uc->c_thread_index = thread_index;
uc->c_proto = TRANSPORT_PROTO_UDP;
clib_spinlock_init (&uc->rx_lock);
return uc;
}
void
udp_connection_free (udp_connection_t * uc)
{
u32 thread_index = uc->c_thread_index;
if (CLIB_DEBUG)
clib_memset (uc, 0xFA, sizeof (*uc));
pool_put (udp_main.connections[thread_index], uc);
}
void
udp_connection_delete (udp_connection_t * uc)
{
if ((uc->flags & UDP_CONN_F_OWNS_PORT)
|| !(uc->flags & UDP_CONN_F_CONNECTED))
udp_unregister_dst_port (vlib_get_main (),
clib_net_to_host_u16 (uc->c_lcl_port),
uc->c_is_ip4);
session_transport_delete_notify (&uc->connection);
udp_connection_free (uc);
}
u32
udp_session_bind (u32 session_index, transport_endpoint_t * lcl)
{
udp_main_t *um = vnet_get_udp_main ();
vlib_main_t *vm = vlib_get_main ();
udp_connection_t *listener;
u32 node_index;
void *iface_ip;
udp_dst_port_info_t *pi;
pi = udp_get_dst_port_info (um, lcl->port, lcl->is_ip4);
if (pi)
return -1;
pool_get (um->listener_pool, listener);
clib_memset (listener, 0, sizeof (udp_connection_t));
listener->c_lcl_port = lcl->port;
listener->c_c_index = listener - um->listener_pool;
/* If we are provided a sw_if_index, bind using one of its ips */
if (ip_is_zero (&lcl->ip, 1) && lcl->sw_if_index != ENDPOINT_INVALID_INDEX)
{
if ((iface_ip = ip_interface_get_first_ip (lcl->sw_if_index,
lcl->is_ip4)))
ip_set (&lcl->ip, iface_ip, lcl->is_ip4);
}
ip_copy (&listener->c_lcl_ip, &lcl->ip, lcl->is_ip4);
listener->c_is_ip4 = lcl->is_ip4;
listener->c_proto = TRANSPORT_PROTO_UDP;
listener->c_s_index = session_index;
listener->c_fib_index = lcl->fib_index;
listener->flags |= UDP_CONN_F_OWNS_PORT;
clib_spinlock_init (&listener->rx_lock);
node_index = lcl->is_ip4 ? udp4_input_node.index : udp6_input_node.index;
udp_register_dst_port (vm, clib_net_to_host_u16 (lcl->port), node_index,
lcl->is_ip4);
return listener->c_c_index;
}
u32
udp_session_unbind (u32 listener_index)
{
vlib_main_t *vm = vlib_get_main ();
udp_connection_t *listener;
listener = udp_listener_get (listener_index);
udp_unregister_dst_port (vm, clib_net_to_host_u16 (listener->c_lcl_port),
listener->c_is_ip4);
return 0;
}
transport_connection_t *
udp_session_get_listener (u32 listener_index)
{
udp_connection_t *us;
us = udp_listener_get (listener_index);
return &us->connection;
}
u32
udp_push_header (transport_connection_t * tc, vlib_buffer_t * b)
{
udp_connection_t *uc;
vlib_main_t *vm = vlib_get_main ();
uc = udp_get_connection_from_transport (tc);
vlib_buffer_push_udp (b, uc->c_lcl_port, uc->c_rmt_port, 1);
if (tc->is_ip4)
vlib_buffer_push_ip4 (vm, b, &uc->c_lcl_ip4, &uc->c_rmt_ip4,
IP_PROTOCOL_UDP, 1);
else
{
ip6_header_t *ih;
ih = vlib_buffer_push_ip6 (vm, b, &uc->c_lcl_ip6, &uc->c_rmt_ip6,
IP_PROTOCOL_UDP);
vnet_buffer (b)->l3_hdr_offset = (u8 *) ih - b->data;
}
vnet_buffer (b)->sw_if_index[VLIB_RX] = 0;
vnet_buffer (b)->sw_if_index[VLIB_TX] = uc->c_fib_index;
b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
if (PREDICT_FALSE (uc->flags & UDP_CONN_F_CLOSING))
{
if (!transport_max_tx_dequeue (&uc->connection))
udp_connection_delete (uc);
}
return 0;
}
transport_connection_t *
udp_session_get (u32 connection_index, u32 thread_index)
{
udp_connection_t *uc;
uc = udp_connection_get (connection_index, thread_index);
if (uc)
return &uc->connection;
return 0;
}
void
udp_session_close (u32 connection_index, u32 thread_index)
{
udp_connection_t *uc;
uc = udp_connection_get (connection_index, thread_index);
if (!uc)
return;
if (!transport_max_tx_dequeue (&uc->connection))
udp_connection_delete (uc);
else
uc->flags |= UDP_CONN_F_CLOSING;
}
void
udp_session_cleanup (u32 connection_index, u32 thread_index)
{
udp_connection_t *uc;
uc = udp_connection_get (connection_index, thread_index);
if (uc)
udp_connection_free (uc);
}
u8 *
format_udp_connection_id (u8 * s, va_list * args)
{
udp_connection_t *uc = va_arg (*args, udp_connection_t *);
if (!uc)
return s;
if (uc->c_is_ip4)
s = format (s, "[#%d][%s] %U:%d->%U:%d", uc->c_thread_index, "U",
format_ip4_address, &uc->c_lcl_ip4,
clib_net_to_host_u16 (uc->c_lcl_port), format_ip4_address,
&uc->c_rmt_ip4, clib_net_to_host_u16 (uc->c_rmt_port));
else
s = format (s, "[#%d][%s] %U:%d->%U:%d", uc->c_thread_index, "U",
format_ip6_address, &uc->c_lcl_ip6,
clib_net_to_host_u16 (uc->c_lcl_port), format_ip6_address,
&uc->c_rmt_ip6, clib_net_to_host_u16 (uc->c_rmt_port));
return s;
}
u8 *
format_udp_connection (u8 * s, va_list * args)
{
udp_connection_t *uc = va_arg (*args, udp_connection_t *);
u32 verbose = va_arg (*args, u32);
if (!uc)
return s;
s = format (s, "%-50U", format_udp_connection_id, uc);
if (verbose)
{
if (verbose == 1)
s = format (s, "%-15s", "-");
else
s = format (s, "\n");
}
return s;
}
u8 *
format_udp_session (u8 * s, va_list * args)
{
u32 uci = va_arg (*args, u32);
u32 thread_index = va_arg (*args, u32);
u32 verbose = va_arg (*args, u32);
udp_connection_t *uc;
uc = udp_connection_get (uci, thread_index);
return format (s, "%U", format_udp_connection, uc, verbose);
}
u8 *
format_udp_half_open_session (u8 * s, va_list * args)
{
u32 __clib_unused tci = va_arg (*args, u32);
u32 __clib_unused thread_index = va_arg (*args, u32);
clib_warning ("BUG");
return 0;
}
u8 *
format_udp_listener_session (u8 * s, va_list * args)
{
u32 tci = va_arg (*args, u32);
u32 __clib_unused thread_index = va_arg (*args, u32);
u32 verbose = va_arg (*args, u32);
udp_connection_t *uc = udp_listener_get (tci);
return format (s, "%U", format_udp_connection, uc, verbose);
}
u16
udp_send_mss (transport_connection_t * t)
{
/* TODO figure out MTU of output interface */
return 1460;
}
u32
udp_send_space (transport_connection_t * t)
{
/* No constraint on TX window */
return ~0;
}
int
udp_open_connection (transport_endpoint_cfg_t * rmt)
{
udp_main_t *um = vnet_get_udp_main ();
vlib_main_t *vm = vlib_get_main ();
u32 thread_index = vm->thread_index;
udp_connection_t *uc;
ip46_address_t lcl_addr;
u32 node_index;
u16 lcl_port;
if (transport_alloc_local_endpoint (TRANSPORT_PROTO_UDP, rmt, &lcl_addr,
&lcl_port))
return -1;
while (udp_get_dst_port_info (um, lcl_port, rmt->is_ip4))
{
lcl_port = transport_alloc_local_port (TRANSPORT_PROTO_UDP, &lcl_addr);
if (lcl_port < 1)
{
clib_warning ("Failed to allocate src port");
return -1;
}
}
node_index = rmt->is_ip4 ? udp4_input_node.index : udp6_input_node.index;
udp_register_dst_port (vm, lcl_port, node_index, 1 /* is_ipv4 */ );
/* We don't poll main thread if we have workers */
if (vlib_num_workers ())
thread_index = 1;
uc = udp_connection_alloc (thread_index);
ip_copy (&uc->c_rmt_ip, &rmt->ip, rmt->is_ip4);
ip_copy (&uc->c_lcl_ip, &lcl_addr, rmt->is_ip4);
uc->c_rmt_port = rmt->port;
uc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
uc->c_is_ip4 = rmt->is_ip4;
uc->c_proto = TRANSPORT_PROTO_UDP;
uc->c_fib_index = rmt->fib_index;
uc->flags |= UDP_CONN_F_OWNS_PORT;
return uc->c_c_index;
}
transport_connection_t *
udp_session_get_half_open (u32 conn_index)
{
udp_connection_t *uc;
u32 thread_index;
/* We don't poll main thread if we have workers */
thread_index = vlib_num_workers ()? 1 : 0;
uc = udp_connection_get (conn_index, thread_index);
if (!uc)
return 0;
return &uc->connection;
}
/* *INDENT-OFF* */
static const transport_proto_vft_t udp_proto = {
.start_listen = udp_session_bind,
.connect = udp_open_connection,
.stop_listen = udp_session_unbind,
.push_header = udp_push_header,
.get_connection = udp_session_get,
.get_listener = udp_session_get_listener,
.get_half_open = udp_session_get_half_open,
.close = udp_session_close,
.cleanup = udp_session_cleanup,
.send_mss = udp_send_mss,
.send_space = udp_send_space,
.format_connection = format_udp_session,
.format_half_open = format_udp_half_open_session,
.format_listener = format_udp_listener_session,
.transport_options = {
.tx_type = TRANSPORT_TX_DGRAM,
.service_type = TRANSPORT_SERVICE_CL,
},
};
/* *INDENT-ON* */
int
udpc_connection_open (transport_endpoint_cfg_t * rmt)
{
udp_connection_t *uc;
/* Reproduce the logic of udp_open_connection to find the correct thread */
u32 thread_index = vlib_num_workers ()? 1 : vlib_get_main ()->thread_index;
u32 uc_index;
uc_index = udp_open_connection (rmt);
if (uc_index == (u32) ~ 0)
return -1;
uc = udp_connection_get (uc_index, thread_index);
uc->flags |= UDP_CONN_F_CONNECTED;
return uc_index;
}
u32
udpc_connection_listen (u32 session_index, transport_endpoint_t * lcl)
{
udp_connection_t *listener;
u32 li_index;
li_index = udp_session_bind (session_index, lcl);
if (li_index == (u32) ~ 0)
return -1;
listener = udp_listener_get (li_index);
listener->flags |= UDP_CONN_F_CONNECTED;
/* Fake udp listener, i.e., make sure session layer adds a udp instead of
* udpc listener to the lookup table */
((session_endpoint_cfg_t *) lcl)->transport_proto = TRANSPORT_PROTO_UDP;
return li_index;
}
/* *INDENT-OFF* */
static const transport_proto_vft_t udpc_proto = {
.start_listen = udpc_connection_listen,
.stop_listen = udp_session_unbind,
.connect = udpc_connection_open,
.push_header = udp_push_header,
.get_connection = udp_session_get,
.get_listener = udp_session_get_listener,
.get_half_open = udp_session_get_half_open,
.close = udp_session_close,
.cleanup = udp_session_cleanup,
.send_mss = udp_send_mss,
.send_space = udp_send_space,
.format_connection = format_udp_session,
.format_half_open = format_udp_half_open_session,
.format_listener = format_udp_listener_session,
.transport_options = {
.tx_type = TRANSPORT_TX_DGRAM,
.service_type = TRANSPORT_SERVICE_VC,
.half_open_has_fifos = 1
},
};
/* *INDENT-ON* */
static clib_error_t *
udp_init (vlib_main_t * vm)
{
udp_main_t *um = vnet_get_udp_main ();
ip_main_t *im = &ip_main;
vlib_thread_main_t *tm = vlib_get_thread_main ();
u32 num_threads;
ip_protocol_info_t *pi;
int i;
/*
* Registrations
*/
/* IP registration */
pi = ip_get_protocol_info (im, IP_PROTOCOL_UDP);
if (pi == 0)
return clib_error_return (0, "UDP protocol info AWOL");
pi->format_header = format_udp_header;
pi->unformat_pg_edit = unformat_pg_udp_header;
/* Register as transport with URI */
transport_register_protocol (TRANSPORT_PROTO_UDP, &udp_proto,
FIB_PROTOCOL_IP4, ip4_lookup_node.index);
transport_register_protocol (TRANSPORT_PROTO_UDP, &udp_proto,
FIB_PROTOCOL_IP6, ip6_lookup_node.index);
transport_register_protocol (TRANSPORT_PROTO_UDPC, &udpc_proto,
FIB_PROTOCOL_IP4, ip4_lookup_node.index);
transport_register_protocol (TRANSPORT_PROTO_UDPC, &udpc_proto,
FIB_PROTOCOL_IP6, ip6_lookup_node.index);
/*
* Initialize data structures
*/
num_threads = 1 /* main thread */ + tm->n_threads;
vec_validate (um->connections, num_threads - 1);
vec_validate (um->connection_peekers, num_threads - 1);
vec_validate (um->peekers_readers_locks, num_threads - 1);
vec_validate (um->peekers_write_locks, num_threads - 1);
if (num_threads > 1)
for (i = 0; i < num_threads; i++)
{
clib_spinlock_init (&um->peekers_readers_locks[i]);
clib_spinlock_init (&um->peekers_write_locks[i]);
}
return 0;
}
/* *INDENT-OFF* */
VLIB_INIT_FUNCTION (udp_init) =
{
.runs_after = VLIB_INITS("ip_main_init", "ip4_lookup_init",
"ip6_lookup_init"),
};
/* *INDENT-ON* */
static clib_error_t *
show_udp_punt_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd_arg)
{
udp_main_t *um = vnet_get_udp_main ();
clib_error_t *error = NULL;
if (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
return clib_error_return (0, "unknown input `%U'", format_unformat_error,
input);
udp_dst_port_info_t *port_info;
if (um->punt_unknown4)
{
vlib_cli_output (vm, "IPv4 UDP punt: enabled");
}
else
{
u8 *s = NULL;
vec_foreach (port_info, um->dst_port_infos[UDP_IP4])
{
if (udp_is_valid_dst_port (port_info->dst_port, 1))
{
s = format (s, (!s) ? "%d" : ", %d", port_info->dst_port);
}
}
s = format (s, "%c", 0);
vlib_cli_output (vm, "IPV4 UDP ports punt : %s", s);
}
if (um->punt_unknown6)
{
vlib_cli_output (vm, "IPv6 UDP punt: enabled");
}
else
{
u8 *s = NULL;
vec_foreach (port_info, um->dst_port_infos[UDP_IP6])
{
if (udp_is_valid_dst_port (port_info->dst_port, 01))
{
s = format (s, (!s) ? "%d" : ", %d", port_info->dst_port);
}
}
s = format (s, "%c", 0);
vlib_cli_output (vm, "IPV6 UDP ports punt : %s", s);
}
return (error);
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_tcp_punt_command, static) =
{
.path = "show udp punt",
.short_help = "show udp punt [ipv4|ipv6]",
.function = show_udp_punt_fn,
};
/* *INDENT-ON* */
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/plugins/crypto_native/aes_cbc.c
|
<gh_stars>1-10
/*
*------------------------------------------------------------------
* Copyright (c) 2019 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*------------------------------------------------------------------
*/
#include <vlib/vlib.h>
#include <vnet/plugin/plugin.h>
#include <vnet/crypto/crypto.h>
#include <crypto_native/crypto_native.h>
#include <crypto_native/aes.h>
#if __GNUC__ > 4 && !__clang__ && CLIB_DEBUG == 0
#pragma GCC optimize ("O3")
#endif
typedef struct
{
u8x16 encrypt_key[15];
#if __VAES__
__m512i decrypt_key[15];
#else
u8x16 decrypt_key[15];
#endif
} aes_cbc_key_data_t;
#include <crypto_native/aes_cbc_aesni.h>
#include <crypto_native/aes_cbc_neon.h>
static_always_inline void *
aesni_cbc_key_exp (vnet_crypto_key_t * key, aes_key_size_t ks)
{
u8x16 e[15], d[15];
aes_cbc_key_data_t *kd;
kd = clib_mem_alloc_aligned (sizeof (*kd), CLIB_CACHE_LINE_BYTES);
aes_key_expand (e, key->data, ks);
aes_key_enc_to_dec (e, d, ks);
for (int i = 0; i < AES_KEY_ROUNDS (ks) + 1; i++)
{
#if __VAES__
kd->decrypt_key[i] = _mm512_broadcast_i64x2 ((__m128i) d[i]);
#else
kd->decrypt_key[i] = d[i];
#endif
kd->encrypt_key[i] = e[i];
}
return kd;
}
#define foreach_aesni_cbc_handler_type _(128) _(192) _(256)
#define _(x) \
static u32 aesni_ops_dec_aes_cbc_##x \
(vlib_main_t * vm, vnet_crypto_op_t * ops[], u32 n_ops) \
{ return aesni_ops_dec_aes_cbc (vm, ops, n_ops, AES_KEY_##x); } \
static u32 aesni_ops_enc_aes_cbc_##x \
(vlib_main_t * vm, vnet_crypto_op_t * ops[], u32 n_ops) \
{ return aesni_ops_enc_aes_cbc (vm, ops, n_ops, AES_KEY_##x); } \
static void * aesni_cbc_key_exp_##x (vnet_crypto_key_t *key) \
{ return aesni_cbc_key_exp (key, AES_KEY_##x); }
foreach_aesni_cbc_handler_type;
#undef _
#include <fcntl.h>
clib_error_t *
#ifdef __VAES__
crypto_native_aes_cbc_init_vaes (vlib_main_t * vm)
#elif __AVX512F__
crypto_native_aes_cbc_init_avx512 (vlib_main_t * vm)
#elif __aarch64__
crypto_native_aes_cbc_init_neon (vlib_main_t * vm)
#elif __AVX2__
crypto_native_aes_cbc_init_avx2 (vlib_main_t * vm)
#else
crypto_native_aes_cbc_init_sse42 (vlib_main_t * vm)
#endif
{
crypto_native_main_t *cm = &crypto_native_main;
crypto_native_per_thread_data_t *ptd;
clib_error_t *err = 0;
int fd;
if ((fd = open ("/dev/urandom", O_RDONLY)) < 0)
return clib_error_return_unix (0, "failed to open '/dev/urandom'");
/* *INDENT-OFF* */
vec_foreach (ptd, cm->per_thread_data)
{
for (int i = 0; i < 4; i++)
{
if (read(fd, ptd->cbc_iv, sizeof (ptd->cbc_iv)) !=
sizeof (ptd->cbc_iv))
{
err = clib_error_return_unix (0, "'/dev/urandom' read failure");
goto error;
}
}
}
/* *INDENT-ON* */
#define _(x) \
vnet_crypto_register_ops_handler (vm, cm->crypto_engine_index, \
VNET_CRYPTO_OP_AES_##x##_CBC_ENC, \
aesni_ops_enc_aes_cbc_##x); \
vnet_crypto_register_ops_handler (vm, cm->crypto_engine_index, \
VNET_CRYPTO_OP_AES_##x##_CBC_DEC, \
aesni_ops_dec_aes_cbc_##x); \
cm->key_fn[VNET_CRYPTO_ALG_AES_##x##_CBC] = aesni_cbc_key_exp_##x;
foreach_aesni_cbc_handler_type;
#undef _
error:
close (fd);
return err;
}
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
OPENAIRINTERFACE/openair-spgwc-vpp-tp
|
src/plugins/crypto_native/aes.h
|
/*
*------------------------------------------------------------------
* Copyright (c) 2020 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*------------------------------------------------------------------
*/
#ifndef __aesni_h__
#define __aesni_h__
typedef enum
{
AES_KEY_128 = 0,
AES_KEY_192 = 1,
AES_KEY_256 = 2,
} aes_key_size_t;
#define AES_KEY_ROUNDS(x) (10 + x * 2)
#define AES_KEY_BYTES(x) (16 + x * 8)
#ifdef __x86_64__
static_always_inline u8x16
aes_block_load (u8 * p)
{
return (u8x16) _mm_loadu_si128 ((__m128i *) p);
}
static_always_inline u8x16
aes_enc_round (u8x16 a, u8x16 k)
{
return (u8x16) _mm_aesenc_si128 ((__m128i) a, (__m128i) k);
}
static_always_inline u8x16
aes_enc_last_round (u8x16 a, u8x16 k)
{
return (u8x16) _mm_aesenclast_si128 ((__m128i) a, (__m128i) k);
}
static_always_inline u8x16
aes_dec_round (u8x16 a, u8x16 k)
{
return (u8x16) _mm_aesdec_si128 ((__m128i) a, (__m128i) k);
}
static_always_inline u8x16
aes_dec_last_round (u8x16 a, u8x16 k)
{
return (u8x16) _mm_aesdeclast_si128 ((__m128i) a, (__m128i) k);
}
static_always_inline void
aes_block_store (u8 * p, u8x16 r)
{
_mm_storeu_si128 ((__m128i *) p, (__m128i) r);
}
static_always_inline u8x16
aes_inv_mix_column (u8x16 a)
{
return (u8x16) _mm_aesimc_si128 ((__m128i) a);
}
/* AES-NI based AES key expansion based on code samples from
Intel(r) Advanced Encryption Standard (AES) New Instructions White Paper
(323641-001) */
static_always_inline void
aes128_key_assist (__m128i * k, __m128i r)
{
__m128i t = k[-1];
t ^= _mm_slli_si128 (t, 4);
t ^= _mm_slli_si128 (t, 4);
t ^= _mm_slli_si128 (t, 4);
k[0] = t ^ _mm_shuffle_epi32 (r, 0xff);
}
static_always_inline void
aes128_key_expand (u8x16 * key_schedule, u8 * key)
{
__m128i *k = (__m128i *) key_schedule;
k[0] = _mm_loadu_si128 ((const __m128i *) key);
aes128_key_assist (k + 1, _mm_aeskeygenassist_si128 (k[0], 0x01));
aes128_key_assist (k + 2, _mm_aeskeygenassist_si128 (k[1], 0x02));
aes128_key_assist (k + 3, _mm_aeskeygenassist_si128 (k[2], 0x04));
aes128_key_assist (k + 4, _mm_aeskeygenassist_si128 (k[3], 0x08));
aes128_key_assist (k + 5, _mm_aeskeygenassist_si128 (k[4], 0x10));
aes128_key_assist (k + 6, _mm_aeskeygenassist_si128 (k[5], 0x20));
aes128_key_assist (k + 7, _mm_aeskeygenassist_si128 (k[6], 0x40));
aes128_key_assist (k + 8, _mm_aeskeygenassist_si128 (k[7], 0x80));
aes128_key_assist (k + 9, _mm_aeskeygenassist_si128 (k[8], 0x1b));
aes128_key_assist (k + 10, _mm_aeskeygenassist_si128 (k[9], 0x36));
}
static_always_inline void
aes192_key_assist (__m128i * r1, __m128i * r2, __m128i key_assist)
{
__m128i t;
*r1 ^= t = _mm_slli_si128 (*r1, 0x4);
*r1 ^= t = _mm_slli_si128 (t, 0x4);
*r1 ^= _mm_slli_si128 (t, 0x4);
*r1 ^= _mm_shuffle_epi32 (key_assist, 0x55);
*r2 ^= _mm_slli_si128 (*r2, 0x4);
*r2 ^= _mm_shuffle_epi32 (*r1, 0xff);
}
static_always_inline void
aes192_key_expand (u8x16 * key_schedule, u8 * key)
{
__m128i r1, r2, *k = (__m128i *) key_schedule;
k[0] = r1 = _mm_loadu_si128 ((__m128i *) key);
/* load the 24-bytes key as 2 * 16-bytes (and ignore last 8-bytes) */
k[1] = r2 = CLIB_MEM_OVERFLOW_LOAD (_mm_loadu_si128, (__m128i *) key + 1);
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x1));
k[1] = (__m128i) _mm_shuffle_pd ((__m128d) k[1], (__m128d) r1, 0);
k[2] = (__m128i) _mm_shuffle_pd ((__m128d) r1, (__m128d) r2, 1);
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x2));
k[3] = r1;
k[4] = r2;
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x4));
k[4] = (__m128i) _mm_shuffle_pd ((__m128d) k[4], (__m128d) r1, 0);
k[5] = (__m128i) _mm_shuffle_pd ((__m128d) r1, (__m128d) r2, 1);
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x8));
k[6] = r1;
k[7] = r2;
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x10));
k[7] = (__m128i) _mm_shuffle_pd ((__m128d) k[7], (__m128d) r1, 0);
k[8] = (__m128i) _mm_shuffle_pd ((__m128d) r1, (__m128d) r2, 1);
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x20));
k[9] = r1;
k[10] = r2;
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x40));
k[10] = (__m128i) _mm_shuffle_pd ((__m128d) k[10], (__m128d) r1, 0);
k[11] = (__m128i) _mm_shuffle_pd ((__m128d) r1, (__m128d) r2, 1);
aes192_key_assist (&r1, &r2, _mm_aeskeygenassist_si128 (r2, 0x80));
k[12] = r1;
}
static_always_inline void
aes256_key_assist (__m128i * k, int i, __m128i key_assist)
{
__m128i r, t;
k += i;
r = k[-2];
r ^= t = _mm_slli_si128 (r, 0x4);
r ^= t = _mm_slli_si128 (t, 0x4);
r ^= _mm_slli_si128 (t, 0x4);
r ^= _mm_shuffle_epi32 (key_assist, 0xff);
k[0] = r;
if (i >= 14)
return;
r = k[-1];
r ^= t = _mm_slli_si128 (r, 0x4);
r ^= t = _mm_slli_si128 (t, 0x4);
r ^= _mm_slli_si128 (t, 0x4);
r ^= _mm_shuffle_epi32 (_mm_aeskeygenassist_si128 (k[0], 0x0), 0xaa);
k[1] = r;
}
static_always_inline void
aes256_key_expand (u8x16 * key_schedule, u8 * key)
{
__m128i *k = (__m128i *) key_schedule;
k[0] = _mm_loadu_si128 ((__m128i *) key);
k[1] = _mm_loadu_si128 ((__m128i *) (key + 16));
aes256_key_assist (k, 2, _mm_aeskeygenassist_si128 (k[1], 0x01));
aes256_key_assist (k, 4, _mm_aeskeygenassist_si128 (k[3], 0x02));
aes256_key_assist (k, 6, _mm_aeskeygenassist_si128 (k[5], 0x04));
aes256_key_assist (k, 8, _mm_aeskeygenassist_si128 (k[7], 0x08));
aes256_key_assist (k, 10, _mm_aeskeygenassist_si128 (k[9], 0x10));
aes256_key_assist (k, 12, _mm_aeskeygenassist_si128 (k[11], 0x20));
aes256_key_assist (k, 14, _mm_aeskeygenassist_si128 (k[13], 0x40));
}
#endif
#ifdef __aarch64__
static_always_inline u8x16
aes_inv_mix_column (u8x16 a)
{
return vaesimcq_u8 (a);
}
static const u8x16 aese_prep_mask1 =
{ 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12 };
static const u8x16 aese_prep_mask2 =
{ 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15 };
static inline void
aes128_key_expand_round_neon (u8x16 * rk, u32 rcon)
{
u8x16 r, t, last_round = rk[-1], z = { };
r = vqtbl1q_u8 (last_round, aese_prep_mask1);
r = vaeseq_u8 (r, z);
r ^= (u8x16) vdupq_n_u32 (rcon);
r ^= last_round;
r ^= t = vextq_u8 (z, last_round, 12);
r ^= t = vextq_u8 (z, t, 12);
r ^= vextq_u8 (z, t, 12);
rk[0] = r;
}
void
aes128_key_expand (u8x16 * rk, const u8 * k)
{
rk[0] = vld1q_u8 (k);
aes128_key_expand_round_neon (rk + 1, 0x01);
aes128_key_expand_round_neon (rk + 2, 0x02);
aes128_key_expand_round_neon (rk + 3, 0x04);
aes128_key_expand_round_neon (rk + 4, 0x08);
aes128_key_expand_round_neon (rk + 5, 0x10);
aes128_key_expand_round_neon (rk + 6, 0x20);
aes128_key_expand_round_neon (rk + 7, 0x40);
aes128_key_expand_round_neon (rk + 8, 0x80);
aes128_key_expand_round_neon (rk + 9, 0x1b);
aes128_key_expand_round_neon (rk + 10, 0x36);
}
static inline void
aes192_key_expand_round_neon (u8x8 * rk, u32 rcon)
{
u8x8 r, last_round = rk[-1], z = { };
u8x16 r2, z2 = { };
r2 = (u8x16) vdupq_lane_u64 ((uint64x1_t) last_round, 0);
r2 = vqtbl1q_u8 (r2, aese_prep_mask1);
r2 = vaeseq_u8 (r2, z2);
r2 ^= (u8x16) vdupq_n_u32 (rcon);
r = (u8x8) vdup_laneq_u64 ((u64x2) r2, 0);
r ^= rk[-3];
r ^= vext_u8 (z, rk[-3], 4);
rk[0] = r;
r = rk[-2] ^ vext_u8 (r, z, 4);
r ^= vext_u8 (z, r, 4);
rk[1] = r;
if (rcon == 0x80)
return;
r = rk[-1] ^ vext_u8 (r, z, 4);
r ^= vext_u8 (z, r, 4);
rk[2] = r;
}
void
aes192_key_expand (u8x16 * ek, const u8 * k)
{
u8x8 *rk = (u8x8 *) ek;
ek[0] = vld1q_u8 (k);
rk[2] = vld1_u8 (k + 16);
aes192_key_expand_round_neon (rk + 3, 0x01);
aes192_key_expand_round_neon (rk + 6, 0x02);
aes192_key_expand_round_neon (rk + 9, 0x04);
aes192_key_expand_round_neon (rk + 12, 0x08);
aes192_key_expand_round_neon (rk + 15, 0x10);
aes192_key_expand_round_neon (rk + 18, 0x20);
aes192_key_expand_round_neon (rk + 21, 0x40);
aes192_key_expand_round_neon (rk + 24, 0x80);
}
static inline void
aes256_key_expand_round_neon (u8x16 * rk, u32 rcon)
{
u8x16 r, t, z = { };
r = vqtbl1q_u8 (rk[-1], rcon ? aese_prep_mask1 : aese_prep_mask2);
r = vaeseq_u8 (r, z);
if (rcon)
r ^= (u8x16) vdupq_n_u32 (rcon);
r ^= rk[-2];
r ^= t = vextq_u8 (z, rk[-2], 12);
r ^= t = vextq_u8 (z, t, 12);
r ^= vextq_u8 (z, t, 12);
rk[0] = r;
}
void
aes256_key_expand (u8x16 * rk, const u8 * k)
{
rk[0] = vld1q_u8 (k);
rk[1] = vld1q_u8 (k + 16);
aes256_key_expand_round_neon (rk + 2, 0x01);
aes256_key_expand_round_neon (rk + 3, 0);
aes256_key_expand_round_neon (rk + 4, 0x02);
aes256_key_expand_round_neon (rk + 5, 0);
aes256_key_expand_round_neon (rk + 6, 0x04);
aes256_key_expand_round_neon (rk + 7, 0);
aes256_key_expand_round_neon (rk + 8, 0x08);
aes256_key_expand_round_neon (rk + 9, 0);
aes256_key_expand_round_neon (rk + 10, 0x10);
aes256_key_expand_round_neon (rk + 11, 0);
aes256_key_expand_round_neon (rk + 12, 0x20);
aes256_key_expand_round_neon (rk + 13, 0);
aes256_key_expand_round_neon (rk + 14, 0x40);
}
#endif
static_always_inline void
aes_key_expand (u8x16 * key_schedule, u8 * key, aes_key_size_t ks)
{
switch (ks)
{
case AES_KEY_128:
aes128_key_expand (key_schedule, key);
break;
case AES_KEY_192:
aes192_key_expand (key_schedule, key);
break;
case AES_KEY_256:
aes256_key_expand (key_schedule, key);
break;
}
}
static_always_inline void
aes_key_enc_to_dec (u8x16 * ke, u8x16 * kd, aes_key_size_t ks)
{
int rounds = AES_KEY_ROUNDS (ks);
kd[rounds] = ke[0];
kd[0] = ke[rounds];
for (int i = 1; i < (rounds / 2); i++)
{
kd[rounds - i] = aes_inv_mix_column (ke[i]);
kd[i] = aes_inv_mix_column (ke[rounds - i]);
}
kd[rounds / 2] = aes_inv_mix_column (ke[rounds / 2]);
}
#endif /* __aesni_h__ */
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
tnhmb/CustomRestManager
|
CustomRestManager/CustomRestManager.h
|
<gh_stars>0
//
// CustomRestManager.h
// CustomRestManager
//
// Created by <NAME> on 31/08/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for CustomRestManager.
FOUNDATION_EXPORT double CustomRestManagerVersionNumber;
//! Project version string for CustomRestManager.
FOUNDATION_EXPORT const unsigned char CustomRestManagerVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <CustomRestManager/PublicHeader.h>
|
jacky00000000love/XMTest
|
Example/XMTest/XMAppDelegate.h
|
<gh_stars>0
//
// XMAppDelegate.h
// XMTest
//
// Created by oauth2 on 03/07/2022.
// Copyright (c) 2022 oauth2. All rights reserved.
//
@import UIKit;
@interface XMAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
jacky00000000love/XMTest
|
Example/Pods/Target Support Files/XMLYTest/XMLYTest-umbrella.h
|
<filename>Example/Pods/Target Support Files/XMLYTest/XMLYTest-umbrella.h
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "XMTestManager.h"
FOUNDATION_EXPORT double XMLYTestVersionNumber;
FOUNDATION_EXPORT const unsigned char XMLYTestVersionString[];
|
jacky00000000love/XMTest
|
Example/XMTest/XMViewController.h
|
<filename>Example/XMTest/XMViewController.h<gh_stars>0
//
// XMViewController.h
// XMTest
//
// Created by oauth2 on 03/07/2022.
// Copyright (c) 2022 oauth2. All rights reserved.
//
@import UIKit;
@interface XMViewController : UIViewController
@end
|
jacky00000000love/XMTest
|
XMTest/Classes/XMTestManager.h
|
<reponame>jacky00000000love/XMTest<gh_stars>0
//
// XMTestManager.h
// XMTest
//
// Created by xmly on 2022/3/7.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface XMTestManager : NSObject
+ (XMTestManager*)shareInstance;
- (void)printArgs:(NSString*)str;
@end
NS_ASSUME_NONNULL_END
|
therodfather/Moonbounce
|
Moonbounce/Moonbounce-Bridging-Header.h
|
//
// Moonbounce-Bridging-Header.h
// Moonbounce
//
// Created by Dr. <NAME> on 9/14/20.
// Copyright © 2020 operatorfoundation.org. All rights reserved.
//
#ifndef Moonbounce_Bridging_Header_h
#define Moonbounce_Bridging_Header_h
#endif /* Moonbounce_Bridging_Header_h */
|
rding2454/vtr7
|
ODIN_II/SRC/verilog_bison.h
|
/* A Bison parser, made by GNU Bison 2.3. */
/* Skeleton interface for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
vSYMBOL_ID = 258,
vNUMBER_ID = 259,
vDELAY_ID = 260,
vALWAYS = 261,
vAND = 262,
vASSIGN = 263,
vBEGIN = 264,
vCASE = 265,
vDEFAULT = 266,
vDEFINE = 267,
vELSE = 268,
vEND = 269,
vENDCASE = 270,
vENDMODULE = 271,
vIF = 272,
vINOUT = 273,
vINPUT = 274,
vMODULE = 275,
vNAND = 276,
vNEGEDGE = 277,
vNOR = 278,
vNOT = 279,
vOR = 280,
vFOR = 281,
vOUTPUT = 282,
vPARAMETER = 283,
vPOSEDGE = 284,
vREG = 285,
vWIRE = 286,
vXNOR = 287,
vXOR = 288,
vDEFPARAM = 289,
voANDAND = 290,
voOROR = 291,
voLTE = 292,
voGTE = 293,
voSLEFT = 294,
voSRIGHT = 295,
voEQUAL = 296,
voNOTEQUAL = 297,
voCASEEQUAL = 298,
voCASENOTEQUAL = 299,
voXNOR = 300,
voNAND = 301,
voNOR = 302,
vWHILE = 303,
vINTEGER = 304,
vNOT_SUPPORT = 305,
UOR = 306,
UAND = 307,
UNOT = 308,
UNAND = 309,
UNOR = 310,
UXNOR = 311,
UXOR = 312,
ULNOT = 313,
UADD = 314,
UMINUS = 315,
LOWER_THAN_ELSE = 316
};
#endif
/* Tokens. */
#define vSYMBOL_ID 258
#define vNUMBER_ID 259
#define vDELAY_ID 260
#define vALWAYS 261
#define vAND 262
#define vASSIGN 263
#define vBEGIN 264
#define vCASE 265
#define vDEFAULT 266
#define vDEFINE 267
#define vELSE 268
#define vEND 269
#define vENDCASE 270
#define vENDMODULE 271
#define vIF 272
#define vINOUT 273
#define vINPUT 274
#define vMODULE 275
#define vNAND 276
#define vNEGEDGE 277
#define vNOR 278
#define vNOT 279
#define vOR 280
#define vFOR 281
#define vOUTPUT 282
#define vPARAMETER 283
#define vPOSEDGE 284
#define vREG 285
#define vWIRE 286
#define vXNOR 287
#define vXOR 288
#define vDEFPARAM 289
#define voANDAND 290
#define voOROR 291
#define voLTE 292
#define voGTE 293
#define voSLEFT 294
#define voSRIGHT 295
#define voEQUAL 296
#define voNOTEQUAL 297
#define voCASEEQUAL 298
#define voCASENOTEQUAL 299
#define voXNOR 300
#define voNAND 301
#define voNOR 302
#define vWHILE 303
#define vINTEGER 304
#define vNOT_SUPPORT 305
#define UOR 306
#define UAND 307
#define UNOT 308
#define UNAND 309
#define UNOR 310
#define UXNOR 311
#define UXOR 312
#define ULNOT 313
#define UADD 314
#define UMINUS 315
#define LOWER_THAN_ELSE 316
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
#line 61 "SRC/verilog_bison.y"
{
char *id_name;
char *num_value;
ast_node_t *node;
}
/* Line 1529 of yacc.c. */
#line 177 "SRC/verilog_bison.h"
YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
extern YYSTYPE yylval;
|
vbouquet/tutoriel-ast-clang
|
exemples/file.c
|
<gh_stars>1-10
#include <stdio.h>
int somme(int a, int b) {
return a + b;
}
int division(int a, int b) {
return a / b;
}
void hello_world() {
printf("Hello World!\n");
}
int main(int argc, char *argv[]) {
int a=1, b=2;
hello_world();
somme(a, b);
division(a, b);
return 0;
}
|
defuliu/ZGHubPods
|
Example/ZGPodsWorks/ZGViewController.h
|
<filename>Example/ZGPodsWorks/ZGViewController.h
//
// ZGViewController.h
// ZGPodsWorks
//
// Created by defuliu on 06/01/2020.
// Copyright (c) 2020 defuliu. All rights reserved.
//
@import UIKit;
@interface ZGViewController : UIViewController
@end
|
defuliu/ZGHubPods
|
ZGPodsWorks/Classes/Model/ZGEntityBase.h
|
<filename>ZGPodsWorks/Classes/Model/ZGEntityBase.h
//
// ZGEntityBase.h
// FatDogLogistics
//
// Created by Sandy on 16/11/8.
// Copyright © 2016年 Sandy. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ZGEntityBase : NSObject
/** @解析
itemFromDict: 将 NSDictionary数据解析成本对象
@return ZGEntityBase.
*/
+ (id)itemFromDict:(NSDictionary *)dict;
/** @解析
itemsFromArray: 将 NSArray数据解析成本对象数组
@return NSArray.
*/
+ (NSArray *)itemsFromArray:(NSArray *)array;
@end
|
rue-ryuzaki/stopwatch
|
src/stopwatch.h
|
#ifndef STOPWATCH_H_
#define STOPWATCH_H_
#include <chrono>
#include <cstdint>
#include <string>
// -----------------------------------------------------------------------------
// -- Stopwatch ----------------------------------------------------------------
// -----------------------------------------------------------------------------
class Stopwatch
{
public:
// -- static ---------------------------------------------------------------
static std::string time_to_string(double seconds);
static std::string time_to_string(uint64_t seconds);
// -- constructor ----------------------------------------------------------
Stopwatch();
// -- methods --------------------------------------------------------------
void start();
void stop();
std::string remain_to_string(double percent) const;
uint64_t remain(double percent) const;
bool is_elapsed(uint64_t sec) const;
template <class T, class U = std::ratio<1, 1> >
T elapsed() const
{
return std::chrono::duration<T, std::nano>(m_last - m_start).count() *
std::nano::num * U::den / (std::nano::den * U::num);
}
inline std::chrono::time_point<std::chrono::system_clock> current() const;
private:
std::chrono::time_point<std::chrono::system_clock> m_start;
std::chrono::time_point<std::chrono::system_clock> m_last;
};
#endif // STOPWATCH_H_
|
doomyster/cpp-misctools
|
src/cppmt-env.h
|
/*
Copyright © 2013-2015 <NAME> <<EMAIL>>. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Nicolas Normand "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPPMT_ENV_H_
#define CPPMT_ENV_H_
#include "cppmt-string.h"
#include <cstdlib>
namespace cppmt
{
template <typename T>
struct env_t
{
const char* Name;
T Default;
env_t(const char* n, T def = T());
};
template <typename T>
struct env_bounded_t: public env_t<T>
{
T minVal;
T maxVal;
env_bounded_t(const char* n, T minval, T maxval, T def = T());
};
namespace getEnv
{
class status_t
{
public:
bool wasNull;
bool hasError;
bool wasOutBound;
status_t(bool wNull = false, bool hErr = false, bool wOut = false);
};
template <typename T> static T safe(const env_t<T>& env);
template <typename T> static T safe(const char* envName, T defaultValue = T());
template <typename T> static status_t check(const env_t<T>& env, T* res);
template <typename T> static status_t check(const char* envName, T* res, T defaultValue = T());
template <typename T> static T safeBounded(const env_bounded_t<T>& env);
template <typename T> static T safeBounded(const char* envName, T vmin, T vmax, T defaultValue = T());
template <typename T> static status_t checkBounded(const env_bounded_t<T>& env, T* res);
template <typename T> static status_t checkBounded(const char* envName, T* res, T vmin, T vmax, T defaultValue = T());
} // End of: namespace getEnv
} // End of: namespace cppmt
#include "cppmt-env.hxx"
#endif
|
doomyster/cpp-misctools
|
src/cppmt-zlib.h
|
<reponame>doomyster/cpp-misctools
#ifndef CPPMT_ZLIB_H_
#define CPPMT_ZLIB_H_
#include <iostream>
#include <string>
#include "zlib.h"
namespace cppmt
{
// Internal types. User won't need these
// Usage: avoid code duplication.
// {
typedef int (*flate_fn_t)(z_streamp, int);
template <flate_fn_t T>
class Z_handler
{
protected:
z_stream strm__;
size_t buffer_size__;
char* buf__;
Z_handler(size_t intern_buf_size = 4096);
virtual ~Z_handler();
int filter(std::string& out, const std::string& in, bool flush = false);
};
// }
// Compression and decompression classes handlers
// {
// These handler classes can be used to compress/decompress data.
// You can call any 'compress'/'decompress' methods cumulatively. Just assure the last call
// must be flushed. Once flushed, the stream should not have any remaining data
// to be retrieved.
// The 'status' represents the return value of the inflate/deflate functions.
// Basically, if not Z_OK or Z_STREAM_END, you should worry.
class deflate_handler: public Z_handler<deflate>
{
public:
deflate_handler(int level = 6, size_t intern_buf_size = 4096);
~deflate_handler();
int compress(std::string& out, const std::string& in, bool flush = false); // 'out' will *NOT* be cleared. Data is APPENDED to it.
std::string compress( const std::string& in, int* status = 0, bool flush = false);
std::ostream& compress(std::ostream& os, const std::string& in, int* status = 0, bool flush = false);
};
class inflate_handler: public Z_handler<inflate>
{
public:
inflate_handler(size_t intern_buf_size = 4096);
~inflate_handler();
int decompress(std::string& out, const std::string& in, bool flush = false); // 'out' will *NOT* be cleared. Data is APPENDED to it.
std::string decompress( const std::string& in, int* status = 0, bool flush = false);
std::ostream& decompress(std::ostream& os, const std::string& in, int* status = 0, bool flush = false);
};
// }
} // End of: namespace cppmt
#endif
|
doomyster/cpp-misctools
|
src/cppmt-sqlite.h
|
/*
Copyright © 2014 <NAME> <<EMAIL>>. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPP_MISCTOOLS_SQLITE3_H_
#define CPP_MISCTOOLS_SQLITE3_H_
#include <sqlite3.h>
#include "cppmt-exceptions.h"
#include "cppmt-string.h"
#include <map>
#include <vector>
namespace cppmt
{
class sqlite_exception: public exception
{
public:
class close_t { public: close_t() {} };
static const close_t close_db;
sqlite_exception(sqlite3* db, const string& msg): exception((msg + ": ") + sqlite3_errmsg(db)) {}
sqlite_exception(const string& fn, const string& msg): exception( fn + ": " + msg ) {}
sqlite_exception(const string& fn, const string& msg, const std::string& rq): exception( fn + ": " + msg + "; Request was: " + rq) {}
sqlite_exception(sqlite3* db, const string& msg, const close_t& c): exception((msg + ": ") + sqlite3_errmsg(db)) { sqlite3_close(db); }
~sqlite_exception() throw() {}
virtual const char* type() const throw() { return "sqlite_exception"; }
};
class Sqlite
{
public:
class no_result_t { public: no_result_t() {} };
class rowid_t { public: rowid_t() {} };
static const no_result_t no_result;
static const rowid_t rowid;
public:
class cell_t
{
public:
std::string value;
std::string columnName;
bool isNull;
cell_t();
cell_t(const char* val, const string& col);
};
class result_t;
class row_t
{
friend class Sqlite;
friend class result_t;
public:
typedef std::vector<cell_t> cells_vector_t;
typedef cells_vector_t::const_iterator const_iterator;
typedef cells_vector_t::size_type size_type;
protected:
std::vector<cell_t> cells__;
std::map<string, int> cellsByName__;
row_t();
row_t(int argc, char** argv, char** name);
public:
size_type numCells() const;
const string& getValue ( int idx) const;
const string& getValue (const string& col) const;
bool isNull ( int idx) const;
bool isNull (const string& col) const;
const string& getColumnName( int idx) const;
template <typename T> T getValue( int idx) const;
template <typename T> T getValue(const string& col) const;
const cell_t& getCell( int idx) const;
const cell_t& getCell(const string& col) const;
const_iterator begin() const;
const_iterator end () const;
};
class result_t
{
friend class Sqlite;
public:
typedef std::vector<row_t> rows_vector_t;
typedef rows_vector_t::const_iterator const_iterator;
typedef rows_vector_t::size_type size_type;
protected:
rows_vector_t rows__;
mutable rows_vector_t::const_iterator current__;
void add(int argc, char** argv, char** name);
public:
result_t();
result_t(const result_t& r);
result_t& operator=(const result_t& r);
void clear();
const string& getValue (int idx) const;
const string& getValue (const string& col) const;
bool isNull (int idx) const;
bool isNull (const string& col) const;
const string& getColumnName(int idx) const;
template <typename T> T getValue( int idx) const;
template <typename T> T getValue(const string& col) const;
const row_t& getCurrentRow() const;
const row_t& getRow(int idx) const;
row_t::size_type numCells() const;
bool nextRow() const; // Returns false on invalid entry (after the last one).
size_type numRows() const;
};
protected:
sqlite3* db__;
static int cb_function(void* data, int argc, char** argv, char** colName);
private:
// Forbid these constructions; seems to lead to incorrect states
Sqlite(const Sqlite& s) {}
Sqlite& operator=(const Sqlite& s) { return *this; }
public:
typedef int (*sqlite_cb)(void*, int, char**, char**); // data, argc, argv, column_name
typedef std::vector<result_t> rows_t;
Sqlite(const string& file = ":memory:");
virtual ~Sqlite();
void exec(const string& query, const no_result_t& nores);
void exec(const string& query, sqlite_cb cb, void* data);
sqlite3_int64 exec(const string& query, const rowid_t& rid);
result_t exec(const string& query);
void exec(const string& query, result_t* res); // can save a vector copy
void saveInto(Sqlite& dest);
sqlite3* getDB() { return db__; }
void enable_extension(bool enable){sqlite3_enable_load_extension(db__,enable); }
};
} // End of: namespace cppmt
#include "cppmt-sqlite.hxx"
#endif
|
doomyster/cpp-misctools
|
src/cppmt-string.h
|
/*
Copyright © 2013-2014 <NAME> <<EMAIL>>. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Nicolas Normand "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPP_TOOLS_H_
#define CPP_TOOLS_H_
#include <string>
#include <sstream>
#include <vector>
namespace cppmt
{
using std::string;
template <typename T, typename STRINGTYPE>
T fromString(const STRINGTYPE& v, bool* success = NULL)
{
T cv;
std::stringstream ss;
ss << v;
ss >> cv;
if (success) {
*success = (ss && ss.eof());
}
return cv;
}
template <typename T, typename STRINGTYPE>
bool fromString(T& val, const STRINGTYPE& v)
{
bool r;
val = fromString<T>(v, &r);
return r;
}
template <typename T>
string toString(T v)
{
std::stringstream ss;
ss << v;
return ss.str();
}
bool endsWith(const string& haystack, const string& needle);
// alter *str
// str must not be NULL
void trim(string* str);
void ltrim(string* str);
void rtrim(string* str);
string trim(const string& str);
string ltrim(const string& str);
string rtrim(const string& str);
std::vector<string> split( const string& str, char delim);
void split(std::vector<string>& tokens, const string& str, char delim);
}
#endif
|
doomyster/cpp-misctools
|
src/cppmt-encoding.h
|
<reponame>doomyster/cpp-misctools
#ifndef CPPMT_ENCODING_H_
#define CPPMT_ENCODING_H_
#include <string>
#include <iostream>
namespace cppmt
{
namespace base64
{
std::string encode(const char* in, size_t s);
std::string encode(const std::string& in);
void encode(const std::string& in, std::string& out);
void encode(std::istream& is, std::ostream& os );
std::string decode(const char* in, size_t s);
std::string decode(const std:: string& in);
void decode(const std:: string& in, std:: string& out);
void decode( std::istream& is, std::ostream& os );
} // End of: namespace base64
} // End of: namespace cppmt
#endif
|
doomyster/cpp-misctools
|
src/cppmt-exceptions.h
|
<filename>src/cppmt-exceptions.h
/*
Copyright © 2013-2014 <NAME> <<EMAIL>>. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Nicolas Normand "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPP_MISCTOOLS_EXCEPTIONS_H_
#define CPP_MISCTOOLS_EXCEPTIONS_H_
#include <exception>
#include <string>
#include <cstring>
#include <typeinfo>
#include <cerrno>
extern "C"
{
#include <netdb.h>
}
#define CPPMT_MAKE_BASIC_EXCEPTION_CLASS(NAME, VIRTUAL) \
class NAME: public cppmt::exception \
{ \
public: \
NAME(const std::string& msg_): cppmt::exception(msg_) {} \
VIRTUAL ~NAME() throw() {} \
\
VIRTUAL const char* type() const throw() { return #NAME ; } \
}
namespace cppmt
{
class exception: public std::exception
{
private:
mutable std::string full_msg__;
protected:
std::string msg__;
exception() {}
public:
exception(const std::string& msg_): msg__(msg_) {}
virtual ~exception() throw() {}
virtual const char* type() const throw() { return "exception"; }
virtual const char* what() const throw() { full_msg__ = type(); full_msg__ += ": " + msg__; return full_msg__.c_str(); }
virtual const std::string& user_message() const { return msg__; }
};
class stdc_exception: public exception
{
protected:
int c_errno__;
public:
stdc_exception(int c_errno_, const std::string& msg_): exception((msg_ + ": ") + strerror(c_errno_)), c_errno__(c_errno_) {}
virtual ~stdc_exception() throw() {}
virtual const char* type() const throw() { return "stdc_exception"; }
inline int c_errno() const throw() { return c_errno__; }
};
class h_exception: public exception
{
protected:
int h_errno__;
public:
h_exception(int h_errno_, const std::string& msg_): exception((msg_ + ": ") + hstrerror(h_errno_)), h_errno__(h_errno_) {}
virtual ~h_exception() throw() {}
virtual const char* type() const throw() { return "h_exception"; }
inline int herrno() const throw() { return h_errno__; } // Apparently, I can't call the method 'h_errno'... Hell ! 'h_errno' is a #define !!
};
} // namespace cppmt
#endif
|
doomyster/cpp-misctools
|
src/cppmt-getopt.h
|
/*
Copyright © 2013-2014 <NAME> <<EMAIL>>. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPP_TOOLS_GETOPT_H_
#define CPP_TOOLS_GETOPT_H_
#include <getopt.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include "cppmt-string.h"
namespace cppmt
{
class Opts
{
public:
typedef string (*convert_t)(void*, char*);
typedef enum
{
EXIT_ON_OPEN_FAILURE,
CONTINUE_ON_OPEN_FAILURE,
SILENT_CONTINUE_ON_OPEN_FAILURE
} cfg_fail_t;
protected:
struct opt_t
{
string long_opt;
string helpstring;
void* recv_opt;
convert_t conv;
bool was_found;
char short_opt;
int has_arg;
bool was_in_command_line;
opt_t(const string& long_opt, char short_opt, const string& helpstring, int has_arg, void* recv_opt, convert_t conv);
};
bool fail_on_open_error__;
bool silent_on_open_error__;
bool got_errors__;
bool autoshow_help__;
bool autoshow_version__;
string version__;
string help_prefix__;
string help_suffix__;
std::ostream& out_stream__;
std::ostream& err_stream__;
void (*exit_func__)(int);
string config_file__;
std::vector<opt_t> all_opts__;
bool find_same_opt(const string& long_opt, char short_opt) const;
void build_struct_option_array(std::vector<struct option>& opts, string& short_opts, int* flag) const;
static string convert_flag(void* recv_opt, char* opt_arg);
int read_config_file();
void handle_line(const std::string& line);
public:
Opts(std::ostream& o_stream = std::cout, std::ostream& e_stream = std::cerr);
void set_exit_func(void (*exit_func)(int));
template <typename T>
static string convert(void* recv_opt, char* opt_arg);
template<typename T>
int add(const string& long_opt, char short_opt, const string& helpstring, int has_arg, T* recv_opt, convert_t conv = Opts::convert<T>);
int add(const string& long_opt, char short_opt, const string& helpstring, bool* flag);
int auto_config_file(const string& long_opt, char short_opt, const string& helpstring, const string& default_location="");
int auto_config_file(const string& long_opt, char short_opt, const string& helpstring, cfg_fail_t fail, const string& default_location="");
int auto_help(); // Add option "--help", "-h". Uses "-H" if option "-h" exists
int auto_help(const string& long_opt, char short_opt, const string& helpstring="Show this help and exit");
int auto_version(const string& version); // If version.empty() == true, disable this feature. Add option "--version", "-v". Uses "-V" if option "-v" exists
int auto_version(const string& version, const string& long_opt, char short_opt, const string& helpstring="show version and exit");
void set_help_prefix_message(const string& help_prefix);
void set_help_suffix_message(const string& help_suffix);
int get(int argc, char** argv, int force_optind=1); // Returns optind
bool got_errors() const;
void show_help();
};
template <>
string Opts::convert<string>(void* recv_opt, char* opt_arg);
} // End of namespace cppmt
#include "cppmt-getopt.hxx"
#endif
|
HiromuKato/UE4HoloSample
|
UE4HoloSample/Source/UE4HoloSample/Public/HoloLensWinrtDLL.h
|
#pragma once
class HoloLensWinrtDLL
{
public:
_declspec(dllexport) static void OpenFileDialogue();
};
|
Guitarheroua/quickflux
|
src/qfappscript.h
|
#ifndef QFAPPSCRIPT_H
#define QFAPPSCRIPT_H
#include <QObject>
#include <QJSValue>
#include <QQmlScriptString>
#include <QQuickItem>
#include <QQmlParserStatus>
#include <QPointer>
#include <QFAppDispatcher>
#include "priv/qfappscriptrunnable.h"
class QFAppScript : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(QQmlScriptString script READ script WRITE setScript NOTIFY scriptChanged)
Q_PROPERTY(bool running READ running WRITE setRunning NOTIFY runningChanged)
Q_PROPERTY(QString runWhen READ runWhen WRITE setRunWhen NOTIFY runWhenChanged)
Q_PROPERTY(QJSValue message READ message NOTIFY messageChanged)
Q_PROPERTY(int listenerId READ listenerId WRITE setListenerId NOTIFY listenerIdChanged)
Q_PROPERTY(QVector<int> waitFor READ waitFor WRITE setWaitFor NOTIFY waitForChanged)
Q_PROPERTY(bool autoExit READ autoExit WRITE setAutoExit NOTIFY autoExitChanged)
public:
explicit QFAppScript(QQuickItem *parent = nullptr);
QQmlScriptString script() const;
void setScript(const QQmlScriptString &script);
bool running() const;
QString runWhen() const;
void setRunWhen(const QString &runWhen);
QJSValue message() const;
void setMessage(const QJSValue &message);
int listenerId() const;
void setListenerId(int listenerId);
QVector<int> waitFor() const;
void setWaitFor(const QVector<int> &waitFor);
bool autoExit() const;
void setAutoExit(bool autoExit);
signals:
void started();
void finished(int returnCode);
void scriptChanged();
void runningChanged();
void runWhenChanged();
void messageChanged();
void listenerIdChanged();
void waitForChanged();
void autoExitChanged();
public slots:
void exit(int returnCode = 0);
void run(const QJSValue &message = QJSValue());
QFAppScriptRunnable* once(const QJSValue &condition, const QJSValue &script);
void on(const QJSValue &condition, const QJSValue &script);
private slots:
void onDispatched(const QString &type, const QJSValue &message);
private:
virtual void componentComplete();
void abort();
void clear();
void setRunning(bool running);
void setListenerWaitFor();
QQmlScriptString m_script;
QVector<QFAppScriptRunnable*> m_runnables;
QPointer<QFAppDispatcher> m_dispatcher;
QString m_runWhen;
bool m_running;
bool m_processing;
int m_listenerId;
bool m_autoExit;
// The message object passed to run()
QJSValue m_message;
QFListener* m_listener;
QVector<int> m_waitFor;
};
#endif // QFAPPSCRIPT_H
|
Guitarheroua/quickflux
|
src/qfstore.h
|
#ifndef QFSTORE_H
#define QFSTORE_H
#include <QObject>
#include <QQmlListProperty>
#include <QJSValue>
#include <QPointer>
#include <QQmlParserStatus>
#include "qfactioncreator.h"
#include "qfdispatcher.h"
class QFStore : public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* bindSource READ bindSource WRITE setBindSource NOTIFY bindSourceChanged)
Q_PROPERTY(QQmlListProperty<QObject> children READ children)
Q_PROPERTY(QQmlListProperty<QObject> redispatchTargets READ redispatchTargets)
Q_PROPERTY(bool filterFunctionEnabled MEMBER m_filterFunctionEnabled NOTIFY filterFunctionEnabledChanged)
Q_CLASSINFO("DefaultProperty", "children")
public:
explicit QFStore(QObject *parent = nullptr);
QQmlListProperty<QObject> children();
QObject* bindSource() const;
void setBindSource(QObject* source);
QQmlListProperty<QObject> redispatchTargets();
signals:
void dispatched(const QString &type, const QJSValue &message);
void bindSourceChanged();
void filterFunctionEnabledChanged();
public slots:
void dispatch(const QString &type, const QJSValue &message = QJSValue());
void bind(QObject* source);
protected:
void classBegin();
void componentComplete();
private slots:
void setup();
private:
QObjectList m_children;
QPointer<QObject> m_bindSource;
QPointer<QFActionCreator> m_actionCreator;
QPointer<QFDispatcher> m_dispatcher;
QObjectList m_redispatchTargets;
bool m_filterFunctionEnabled;
};
#endif // QFSTORE_H
|
Guitarheroua/quickflux
|
src/qfdispatcher.h
|
#pragma once
#include <QObject>
#include <QVariantMap>
#include <QJSValue>
#include <QQueue>
#include <QPair>
#include <QQmlEngine>
#include <QPointer>
#include "priv/qflistener.h"
#include "priv/qfhook.h"
/// Message Dispatcher
class QFDispatcher : public QObject
{
Q_OBJECT
public:
explicit QFDispatcher(QObject *parent = nullptr);
~QFDispatcher() = default;
signals:
/// Listeners should listen on this signal to get the latest dispatched message from AppDispatcher
Q_SIGNAL void dispatched(const QString &type, const QJSValue &message);
public slots:
/// Dispatch a message via Dispatcher
/**
@param type The type of the message
@param message The message content
@reentrant
Dispatch a message with type via the AppDispatcher. Listeners should listen on the "dispatched"
signal to be notified.
Usually, it will emit "dispatched" signal immediately after calling dispatch(). However, if
AppDispatcher is still dispatching messages, the new messages will be placed on a queue, and
wait until it is finished. It guarantees the order of messages are arrived in sequence to
listeners
*/
Q_INVOKABLE void dispatch(const QString &type, const QJSValue &message = QJSValue());
Q_INVOKABLE void waitFor(const QVector<int> &ids);
Q_INVOKABLE int addListener(const QJSValue &callback);
Q_INVOKABLE void removeListener(int id);
public:
void dispatch(const QString& type, const QVariant& message);
int addListener(QFListener* listener);
QQmlEngine *engine() const;
void setEngine(QQmlEngine *engine);
QFHook *hook() const;
void setHook(QFHook *hook);
private slots:
/// Invoke listener and emit the dispatched signal
void send(const QString &type, const QJSValue &message);
private:
void invokeListeners(const QVector<int> &ids);
bool m_dispatching;
QPointer<QQmlEngine> m_engine;
// Queue for dispatching messages
QQueue<QPair<QString,QJSValue > > m_queue;
// Next id for listener.
int m_nextListenerId;
// Registered listener
QMap<int, QPointer<QFListener> > m_listeners;
// Current dispatching listener id
int m_dispatchingListenerId;
// Current dispatching message
QJSValue m_dispatchingMessage;
// Current dispatching message type
QString m_dispatchingMessageType;
// List of listeners pending to be invoked.
QMap<int,bool> m_pendingListeners;
// List of listeners blocked in waitFor()
QMap<int,bool> m_waitingListeners;
QPointer<QFHook> m_hook;
};
|
Guitarheroua/quickflux
|
src/qfhydrate.h
|
#ifndef QFHYDRATE_H
#define QFHYDRATE_H
#include <QObject>
#include <QVariantMap>
class QFHydrate : public QObject
{
Q_OBJECT
public:
explicit QFHydrate(QObject *parent = nullptr);
signals:
public slots:
void rehydrate(QObject *dest, const QVariantMap & source);
QVariantMap dehydrate(QObject *source);
};
#endif // QFHYDRATE_H
|
Guitarheroua/quickflux
|
src/qfappdispatcher.h
|
<reponame>Guitarheroua/quickflux<gh_stars>0
#ifndef QFAPPDISPATCHER_H
#define QFAPPDISPATCHER_H
#include <QObject>
#include "qfdispatcher.h"
class QFAppDispatcher : public QFDispatcher
{
Q_OBJECT
public:
explicit QFAppDispatcher(QObject *parent = nullptr);
/// Obtain the singleton instance of AppDispatcher for specific QQmlEngine
static QFAppDispatcher* instance(QQmlEngine* engine);
/// Obtain a singleton object from package for specific QQmlEngine
static QObject* singletonObject(QQmlEngine* engine, const QString &package,
int versionMajor,
int versionMinor,
const QString &typeName);
};
#endif // QFAPPDISPATCHER_H
|
Guitarheroua/quickflux
|
src/qfappscriptgroup.h
|
#pragma once
#include <QQuickItem>
#include <QPointer>
#include "qfappscript.h"
class QFAppScriptGroup : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(QJSValue scripts READ scripts WRITE setScripts NOTIFY scriptsChanged)
public:
QFAppScriptGroup(QQuickItem* parent = nullptr);
QJSValue scripts() const;
void setScripts(const QJSValue &scripts);
signals:
void scriptsChanged();
public slots:
void exitAll();
private slots:
void onStarted();
private:
QJSValue m_scripts;
QVector<QPointer<QFAppScript> > objects;
};
|
Guitarheroua/quickflux
|
src/qfapplistenergroup.h
|
<filename>src/qfapplistenergroup.h<gh_stars>0
#ifndef QFAPPLISTENERGROUP_H
#define QFAPPLISTENERGROUP_H
#include <QQuickItem>
#include <QQmlParserStatus>
#include "priv/qflistener.h"
class QFAppListenerGroup : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(QVector<int> listenerIds READ listenerIds WRITE setListenerIds NOTIFY listenerIdsChanged)
Q_PROPERTY(QVector<int> waitFor READ waitFor WRITE setWaitFor NOTIFY waitForChanged)
public:
QFAppListenerGroup(QQuickItem* parent = nullptr);
QVector<int> listenerIds() const;
void setListenerIds(const QVector<int> &listenerIds);
QVector<int> waitFor() const;
void setWaitFor(const QVector<int> &waitFor);
public slots:
signals:
void listenerIdsChanged();
void waitForChanged();
private:
virtual void componentComplete();
QVector<int> search(QQuickItem* item);
void setListenerWaitFor();
QVector<int> m_waitFor;
QVector<int> m_listenerIds;
int m_listenerId;
QFListener* m_listener;
};
#endif // QFAPPLISTENERGROUP_H
|
Guitarheroua/quickflux
|
src/priv/qflistener.h
|
<filename>src/priv/qflistener.h
#ifndef QFLISTENER_H
#define QFLISTENER_H
#include <QObject>
#include <QJSValue>
#include <QVector>
class QFDispatcher;
/// A listener class for AppDispatcher.
class QFListener : public QObject
{
Q_OBJECT
public:
explicit QFListener(QObject *parent = nullptr);
~QFListener() = default;
QJSValue callback() const;
void setCallback(const QJSValue &callback);
void dispatch(QFDispatcher* dispatcher, const QString &type, const QJSValue &message);
int listenerId() const;
void setListenerId(int listenerId);
QVector<int> waitFor() const;
void setWaitFor(const QVector<int> &waitFor);
signals:
void dispatched(const QString &type, const QJSValue &message);
public slots:
private:
QJSValue m_callback;
int m_listenerId;
QVector<int> m_waitFor;
};
#endif // QFLISTENER_H
|
Guitarheroua/quickflux
|
src/priv/quickfluxfunctions.h
|
<filename>src/priv/quickfluxfunctions.h
#ifndef QUICKFLUXFUNCTIONS_H
#define QUICKFLUXFUNCTIONS_H
#include <QJSValue>
namespace QuickFlux {
void printException(const QJSValue &value);
}
#if ((QT_VERSION == QT_VERSION_CHECK(5,7,1)) || \
(QT_VERSION == QT_VERSION_CHECK(5,8,0)) || \
(QT_VERSION == QT_VERSION_CHECK(5,6,2)) || \
defined(SAILFISH_OS))
/* A dirty hack to fix QTBUG-58133 and #13 issue.
Reference:
1. https://bugreports.qt.io/browse/QTBUG-58133
2. https://github.com/benlau/quickflux/issues/13
*/
#define QF_PRECHECK_DISPATCH(engine, type, message) {\
if (message.isUndefined() && engine) { \
message = engine->toScriptValue<QVariant>(QVariant()); \
}\
}
#else
#define QF_PRECHECK_DISPATCH(engine, type, message) Q_UNUSED(engine)
#endif
#endif // QUICKFLUXFUNCTIONS_H
|
Guitarheroua/quickflux
|
src/qfactioncreator.h
|
<reponame>Guitarheroua/quickflux<filename>src/qfactioncreator.h
#ifndef QFACTIONCREATOR_H
#define QFACTIONCREATOR_H
#include <QObject>
#include <QQmlParserStatus>
#include <QFAppDispatcher>
#include <QPointer>
#include "priv/qfsignalproxy.h"
class QFActionCreator : public QObject, public QQmlParserStatus
{
Q_OBJECT
Q_INTERFACES(QQmlParserStatus)
Q_PROPERTY(QFDispatcher* dispatcher READ dispatcher WRITE setDispatcher NOTIFY dispatcherChanged)
public:
explicit QFActionCreator(QObject *parent = nullptr);
QFDispatcher *dispatcher() const;
void setDispatcher(QFDispatcher *value);
public slots:
QString genKeyTable();
void dispatch(const QString &type, const QJSValue &message = QJSValue());
signals:
void dispatcherChanged();
protected:
void classBegin();
void componentComplete();
private:
QPointer<QFDispatcher> m_dispatcher;
QList<QFSignalProxy*> m_proxyList;
};
#endif // QFACTIONCREATOR_H
|
Guitarheroua/quickflux
|
src/priv/qfhook.h
|
<gh_stars>0
#pragma once
#include <QObject>
#include <QJSValue>
class QFHook : public QObject
{
Q_OBJECT
public:
using QObject::QObject;
virtual void dispatch(const QString &type, const QJSValue &message) = 0;
signals:
void dispatched(const QString &type, const QJSValue &message);
};
|
RIP95/SP_Adapter
|
Middlewares/ST/STM32_USB_Device_Library/Class/HID/Inc/usbd_hid.h
|
/**
******************************************************************************
* @file usbd_hid.h
* @author MCD Application Team
* @version V2.4.2
* @date 11-December-2015
* @brief Header file for the usbd_hid_core.c file.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2015 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_HID_H
#define __USB_HID_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
#define HID_EPIN_ADDR 0x81
#define HID_EPIN_SIZE 0x0a
#define HID_EPOUT_ADDR 0x01
#define HID_EPOUT_SIZE 0x40
#define USB_HID_CONFIG_DESC_SIZ 41
#define USB_HID_DESC_SIZ 9
#define HID_JOY_REPORT_DESC_SIZE 100
#define HID_DESCRIPTOR_TYPE 0x21
#define HID_REPORT_DESC 0x22
#define HID_HS_BINTERVAL 0x01
#define HID_FS_BINTERVAL 0x01
#define HID_POLLING_INTERVAL 0x01
#define HID_REQ_SET_PROTOCOL 0x0B
#define HID_REQ_GET_PROTOCOL 0x03
#define HID_REQ_SET_IDLE 0x0A
#define HID_REQ_GET_IDLE 0x02
#define HID_REQ_SET_REPORT 0x09
#define HID_REQ_GET_REPORT 0x01
typedef enum
{
HID_IDLE = 0,
HID_BUSY,
}
HID_StateTypeDef;
__ALIGN_BEGIN typedef struct
{
uint32_t Protocol;
uint32_t IdleState;
uint32_t AltSetting;
uint8_t HIDRxBuffer[HID_EPOUT_SIZE];
uint32_t HIDRxLength;
uint8_t IsReportAvailable;
HID_StateTypeDef state;
}
USBD_HID_HandleTypeDef __ALIGN_END;
extern unsigned short x_low_th;
extern unsigned short y_low_th;
extern unsigned short x_high_th;
extern unsigned short y_high_th;
extern unsigned short report2send;
extern unsigned short shifter;
extern USBD_ClassTypeDef USBD_HID;
#define USBD_HID_CLASS &USBD_HID
uint8_t USBD_HID_SendReport(USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len);
uint32_t USBD_HID_GetPollingInterval(USBD_HandleTypeDef *pdev);
#ifdef __cplusplus
}
#endif
#endif /* __USB_HID_H */
|
RIP95/SP_Adapter
|
SP_Profiler/Inc/Hidsdi++.h
|
<reponame>RIP95/SP_Adapter<filename>SP_Profiler/Inc/Hidsdi++.h
/*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
HIDDLL.H
Abstract:
This module contains the PUBLIC definitions for the
code that implements the HID dll.
Environment:
Kernel & user mode
Revision History:
Aug-96 : created by <NAME>
--*/
#ifndef _HIDSDI_H
#define _HIDSDI_H
//#include "wtypes.h"
//#include <windef.h>
//#include <win32.h>
//#include <basetyps.h>
typedef LONG NTSTATUS;
#include "hidusage.h"
#include "hidpi++.h"
typedef struct _HIDD_CONFIGURATION {
PVOID cookie;
ULONG size;
ULONG RingBufferSize;
} HIDD_CONFIGURATION, *PHIDD_CONFIGURATION;
typedef struct _HIDD_ATTRIBUTES {
ULONG Size; // = sizeof (struct _HIDD_ATTRIBUTES)
//
// Vendor ids of this hid device
//
USHORT VendorID;
USHORT ProductID;
USHORT VersionNumber;
//
// Additional fields will be added to the end of this structure.
//
} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
extern "C" BOOLEAN __stdcall
HidD_GetAttributes (
IN HANDLE HidDeviceObject,
OUT PHIDD_ATTRIBUTES Attributes
);
/*++
Routine Description:
Fill in the given HIDD_ATTRIBUTES structure with the attributes of the
given hid device.
--*/
extern "C" void __stdcall
HidD_GetHidGuid (
OUT LPGUID HidGuid
);
extern "C" BOOLEAN __stdcall
HidD_GetPreparsedData (
IN HANDLE HidDeviceObject,
OUT PHIDP_PREPARSED_DATA * PreparsedData
);
/*++
Routine Description:
Given a handle to a valid Hid Class Device Oject retrieve the preparsed data.
This routine will ``malloc'' the apropriately size buffer to hold this
preparsed data. It is up to the caller to then free that data at the
caller's conveniance.
Arguments:
HidDeviceObject a handle to a HidDeviceObject. The client can obtain this
handle via a create file on a string name of a Hid device.
This string name can be obtained using standard PnP calls.
PreparsedData an opaque data used by other functions in this library to
retreive information about a given device.
Return Value:
TRUE if successful.
errors returned by DeviceIoControl
--*/
extern "C" BOOLEAN __stdcall
HidD_FreePreparsedData (
IN PHIDP_PREPARSED_DATA PreparsedData
);
extern "C" BOOLEAN __stdcall
HidD_FlushQueue (
IN HANDLE HidDeviceObject
);
/*++
Routine Description:
Flush the input queue for the given HID device.
Arguments:
HidDeviceObject a handle to a HidDeviceObject. The client can obtain this
handle via a create file on a string name of a Hid device.
This string name can be obtained using standard PnP calls.
Return Value:
TRUE if successful
errors returned by DeviceIoControl
--*/
extern "C" BOOLEAN __stdcall
HidD_GetConfiguration (
IN HANDLE HidDeviceObject,
OUT PHIDD_CONFIGURATION Configuration,
IN ULONG ConfigurationLength
);
/*++
Routine Description:
Get the configuration information for this hid device
Arguments:
HidDeviceObject a handle to a HidDeviceObject.
Configuration a configuration structure. You MUST call HidD_GetConfiguration
before you can modify the configuration and use
HidD_SetConfiguration.
ConfigurationLength that is ``sizeof (HIDD_CONFIGURATION)'' using this
parameter we can later increase the length of the configuration
array and maybe not break older apps.
Return Value:
same as others
--*/
extern "C" BOOLEAN __stdcall
HidD_SetConfiguration (
IN HANDLE HidDeviceObject,
IN PHIDD_CONFIGURATION Configuration,
IN ULONG ConfigurationLength
);
/*++
Routine Description:
Set the configuration information for this hid device
Arguments:
HidDeviceObject a handle to a HidDeviceObject.
Configuration a configuration structure. You MUST call HidD_GetConfiguration
before you can modify the configuration and use
HidD_SetConfiguration.
ConfigurationLength that is ``sizeof (HIDD_CONFIGURATION)'' using this
parameter will allow us later to inclrease the size of the
configuration structure.
Return Value:
same as others
--*/
extern "C" BOOLEAN __stdcall
HidD_GetFeature (
IN HANDLE HidDeviceObject,
OUT PVOID ReportBuffer,
IN ULONG ReportBufferLength
);
/*++
Routine Description:
Retrieve a feature report from a HID device.
--*/
extern "C" BOOLEAN __stdcall
HidD_SetFeature (
IN HANDLE HidDeviceObject,
IN PVOID ReportBuffer,
IN ULONG ReportBufferLength
);
/*++
Routine Description:
Send a feature report to a HID device.
--*/
extern "C" BOOLEAN __stdcall
HidD_GetNumInputBuffers (
IN HANDLE HidDeviceObject,
OUT PULONG NumberBuffers
);
extern "C" BOOLEAN __stdcall
HidD_SetNumInputBuffers (
IN HANDLE HidDeviceObject,
OUT ULONG NumberBuffers
);
/*++
Routine Description:
Number of hid packets actually retained
--*/
extern "C" BOOLEAN __stdcall
HidD_GetPhysicalDescriptor (
IN HANDLE HidDeviceObject,
OUT PVOID Buffer,
IN ULONG BufferLength
);
extern "C" BOOLEAN __stdcall
HidD_GetManufacturerString (
IN HANDLE HidDeviceObject,
OUT PVOID Buffer,
IN ULONG BufferLength
);
extern "C" BOOLEAN __stdcall
HidD_GetProductString (
IN HANDLE HidDeviceObject,
OUT PVOID Buffer,
IN ULONG BufferLength
);
extern "C" BOOLEAN __stdcall
HidD_GetSerialNumberString (
IN HANDLE HidDeviceObject,
OUT PVOID Buffer,
IN ULONG BufferLength
);
#endif
|
RIP95/SP_Adapter
|
Src/main.c
|
/**
******************************************************************************
* File Name : main.c
* Description : Main program body
******************************************************************************
*
* COPYRIGHT(c) 2016 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_hal.h"
#include "usb_device.h"
#include "usbd_hid.h"
#include "eeprom.h"
TIM_HandleTypeDef htim14;
ADC_HandleTypeDef hadc;
DMA_HandleTypeDef hdma_adc;
SPI_HandleTypeDef hspi1;
#define X_AXIS_LOW_TH 1400
#define X_AXIS_HIGH_TH 2500
#define Y_AXIS_LOW_TH 500
#define Y_AXIS_HIGH_TH 2600
#define X_AXIS (axis[0] & 0xffffu)
#define Y_AXIS (axis[1] & 0xffffu)
#define T_AXIS (axis[2] & 0xffffu)
#define B_AXIS (axis[3] & 0xffffu)
#define C_AXIS (axis[4] & 0xffffu)
__ALIGN_BEGIN static volatile uint32_t axis[5] __ALIGN_END = { 0, 0, 0, 0, 0 }; // Y, X, T, B, C
__ALIGN_BEGIN static uint8_t rx_buffer[2] __ALIGN_END;
/* Virtual address defined by the user: 0xFFFF value is prohibited */
#define X_AXIS_LOW_VADDR 0x1001
#define X_AXIS_HIGH_VADDR 0x1002
#define Y_AXIS_LOW_VADDR 0x1003
#define Y_AXIS_HIGH_VADDR 0x1004
#if BOARD_REV >= 14
# define SHIFTER_TYPE_VADDR 0x1005
#endif
__ALIGN_BEGIN uint16_t VirtAddVarTab[NB_OF_VAR] __ALIGN_END =
{
X_AXIS_LOW_VADDR, X_AXIS_HIGH_VADDR, Y_AXIS_LOW_VADDR, Y_AXIS_HIGH_VADDR
};
struct __packed
{
uint8_t id; // 0x01
uint8_t buttons; // red + black
uint8_t gears; // 1-7 (reverse)
uint8_t d_pad; // lower 4 bits
uint16_t axis[5];
#if BOARD_REV >= 14
uint16_t threshold[4];
uint8_t sh_type;
#endif
} report;
unsigned short x_low_th = X_AXIS_LOW_TH;
unsigned short y_low_th = Y_AXIS_LOW_TH;
unsigned short x_high_th = X_AXIS_HIGH_TH;
unsigned short y_high_th = Y_AXIS_HIGH_TH;
unsigned short report2send = 0;
static unsigned short x_axis = 2048;
static unsigned short y_axis = 2048;
static volatile uint32_t u100ticks = 0;
void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM14_Init(void);
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc);
#if BOARD_REV >= 14
enum
{
SHIFTER_G27 = 0,
SHIFTER_G25,
SHIFTER_DFP,
SHIFTER_AUTO = 254,
SHIFTER_NONE = 255
};
unsigned short shifter = SHIFTER_G27;
#define RDSR 5 /* http://pdf.datasheetcatalog.com/datasheets2/60/601078_1.pdf */
__ALIGN_BEGIN static const uint8_t tx_buffer[2] __ALIGN_END = { RDSR, 0 };
#endif
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC_Init();
MX_SPI1_Init();
MX_USB_DEVICE_Init();
MX_TIM14_Init();
HAL_FLASH_Unlock();
EE_Init();
EE_ReadVariable(VirtAddVarTab[0], &x_low_th);
EE_ReadVariable(VirtAddVarTab[1], &x_high_th);
EE_ReadVariable(VirtAddVarTab[2], &y_low_th);
EE_ReadVariable(VirtAddVarTab[3], &y_high_th);
#if BOARD_REV >= 14
EE_ReadVariable(VirtAddVarTab[4], &shifter);
#endif
HAL_FLASH_Lock();
report.gears = 0;
HAL_ADC_Start_DMA(&hadc, (uint32_t*)axis, 5);
while (1)
{
HAL_StatusTypeDef status;
#if BOARD_REV >= 14
if (SHIFTER_AUTO == shifter)
{
// attempt to detect G27 or DFP shifter
GPIOF->BSRR = ((uint32_t) GPIO_PIN_1 << 16) | GPIO_PIN_0;
status = HAL_SPI_TransmitReceive(&hspi1, tx_buffer, rx_buffer, sizeof(rx_buffer), 3000);
if (HAL_OK == status)
{
if (!rx_buffer[0] && rx_buffer[1])
{
// G27 shifter detected
shifter = SHIFTER_G27;
}
else
{
// G25
GPIOF->BSRR = ((uint32_t) GPIO_PIN_0 << 16) | GPIO_PIN_1;
HAL_TIM_Base_Start_IT(&htim14);
while (!u100ticks) ;
HAL_TIM_Base_Stop_IT(&htim14);
u100ticks = 0;
status = HAL_SPI_TransmitReceive(&hspi1, tx_buffer, rx_buffer, sizeof(rx_buffer), 3000);
if (HAL_OK == status)
{
if (!rx_buffer[0] && rx_buffer[1])
{
// G25 shifter detected
shifter = SHIFTER_G25;
}
}
}
}
}
#endif
HAL_GPIO_WritePin(SPI1_nCS_GPIO_Port, SPI1_nCS_Pin, GPIO_PIN_SET);
HAL_TIM_Base_Start_IT(&htim14);
while (!u100ticks) /* do nothing for 100 us */;
HAL_TIM_Base_Stop_IT(&htim14);
u100ticks = 0;
status = HAL_SPI_Receive(&hspi1, rx_buffer, sizeof(rx_buffer), 3000);
switch(status)
{
case HAL_OK:
report.buttons = 0x00;
report.d_pad = 0x00;
if ((rx_buffer[0] & 0xff) != 0xff) // if all bits of rx_buffer[0] is 1 assume shifter is disconnected
{
if (rx_buffer[0] & 4) report.buttons |= 1;
else report.buttons &= ~1;
if (rx_buffer[0] & 1) report.buttons |= (1 << 1);
else report.buttons &= ~(1 << 1);
if (rx_buffer[0] & 2) report.buttons |= (1 << 2);
else report.buttons &= ~(1 << 2);
if (rx_buffer[0] & 8) report.buttons |= (1 << 3);
else report.buttons &= ~(1 << 3);
if (rx_buffer[1] & 1) report.d_pad |= 1;
else report.d_pad &= ~1;
if (rx_buffer[1] & 2) report.d_pad |= (1 << 1);
else report.d_pad &= ~(1 << 1);
if (rx_buffer[1] & 4) report.d_pad |= (1 << 2);
else report.d_pad &= ~(1 << 2);
if (rx_buffer[1] & 8) report.d_pad |= (1 << 3);
else report.d_pad &= ~(1 << 3);
if (rx_buffer[1] & 32) report.buttons |= (1 << 4);
else report.buttons &= ~(1 << 4);
if (rx_buffer[1] & 128) report.buttons |= (1 << 5);
else report.buttons &= ~(1 << 5);
if (rx_buffer[1] & 64) report.buttons |= (1 << 6);
else report.buttons &= ~(1 << 6);
if (rx_buffer[1] & 16) report.buttons |= (1 << 7);
else report.buttons &= ~(1 << 7);
}
break;
case HAL_TIMEOUT:
case HAL_BUSY:
case HAL_ERROR:
Error_Handler();
default:
report.buttons = 0xff;
#if BOARD_REV >= 14
// shifter = SHIFTER_NONE;
#endif
break;
}
HAL_GPIO_WritePin(SPI1_nCS_GPIO_Port, SPI1_nCS_Pin, GPIO_PIN_RESET);
report.id = 0x01;
x_axis = ((X_AXIS << 2) + x_axis * 96) / 100;
y_axis = ((Y_AXIS << 2) + y_axis * 96) / 100;
if (y_axis < y_low_th) // stick towards player
{
if (x_axis < x_low_th)
{
if (!report.gears) report.gears = 2; // 2nd gear
}
else
{
if (x_axis > x_high_th)
{
if (!report.gears) report.gears = (rx_buffer[0] & 64) ? 64 : 32; // 6th gear or reverse
}
else
{
if (!report.gears) report.gears = 8; // 4th gear
}
}
}
else
{
if (y_axis > y_high_th) // stick opposite to player
{
if (x_axis < x_low_th)
{
if (!report.gears) report.gears = 1; // 1st gear
}
else
{
if (x_axis > x_high_th)
{
if (!report.gears) report.gears = 16; // 5th gear
}
else
{
if (!report.gears) report.gears = 4; // 3rd gear
}
}
}
else
{
report.gears = 0; // neutral
}
}
report.axis[0] = x_axis;
report.axis[1] = y_axis;
#if BOARD_REV >= 14
report.threshold[0] = x_low_th;
report.threshold[1] = x_high_th;
report.threshold[2] = y_low_th;
report.threshold[3] = y_high_th;
report.sh_type = shifter;
#endif
do
{
HAL_TIM_Base_Start_IT(&htim14);
while (!u100ticks) /* do nothing for 100 us */;
HAL_TIM_Base_Stop_IT(&htim14);
u100ticks = 0;
}
while (hUsbDeviceFS.pClassData
&& ((USBD_HID_HandleTypeDef *)hUsbDeviceFS.pClassData)->state != HID_IDLE);
USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&report, sizeof(report));
#if 0
uint8_t buf[64];
mute_xy = 0;
buf[0] = 0x02;
buf[1] = 0x01;
buf[3] = x_low_th & 0xff;
buf[4] = x_low_th >> 8;
buf[5] = x_high_th & 0xff;
buf[6] = x_high_th >> 8;
buf[7] = y_low_th & 0xff;
buf[8] = y_low_th >> 8;
buf[9] = y_high_th & 0xff;
buf[10] = y_high_th >> 8;
if (report2send == 2 || report2send == 3)
{
/* Unlock the Flash Program Erase controller */
HAL_FLASH_Unlock();
EE_WriteVariable(VirtAddVarTab[0], x_low_th);
EE_WriteVariable(VirtAddVarTab[1], x_high_th);
EE_WriteVariable(VirtAddVarTab[2], y_low_th);
EE_WriteVariable(VirtAddVarTab[3], y_high_th);
EE_WriteVariable(VirtAddVarTab[4], shifter);
/* Lock the Flash Program Erase controller */
HAL_FLASH_Lock();
HAL_Delay(10);
}
#endif
}
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInit;
#if BOARD_REV >= 14
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14|RCC_OSCILLATORTYPE_HSI48;
RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
#else
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14|RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
#endif
RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
RCC_OscInitStruct.HSI14CalibrationValue = RCC_HSI14CALIBRATION_DEFAULT;
#if BOARD_REV >= 14
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
#else
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
#endif
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1;
#if BOARD_REV >= 14
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI48;
#else
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
#endif
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
#if BOARD_REV >= 14
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_HSI48;
#else
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL;
#endif
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* TIM14 init function */
static void MX_TIM14_Init(void)
{
htim14.Instance = TIM14;
htim14.Init.Prescaler = 48;
htim14.Init.CounterMode = TIM_COUNTERMODE_UP;
htim14.Init.Period = 100; /* generate IRQ 48 MHz / 48 / 100 = 10,000 times per second */
htim14.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_Base_Init(&htim14) != HAL_OK)
{
Error_Handler();
}
}
/* ADC init function */
static void MX_ADC_Init(void)
{
ADC_ChannelConfTypeDef sConfig;
/**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc.Instance = ADC1;
hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
hadc.Init.Resolution = ADC_RESOLUTION_12B;
hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
hadc.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hadc.Init.LowPowerAutoWait = DISABLE;
hadc.Init.LowPowerAutoPowerOff = DISABLE;
hadc.Init.ContinuousConvMode = ENABLE;
hadc.Init.DiscontinuousConvMode = DISABLE;
hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc.Init.SamplingTimeCommon = ADC_SAMPLETIME_239CYCLES_5;
hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc.Init.DMAContinuousRequests = ENABLE;
hadc.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
if (HAL_ADC_Init(&hadc) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_1;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_2;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_3;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_4;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
}
// ADC DMA interrupt handler
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
report.axis[2] = ((T_AXIS << 1) + report.axis[2] * 98) / 100;
report.axis[3] = ((B_AXIS << 1) + report.axis[3] * 98) / 100;
report.axis[4] = ((C_AXIS << 1) + report.axis[4] * 98) / 100;
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM14)
{
u100ticks++;
}
}
static void MX_SPI1_Init(void)
{
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 7;
hspi1.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
__HAL_RCC_DMA1_CLK_ENABLE();
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
#if BOARD_REV >= 14
switch(shifter)
{
case SHIFTER_G27:
GPIOF->BSRR = ((uint32_t) GPIO_PIN_1 << 16) | GPIO_PIN_0;
break;
case SHIFTER_G25:
GPIOF->BSRR = ((uint32_t) GPIO_PIN_0 << 16) | GPIO_PIN_1;
break;
default:
/** Not implemented yet */
break;
}
GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
#endif
HAL_GPIO_WritePin(SPI1_nCS_GPIO_Port, SPI1_nCS_Pin, GPIO_PIN_RESET);
GPIO_InitStruct.Pin = SPI1_nCS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(SPI1_nCS_GPIO_Port, &GPIO_InitStruct);
}
/**
* @brief This function is executed in case of error occurrence.
* @param None
* @retval None
*/
void Error_Handler(void)
{
while(1)
{
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.