Reference Manual

 

Volume II

Advanced Programming Guide

 

 

Version 6.24

June 15th 2006

 

 

 

 

 

 


CLIPS Advanced Programming Guide

Version 6.24  June 15th 2006

 

CONTENTS

License Information....................................................................................................................... i

Preface............................................................................................................................................ iii

Acknowledgements...................................................................................................................... vii

Section 1 ‑ Introduction................................................................................................................ 1

1.1 Warning About Interfacing With CLIPS.............................................................................. 1

1.2 C++ Compatibility............................................................................................................... 2

1.3 Threads and Concurrency.................................................................................................... 2

1.4 Garbage Collection............................................................................................................... 3

Section 2 ‑ Installing and Tailoring CLIPS................................................................................. 9

2.1 Installing CLIPS.................................................................................................................. 9

2.1.1 Additional Considerations......................................................................................... 12

2.2 Tailoring CLIPS................................................................................................................. 13

Section 3 ‑ Integrating CLIPS with External Functions.......................................................... 19

3.1 Declaring User‑Defined External Functions...................................................................... 19

3.2 Passing Arguments from CLIPS to External Functions..................................................... 23

3.2.1 Determining the Number of Passed Arguments........................................................ 23

3.2.2 Passing Symbols, Strings, Instance Names, Floats, and Integers............................. 23

3.2.3 Passing Unknown Data Types.................................................................................. 25

3.2.4 Passing Multifield Values......................................................................................... 28

3.3 Returning Values To CLIPS From External Functions...................................................... 30

3.3.1 Returning Symbols, Strings, and Instance Names.................................................... 31

3.3.2 Returning Boolean Values........................................................................................ 32

3.3.3 Returning External Addresses and Instance Addresses............................................ 34

3.3.4 Returning Unknown Data Types.............................................................................. 34

3.3.5 Returning Multifield Values...................................................................................... 37

3.4 User‑Defined Function Example........................................................................................ 40

Section 4 ‑ Embedding CLIPS................................................................................................... 43

4.1 Environment Functions...................................................................................................... 43

4.1.1 AddClearFunction..................................................................................................... 43

4.1.2 AddPeriodicFunction................................................................................................ 44

4.1.3 AddResetFunction.................................................................................................... 44

4.1.4 BatchStar................................................................................................................... 45

4.1.5 Bload......................................................................................................................... 45

4.1.6 Bsave........................................................................................................................ 46

4.1.7 Build......................................................................................................................... 46

4.1.8 Clear.......................................................................................................................... 46

4.1.9 Eval........................................................................................................................... 47

4.1.10 FunctionCall............................................................................................................ 47

4.1.11 GetAutoFloatDividend............................................................................................ 48

4.1.12 GetDynamicConstraintChecking............................................................................. 48

4.1.13 GetSequenceOperatorRecognition.......................................................................... 48

4.1.14 GetStaticConstraintChecking.................................................................................. 49

4.1.15 InitializeEnvironment.............................................................................................. 49

4.1.16 Load........................................................................................................................ 49

4.1.17 RemoveClearFunction............................................................................................. 50

4.1.18 RemovePeriodicFunction........................................................................................ 50

4.1.19 RemoveResetFunction............................................................................................ 50

4.1.20 Reset....................................................................................................................... 51

4.1.21 Save........................................................................................................................ 51

4.1.22 SetAutoFloatDividend............................................................................................ 51

4.1.23 SetDynamicConstraintChecking............................................................................. 52

4.1.24 SetSequenceOperator Recognition.......................................................................... 52

4.1.25 SetStaticConstraintChecking................................................................................... 53

4.2 Debugging Functions......................................................................................................... 53

4.2.1 DribbleActive............................................................................................................ 53

4.2.2 DribbleOff................................................................................................................ 53

4.2.3 DribbleOn................................................................................................................. 54

4.2.4 GetWatchItem........................................................................................................... 54

4.2.5 Unwatch.................................................................................................................... 54

4.2.6 Watch........................................................................................................................ 55

4.3 Deftemplate Functions....................................................................................................... 55

4.3.1 DeftemplateModule................................................................................................... 55

4.3.2 DeftemplateSlotAllowedValues................................................................................ 55

4.3.3 DeftemplateSlotCardinality....................................................................................... 56

4.3.4 DeftemplateSlotDefaultP........................................................................................... 56

4.3.5 DeftemplateSlotDefaultValue.................................................................................... 57

4.3.6 DeftemplateSlotExistP.............................................................................................. 57

4.3.7 DeftemplateSlotMultiP.............................................................................................. 57

4.3.8 DeftemplateSlotNames.............................................................................................. 58

4.3.9 DeftemplateSlotRange............................................................................................... 58

4.3.10 DeftemplateSlotSingleP.......................................................................................... 58

4.3.11 DeftemplateSlotTypes............................................................................................. 59

4.3.12 FindDeftemplate...................................................................................................... 59

4.3.13 GetDeftemplateList................................................................................................. 60

4.3.14 GetDeftemplateName.............................................................................................. 60

4.3.15 GetDeftemplatePPForm.......................................................................................... 60

4.3.16 GetDeftemplateWatch............................................................................................. 61

4.3.17 GetNextDeftemplate................................................................................................ 61

4.3.18 IsDeftemplateDeletable........................................................................................... 61

4.3.19 ListDeftemplates..................................................................................................... 61

4.3.20 SetDeftemplateWatch.............................................................................................. 62

4.3.21 Undeftemplate......................................................................................................... 62

4.4 Fact Functions.................................................................................................................... 63

4.4.1 Assert........................................................................................................................ 63

4.4.2 AssertString.............................................................................................................. 63

4.4.3 AssignFactSlotDefaults............................................................................................ 64

4.4.4 CreateFact................................................................................................................. 65

4.4.5 DecrementFactCount................................................................................................. 67

4.4.6 FactDeftemplate........................................................................................................ 68

4.4.7 FactExistp................................................................................................................. 68

4.4.8 FactIndex.................................................................................................................. 68

4.4.9 Facts.......................................................................................................................... 68

4.4.10 FactSlotNames........................................................................................................ 69

4.4.11 GetFactDuplication................................................................................................. 69

4.4.12 GetFactList.............................................................................................................. 70

4.4.13 GetFactListChanged................................................................................................ 70

4.4.14 GetFactPPForm...................................................................................................... 71

4.4.15 GetFactSlot............................................................................................................. 71

4.4.16 GetNextFact............................................................................................................ 71

4.4.17 GetNextFactInTemplate.......................................................................................... 72

4.4.18 IncrementFactCount................................................................................................ 73

4.4.19 LoadFacts................................................................................................................ 73

4.4.20 LoadFactsFromString............................................................................................. 74

4.4.21 PPFact..................................................................................................................... 74

4.4.22 PutFactSlot.............................................................................................................. 74

4.4.23 Retract..................................................................................................................... 75

4.4.24 SaveFacts................................................................................................................ 75

4.4.25 SetFactDuplication.................................................................................................. 76

4.4.26 SetFactListChanged................................................................................................ 76

4.5 Deffacts Functions............................................................................................................. 77

4.5.1 DeffactsModule........................................................................................................ 77

4.5.2 FindDeffacts............................................................................................................. 77

4.5.3 GetDeffactsList......................................................................................................... 77

4.5.4 GetDeffactsName...................................................................................................... 78

4.5.5 GetDeffactsPPForm.................................................................................................. 78

4.5.6 GetNextDeffacts....................................................................................................... 78

4.5.7 IsDeffactsDeletable................................................................................................... 79

4.5.8 ListDeffacts............................................................................................................... 79

4.5.9 Undeffacts................................................................................................................. 79

4.6 Defrule Functions.............................................................................................................. 80

4.6.1 DefruleHasBreakpoint.............................................................................................. 80

4.6.2 DefruleModule.......................................................................................................... 80

4.6.3 FindDefrule............................................................................................................... 80

4.6.4 GetDefruleList.......................................................................................................... 80

4.6.5 GetDefruleName....................................................................................................... 81

4.6.6 GetDefrulePPForm................................................................................................... 81

4.6.7 GetDefruleWatchActivations.................................................................................... 81

4.6.8 GetDefruleWatchFirings........................................................................................... 82

4.6.9 GetIncrementalReset................................................................................................. 82

4.6.10 GetNextDefrule....................................................................................................... 82

4.6.11 IsDefruleDeletable.................................................................................................. 83

4.6.12 ListDefrules............................................................................................................ 83

4.6.13 Matches................................................................................................................... 83

4.6.14 Refresh.................................................................................................................... 84

4.6.15 RemoveBreak.......................................................................................................... 84

4.6.16 SetBreak.................................................................................................................. 84

4.6.17 SetDefruleWatchActivations................................................................................... 84

4.6.18 SetDefruleWatchFirings.......................................................................................... 85

4.6.19 SetIncrementalReset................................................................................................ 85

4.6.20 ShowBreaks............................................................................................................ 85

4.6.21 Undefrule................................................................................................................ 86

4.7 Agenda Functions.............................................................................................................. 86

4.7.1 AddRunFunction...................................................................................................... 86

4.7.2 Agenda...................................................................................................................... 87

4.7.3 ClearFocusStack....................................................................................................... 88

4.7.4 DeleteActivation........................................................................................................ 88

4.7.5 Focus........................................................................................................................ 88

4.7.6 GetActivationName................................................................................................... 88

4.7.7 GetActivationPPForm............................................................................................... 89

4.7.8 GetActivationSalience............................................................................................... 89

4.7.9 GetAgendaChanged.................................................................................................. 89

4.7.10 GetFocus................................................................................................................. 90

4.7.11 GetFocusStack........................................................................................................ 90

4.7.12 GetNextActivation.................................................................................................. 90

4.7.13 GetSalienceEvaluation............................................................................................. 91

4.7.14 GetStrategy............................................................................................................. 91

4.7.15 ListFocusStack........................................................................................................ 91

4.7.16 PopFocus................................................................................................................ 91

4.7.17 RefreshAgenda....................................................................................................... 92

4.7.18 RemoveRunFunction.............................................................................................. 92

4.7.19 ReorderAgenda....................................................................................................... 92

4.7.20 Run......................................................................................................................... 93

4.7.21 SetActivationSalience.............................................................................................. 93

4.7.22 SetAgendaChanged................................................................................................. 93

4.7.23 SetSalienceEvaluation............................................................................................. 94

4.7.24 SetStrategy.............................................................................................................. 94

4.8 Defglobal Functions........................................................................................................... 95

4.8.1 DefglobalModule...................................................................................................... 95

4.8.2 FindDefglobal........................................................................................................... 95

4.8.3 GetDefglobalList....................................................................................................... 95

4.8.4 GetDefglobalName................................................................................................... 96

4.8.5 GetDefglobalPPForm............................................................................................... 96

4.8.6 GetDefglobalValue................................................................................................... 96

4.8.7 GetDefglobalValueForm........................................................................................... 97

4.8.8 GetDefglobalWatch................................................................................................... 97

4.8.9 GetGlobalsChanged.................................................................................................. 97

4.8.10 GetNextDefglobal................................................................................................... 98

4.8.11 GetResetGlobals..................................................................................................... 98

4.8.12 IsDefglobalDeletable............................................................................................... 98

4.8.13 ListDefglobals......................................................................................................... 99

4.8.14 SetDefglobalValue.................................................................................................. 99

4.8.15 SetDefglobalWatch................................................................................................. 99

4.8.16 SetGlobalsChanged............................................................................................... 100

4.8.17 SetResetGlobals.................................................................................................... 100

4.8.18 ShowDefglobals................................................................................................... 100

4.8.19 Undefglobal.......................................................................................................... 101

4.9 Deffunction Functions..................................................................................................... 101

4.9.1 DeffunctionModule................................................................................................. 101

4.9.2 FindDeffunction...................................................................................................... 101

4.9.3 GetDeffunctionList................................................................................................. 102

4.9.4 GetDeffunctionName.............................................................................................. 102

4.9.5 GetDeffunctionPPForm.......................................................................................... 102

4.9.6 GetDeffunctionWatch............................................................................................. 103

4.9.7 GetNextDeffunction................................................................................................ 103

4.9.8 IsDeffunctionDeletable........................................................................................... 103

4.9.9 ListDeffunctions..................................................................................................... 104

4.9.10 SetDeffunctionWatch............................................................................................ 104

4.9.11 Undeffunction....................................................................................................... 104

4.10 Defgeneric Functions..................................................................................................... 105

4.10.1 DefgenericModule................................................................................................ 105

4.10.2 FindDefgeneric..................................................................................................... 105

4.10.3 GetDefgenericList................................................................................................. 105

4.10.4 GetDefgenericName.............................................................................................. 106

4.10.5 GetDefgenericPPForm.......................................................................................... 106

4.10.6 GetDefgenericWatch............................................................................................. 106

4.10.7 GetNextDefgeneric............................................................................................... 107

4.10.8 IsDefgenericDeletable........................................................................................... 107

4.10.9 ListDefgenerics..................................................................................................... 107

4.10.10 SetDefgenericWatch............................................................................................ 108

4.10.11 Undefgeneric....................................................................................................... 108

4.11 Defmethod Functions..................................................................................................... 108

4.11.1 GetDefmethodDescription.................................................................................... 108

4.11.2 GetDefmethodList................................................................................................. 109

4.11.3 GetDefmethodPPForm......................................................................................... 109

4.11.4 GetDefmethodWatch............................................................................................. 110

4.11.5 GetMethodRestrictions......................................................................................... 110

4.11.6 GetNextDefmethod............................................................................................... 110

4.11.7 IsDefmethodDeletable........................................................................................... 111

4.11.8 ListDefmethods..................................................................................................... 111

4.11.9 SetDefmethodWatch............................................................................................. 111

4.11.10 Undefmethod...................................................................................................... 112

4.12 Defclass Functions......................................................................................................... 112

4.12.1 BrowseClasses...................................................................................................... 112

4.12.2 ClassAbstractP...................................................................................................... 113

4.12.3 ClassReactiveP...................................................................................................... 113

4.12.4 ClassSlots............................................................................................................. 113

4.12.5 ClassSubclasses.................................................................................................... 114

4.12.6 ClassSuperclasses................................................................................................. 114

4.12.7 DefclassModule.................................................................................................... 115

4.12.8 DescribeClass....................................................................................................... 115

4.12.9 FindDefclass......................................................................................................... 115

4.12.10 GetClassDefaultsMode....................................................................................... 116

4.12.11 GetDefclassList................................................................................................... 116

4.12.12 GetDefclassName............................................................................................... 116

4.12.13 GetDefclassPPForm........................................................................................... 117

4.12.14 GetDefclassWatchInstances................................................................................ 117

4.12.15 GetDefclassWatchSlots....................................................................................... 117

4.12.16 GetNextDefclass................................................................................................. 117

4.12.17 IsDefclassDeletable............................................................................................. 118

4.12.18 ListDefclasses..................................................................................................... 118

4.12.19 SetClassDefaultsMode........................................................................................ 118

4.12.20 SetDefclassWatchInstances................................................................................. 119

4.12.21 SetDefclassWatchSlots....................................................................................... 119

4.12.22 SlotAllowedClasses............................................................................................ 119

4.12.23 SlotAllowedValues............................................................................................. 120

4.12.24 SlotCardinality.................................................................................................... 120

4.12.25 SlotDefaultValue................................................................................................. 121

4.12.26 SlotDirectAccessP.............................................................................................. 121

4.12.27 SlotExistP........................................................................................................... 121

4.12.28 SlotFacets............................................................................................................ 122

4.12.29 SlotInitableP........................................................................................................ 122

4.12.30 SlotPublicP......................................................................................................... 122

4.12.31 SlotRange............................................................................................................ 123

4.12.32 SlotSources......................................................................................................... 123

4.12.33 SlotTypes............................................................................................................ 123

4.12.34 SlotWritableP...................................................................................................... 124

4.12.35 SubclassP............................................................................................................ 124

4.12.36 SuperclassP......................................................................................................... 124

4.12.37 Undefclass.......................................................................................................... 125

4.13 Instance Functions......................................................................................................... 125

4.13.1 BinaryLoadInstances............................................................................................. 125

4.13.2 BinarySaveInstances............................................................................................. 125

4.13.3 CreateRawInstance................................................................................................ 126

4.13.4 DecrementInstanceCount...................................................................................... 126

4.13.5 DeleteInstance....................................................................................................... 126

4.13.6 DirectGetSlot........................................................................................................ 127

4.13.7 DirectPutSlot......................................................................................................... 127

4.13.8 FindInstance.......................................................................................................... 128

4.13.9 GetInstanceClass................................................................................................... 128

4.13.10 GetInstanceName................................................................................................ 129

4.13.11 GetInstancePPForm............................................................................................ 129

4.13.12 GetInstancesChanged.......................................................................................... 129

4.13.13 GetNextInstance.................................................................................................. 130

4.13.14 GetNextInstanceInClass...................................................................................... 130

4.13.15 GetNextInstanceInClassAndSubclasses............................................................. 130

4.13.16 IncrementInstanceCount...................................................................................... 131

4.13.17 Instances............................................................................................................. 133

4.13.18 LoadInstances..................................................................................................... 133

4.13.19 LoadInstancesFromString................................................................................... 134

4.13.20 MakeInstance...................................................................................................... 134

4.13.21 RestoreInstances................................................................................................. 134

4.13.22 RestoreInstancesFromString............................................................................... 135

4.13.23 SaveInstances...................................................................................................... 135

4.13.24 Send.................................................................................................................... 136

4.13.25 SetInstancesChanged.......................................................................................... 136

4.13.26 UnmakeInstance.................................................................................................. 137

4.13.27 ValidInstanceAddress......................................................................................... 137

4.14 Defmessage-handler Functions...................................................................................... 137

4.14.1 FindDefmessageHandler....................................................................................... 137

4.14.2 GetDefmessageHandlerList.................................................................................. 138

4.14.3 GetDefmessageHandlerName............................................................................... 138

4.14.4 GetDefmessageHandlerPPForm........................................................................... 139

4.14.5 GetDefmessageHandlerType................................................................................ 139

4.14.6 GetDefmessageHandlerWatch.............................................................................. 139

4.14.7 GetNextDefmessageHandler................................................................................. 140

4.14.8 IsDefmessageHandlerDeletable............................................................................ 140

4.14.9 ListDefmessageHandlers...................................................................................... 140

4.14.10 PreviewSend....................................................................................................... 141

4.14.11 SetDefmessageHandlerWatch............................................................................. 141

4.14.12 UndefmessageHandler........................................................................................ 142

4.15 Definstances Functions.................................................................................................. 142

4.15.1 DefinstancesModule............................................................................................. 142

4.15.2 FindDefinstances.................................................................................................. 142

4.15.3 GetDefinstancesList.............................................................................................. 143

4.15.4 GetDefinstancesName........................................................................................... 143

4.15.5 GetDefinstancesPPForm....................................................................................... 143

4.15.6 GetNextDefinstances............................................................................................ 144

4.15.7 IsDefinstancesDeletable........................................................................................ 144

4.15.8 ListDefinstances.................................................................................................... 144

4.15.9 Undefinstances...................................................................................................... 145

4.16 Defmodule Functions..................................................................................................... 145

4.16.1 FindDefmodule..................................................................................................... 145

4.16.2 GetCurrentModule................................................................................................ 145

4.16.3 GetDefmoduleList................................................................................................. 146

4.16.4 GetDefmoduleName............................................................................................. 146

4.16.5 GetDefmodulePPForm......................................................................................... 146

4.16.6 GetNextDefmodule............................................................................................... 147

4.16.7 ListDefmodules..................................................................................................... 147

4.16.8 SetCurrentModule................................................................................................. 147

4.17 Embedded Application Examples................................................................................... 148

4.17.1 User‑Defined Functions........................................................................................ 148

4.17.2 Manipulating Objects and Calling CLIPS Functions............................................ 150

Section 5 ‑ Creating a CLIPS Run‑time Program.................................................................. 153

5.1 Compiling the Constructs................................................................................................. 153

Section 6 ‑ Combining CLIPS with Languages Other Than C............................................ 157

6.1 Introduction...................................................................................................................... 157

6.2 Ada and FORTRAN Interface Package Function List..................................................... 157

6.3 Embedded CLIPS ‑ Using an External Main Program..................................................... 158

6.4 Asserting Facts into CLIPS............................................................................................. 159

6.5 Calling a Subroutine from CLIPS.................................................................................... 160

6.6 Passing Arguments from CLIPS to an External Function................................................ 161

6.7 String Conversion............................................................................................................ 164

6.8 Compiling and Linking.................................................................................................... 164

6.8.1 VMS Ada Version.................................................................................................. 164

6.8.2 VMS FORTRAN Version..................................................................................... 165

6.8.3 CLIPS Library........................................................................................................ 166

6.9 Building an Interface Package.......................................................................................... 166

Section 7 ‑ I/O Router System.................................................................................................. 167

7.1 Introduction...................................................................................................................... 167

7.2 Logical Names................................................................................................................. 167

7.3 Routers............................................................................................................................. 169

7.4 Router Priorities............................................................................................................... 170

7.5 Internal I/O Functions...................................................................................................... 171

7.5.1 ExitRouter............................................................................................................... 171

7.5.2 GetcRouter.............................................................................................................. 172

7.5.3 PrintRouter.............................................................................................................. 172

7.5.4 UngetcRouter.......................................................................................................... 172

7.6 Router Handling Functions.............................................................................................. 173

7.6.1 ActivateRouter........................................................................................................ 173

7.6.2 AddRouter.............................................................................................................. 174

7.6.3 DeactivateRouter..................................................................................................... 175

7.6.4 DeleteRouter........................................................................................................... 175

Section 8 ‑ Memory Management............................................................................................. 177

8.1 How CLIPS Uses Memory............................................................................................. 177

8.2 Standard Memory Functions............................................................................................ 178

8.2.1 GetConserveMemory.............................................................................................. 178

8.2.2 MemRequests......................................................................................................... 178

8.2.3 MemUsed............................................................................................................... 179

8.2.4 ReleaseMem............................................................................................................ 179

8.2.5 SetConserveMemory.............................................................................................. 180

8.2.6 SetOutOfMemoryFunction..................................................................................... 180

Section 9 ‑ Environments.......................................................................................................... 183

9.1 Creating, selecting, and destroying environments............................................................ 183

9.2 Environment Companion Functions................................................................................. 185

9.3 Standard Environment Functions..................................................................................... 186

9.3.1 AddEnvironmentCleanupFunction.......................................................................... 186

9.3.2 AllocateEnvironmentData....................................................................................... 187

9.3.3 CreateEnvironment.................................................................................................. 188

9.3.4 DeallocateEnvironmentData.................................................................................... 188

9.3.5 DestroyEnvironment............................................................................................... 189

9.3.6 GetCurrentEnvironment.......................................................................................... 189

9.3.7 GetEnvironmentByIndex........................................................................................ 189

9.3.8 GetEnvironmentData............................................................................................... 190

9.3.9 GetEnvironmentIndex............................................................................................. 190

9.3.10 SetCurrentEnvironment......................................................................................... 190

9.3.11 SetCurrentEnvironmentByIndex........................................................................... 190

9.4 Environment Aware User-Defined Functions.................................................................. 191

9.5 Allocating Environment Data........................................................................................... 192

9.6 Environment Globals....................................................................................................... 195

9.7 Other Considerations....................................................................................................... 195

Appendix A ‑ Language Integration Listings......................................................................... 197

A.1 Ada Interface Package for CLIPS................................................................................... 197

A.2 FORTRAN Interface Package for VAX VMS............................................................... 201

A.3 Function to Convert C Strings for VMS Ada or FORTRAN......................................... 205

Appendix B ‑ I/O Router Examples......................................................................................... 207

B.1 Dribble System................................................................................................................ 207

B.2 Better Dribble System..................................................................................................... 209

B.3 Batch System................................................................................................................... 210

B.4 Simple Window System.................................................................................................. 212

Appendix C ‑ Update Release Notes........................................................................................ 217

C.1 Version 6.24.................................................................................................................... 217

C.2 Version 6.23.................................................................................................................... 218

C.3 Version 6.22.................................................................................................................... 218

C.4 Version 6.21.................................................................................................................... 219

C.5 Version 6.2...................................................................................................................... 219

C.6 Version 6.1...................................................................................................................... 220

C.7 Version 6.05.................................................................................................................... 221

Index........................................................................................................................................... 223

 


License Information

 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ÒSoftwareÓ), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.                            

 

THE SOFTWARE IS PROVIDED ÒAS ISÓ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 

CLIPS is released as public domain software and as such you are under no obligation to pay for its use. However, if you derive commercial or monetary benefit from use of the software or just want to show support, please consider making a voluntary payment based on the worth of the software to you as compensation for the time and effort required to develop and maintain CLIPS. Payments can be made online at http://order.kagi.com/?JKT.

 


Preface

 

The History of CLIPS

 

The origins of the C Language Integrated Production System (CLIPS) date back to 1984 at NASAÕs Johnson Space Center. At this time, the Artificial Intelligence Section (now the Software Technology Branch) had developed over a dozen prototype expert systems applications using state‑of‑the‑art hardware and software. However, despite extensive demonstrations of the potential of expert systems, few of these applications were put into regular use. This failure to provide expert systems technology within NASAÕs operational computing constraints could largely be traced to the use of LISP as the base language for nearly all expert system software tools at that time. In particular, three problems hindered the use of LISP based expert system tools within NASA: the low availability of LISP on a wide variety of conventional computers, the high cost of state‑of‑the‑art LISP tools and hardware, and the poor integra­tion of LISP with other languages (making embedded applications difficult).

 

The Artificial Intelligence Section felt that the use of a conventional language, such as C, would eliminate most of these problems, and initially looked to the expert system tool vendors to provide an expert system tool written using a conventional language. Although a number of tool vendors started converting their tools to run in C, the cost of each tool was still very high, most were restricted to a small variety of computers, and the projected availability times were discouraging. To meet all of its needs in a timely and cost effective manner, it became evident that the Artificial Intelligence Section would have to develop its own C based expert system tool.

 

The prototype version of CLIPS was developed in the spring of 1985 in a little over two months. Particular attention was given to making the tool compatible with expert systems under development at that time by the Artificial Intelligence Section. Thus, the syntax of CLIPS was made to very closely resemble the syntax of a subset of the ART expert system tool developed by Inference Corporation. Although originally modeled from ART, CLIPS was developed entirely without assistance from Inference or access to the ART source code.

 

The original intent for CLIPS was to gain useful insight and knowledge about the construction of expert system tools and to lay the groundwork for the construction of a replacement tool for the commercial tools currently being used. Version 1.0 demonstrated the feasibility of the project concept. After additional development, it became apparent that CLIPS would be a low cost expert system tool ideal for the purposes of training. Another year of development and internal use went into CLIPS improving its portability, performance, functionality, and supporting documentation. Version 3.0 of CLIPS was made available to groups outside of NASA in the summer of 1986.

 

Further enhancements transformed CLIPS from a training tool into a tool useful for the development and delivery of expert systems as well. Versions 4.0 and 4.1 of CLIPS, released respectively in the summer and fall of 1987, featured greatly improved performance, external language integration, and delivery capabilities. Version 4.2 of CLIPS, released in the summer of 1988, was a complete rewrite of CLIPS for code modularity. Also included with this release were an architecture manual providing a detailed description of the CLIPS software architecture and a utility program for aiding in the verification and validation of rule‑based programs. Version 4.3 of CLIPS, released in the summer of 1989, added still more functionality.

 

Originally, the primary representation methodology in CLIPS was a forward chaining rule lan­guage based on the Rete algorithm (hence the Production System part of the CLIPS acronym). Version 5.0 of CLIPS, released in the spring of 1991, introduced two new programming paradigms: procedural programming (as found in languages such as C and Ada) and object‑oriented programming (as found in languages such as the Common Lisp Object System and Smalltalk). The object‑oriented programming language provided within CLIPS is called the CLIPS Object‑Oriented Language (COOL). Version 5.1 of CLIPS, released in the fall of 1991, was primarily a software maintenance upgrade required to support the newly developed and/or enhanced X Window, MS‑DOS, and Macintosh interfaces. Version 6.0 of CLIPS, released in 1993, provided support for the development of modular programs and tight integration between the object-oriented and rule-based programming capabilities of CLIPS. Version 6.1 of CLIPS, released in 1998,  removed support for older non-ANSI C Compilers and added support for C++ compilers. Commands to profile the time spent in constructs and user-defined functions were also added.

 

Because of its portability, extensibility, capabilities, and low‑cost, CLIPS has received widespread acceptance throughout the government, industry, and academia. The development of CLIPS has helped to improve the ability to deliver expert system technology throughout the public and private sectors for a wide range of applications and diverse computing environments. CLIPS is being used by numerous users throughout the public and private community including: all NASA sites and branches of the mil­itary, numerous federal bureaus, gov­ernment contractors, uni­versities, and many private compa­nies.

 

CLIPS is now maintained as public domain software by the main program authors who no longer work for NASA. See appendix A of the Basic Programming Guide for information on obtaining CLIPS and support.

 

CLIPS Version 6.2

 

Version 6.2 of CLIPS contains two major enhancements. First, CLIPS now provides a mechanism which allows an embedded application to create multiple environments into which programs can be loaded. Second, an improved Windows 2000/XP CLIPS interface is now available and the Macintosh CLIPS interface has been enhanced to support MacOS X. For a detailed listing of differences between the 6.x releases of CLIPS, refer to appendix B of the Basic Programming Guide and appendix C of the Advanced Programming Guide.


CLIPS Documentation

 

Two documents are provided with CLIPS.

 

¥     The CLIPS Reference Manual which is split into the following parts:

 

¥     Volume I - The Basic Programming Guide, which provides the definitive description of CLIPS syntax and examples of usage.

 

¥     Volume II - The Advanced Programming Guide, which provides detailed discus­sions of the more sophisticated features in CLIPS and is intended for people with extensive programming experience who are using CLIPS for advanced ap­plications.

 

¥     Volume III - The Interfaces Guide, which provides information on machine‑specific interfaces.

 

¥     The CLIPS UserÕs Guide which provides an introduction to CLIPS rule‑based and object‑oriented programming and is intended for people with little or no expert system experience.


Acknowledgements

As with any large project, CLIPS is the result of the efforts of numerous people. The primary contributors have been: Robert Savely, who conceived the project and provided overall direction and support;  Chris Culbert, who managed the project and wrote the original CLIPS Reference Manual; Gary Riley, who designed and developed the rule‑based portion of CLIPS, co‑authored the CLIPS Reference Manual, and developed the Macintosh interface for CLIPS; Brian Donnell, who designed and developed the CLIPS Object Oriented Language (COOL) and co‑authored the CLIPS Reference Manual; Bebe Ly, who developed the X Window interface for CLIPS; Chris Ortiz, who developed the original Windows 95 interface for CLIPS; Dr. Joseph Giarratano of the University of Houston-Clear Lake, who wrote the CLIPS UserÕs Guide; and Frank Lopez, who designed and developed CLIPS version 1.0 and wrote the CLIPS 1.0 User's Guide.

 

Many other individuals contributed to the design, development, review, and general support of CLIPS, including: Jack Aldridge, Carla Armstrong, Paul Baffes, Ann Baker, Stephen Baudendistel, Les Berke, Tom Blinn, Marlon Boarnet, Dan Bochsler, Bob Brown, Barry Cameron, Tim Cleghorn, Major Paul Condit, Major Steve Cross, Andy Cunningham, Dan Danley, Mark Engelberg, Kirt Fields, Ken Freeman, Kevin Greiner, Ervin Grice, Sharon Hecht, Patti Herrick, Mark Hoffman, Grace Hua, Gordon Johnson, Phillip Johnston, Sam Juliano, Ed Lineberry, Bowen Loftin, Linda Martin, Daniel McCoy, Terry McGregor, Becky McGuire, Scott Meadows, C. J. Melebeck, Paul Mitchell, Steve Mueller, Bill Paseman, Cynthia Rathjen, Eric Raymond, Reza Razavipour, Marsha Renals, Monica Rua, Tim Saito, Michael Sullivan, Gregg Swietek, Eric Taylor, James Villarreal, Lui Wang, Bob Way, Jim Wescott, Charlie Wheeler, and Wes White.


Section 1 ‑ Introduction

This manual is the Advanced Programming Guide for CLIPS. It describes the Application Programmer Interface (API) that allows users to integrate their programs with CLIPS and use some of the more sophisticated features of CLIPS. It is written with the assump­tion that the user has a complete understanding of the basic features of CLIPS and a back­ground in program­ming. Many sections will not be understandable without a working knowledge of C. Knowledge of other languages also may be helpful. The informa­tion presented here will require some experience to understand, but every effort has been made to implement capabilities in a simple manner consistent with the portability and efficiency goals of CLIPS.

 

Section 2 describes how to install and tailor CLIPS to meet specific needs. Section 3 of this document describes how to add user‑defined functions to a CLIPS expert system. Section 4 describes how to embed a CLIPS application in a C program. Section 5 describes how to create run‑time CLIPS programs. Section 6 dis­cusses integrating CLIPS with languages other than C. Section 7 details the input/ output (I/O) router system used by CLIPS and how the user can define his own I/O routers. Section 8 discusses CLIPS memory management. Section 9 discusses environments which allow multiple expert systems to be loaded and run concurrently.

 

Not all of the features documented here will be of use to all users. Users should pick those areas which are of specific use to them. It is advised that users complete the Basic Programming Guide before reading this manual.

1.1 Warning About Interfacing With CLIPS

CLIPS provides numerous methods for integrating with user‑defined code. As with any powerful capability, some care must be taken when using these features. By providing users with the ability to access internal information, we have also opened the door to the possibility of users corrupting or destroying data that CLIPS needs to work prop­erly. Users are advised to be careful when dealing with data structures or strings which are returned from calls to CLIPS functions. Generally, these data structures represent useful information to CLIPS and should not be modified or changed in any way except as described in this manual. A good rule of thumb is to duplicate in user-defined stor­age space every piece of information taken out of or passed into CLIPS. In particular, do not store pointers to strings returned by CLIPS as part of a permanent data structure. When CLIPS performs garbage collection on symbols and strings, the pointer reference to the string may be rendered invalid. To store a permanent reference to a string, allocate storage for a copy of the string and then copy the string returned by CLIPS to the copyÕs storage area.

1.2 C++ Compatibility

The CLIPS source code can now be compiled using either an ANSI C or C++ compiler. Minimally, non-ANSI C compilers must support full ANSI style function prototypes and the void data type in order to compile CLIPS. If you want to make CLIPS API calls from a C++ program, it is usually easier to do the integration by compiling the CLIPS source files as C++ files. This removes the need to make an extern "C" declaration in your C++ program for the CLIPS APIs. Some programming environments allow you to specify the whether a file should be compiled as C or C++ code based on the file extension. Other environments allow you to explicitly specify which compiler to use regardless of the extension (e.g. in gcc the option Ò-x c++Ó will compile .c files as C++ files). In some environments, the same compiler is used to compile both C and C++ programs and the compiler uses the file extension to determine whether the file should be compiled as a C or C++ program. In this situation, changing the .c extension of the CLIPS source files to .cpp usually allows the source to be compiled as a C++ program.

1.3 Threads and Concurrency

The CLIPS architecture is designed to support multiple expert systems running concurrently using a single CLIPS application engine. The environment API, described in section 9, is used to implement this functionality. In order to use multiple environments, CLIPS must be embedded within your program either by linking the CLIPS source code with your program or using a shared library such as a Dynamic Link Library (DLL). The standard command line version of CLIPS as well as the operating system specific development interfaces for Windows, Mac OS X, and X Windows provide access to a single environment. It is not possible to load and run multiple expert systems using these versions of CLIPS.

 

If multiple environments are created, a single thread of execution can be used to run each expert system. In this situation, one environment must finish executing before control can be passed to another environment. The user explicitly determines which environment should be executed by using the environment API to set the current environment. Once execution of an API call for that environment begins, the user must wait for completion of the API call before passing control to another environment.

 

Most likely, this type of execution control will be used when you need to make several expert systems available to a single end user, but donÕt want to go through the process of clearing the current expert system from a single environment, loading another expert system into it, and then resetting the environment. Instead, each expert system is loaded into its own environment, so to change expert systems it is only necessary to switch to the new environment and reset it.

 

A less likely scenario for this type of execution control is to simulate multiple expert systems running concurrently. In this scenario, each environment is allowed to execute a number of rules before control is switched to the next environment.

 

Instead of simulating multiple expert systems running concurrently, using the multi-threading capabilities native to the operating system on which CLIPS is running allows concurrent execution to occur efficiently and prevents one environment from blocking the execution of another. In this scenario, each environment uses a single thread of execution. Since each environment maintains its own set of data structures, it is safe to run a separate thread on each environment. This use of environments is most likely for a shared library where it is desirable to have a single CLIPS engine running that is shared by multiple applications.

   

Warning

 

Each environment can have at most one thread of execution. The CLIPS internal data structures can become corrupted if two CLIPS API calls are executing at the same time for a single environment. For example, you canÕt have one thread executing rules and another thread asserting facts for the same environment without some synchronization between the two threads.

1.4 Garbage Collection

Garbage collection is a process used by CLIPS to manage memory that most users do not need to understand to use CLIPS. In some cases, when users embed CLIPS within their applications, a knowledge of the garbage collection process is necessary to understand when values returned by CLIPS to an embedding program can be safely accessed.

 

As a CLIPS program executes, it allocates and deallocates numerous types of data structures. In many cases, some data structures cannot be immediately deallocated because either outstanding references to the data structure still exist or the need to deallocate the data structure is questionable. Data which has been marked for later deallocation is referred to as garbage. The process of deallocating this garbage is referred to as garbage collection. CLIPS only performs garbage collection when it can determine that it is safe to deallocate the data structures marked for deallocation.

 

The following example illustrates several important concepts:

 

CLIPS>

(defrule gc-example

   ?f <- (factoid ?g)

   =>

   (retract ?f)

   (printout t "The value is " ?g crlf))

CLIPS> (assert (factoid (gensym*)))

<Fact-0>

CLIPS> (run)

The value is gen1

CLIPS>

 

First the gc-example rule is entered at the command prompt. The RHS of this rule retracts the factoid fact bound on the LHS of the rule. It then prints out one of the field values contained in this fact. The next command creates a factoid fact that activates the rule. This fact contains the unique symbol gen1 returned by the gensym* function. The gen1 symbol is initially considered to be garbage when created since nothing refers to it, but when it is asserted as part of the factoid fact itÕs no longer considered as garbage and isnÕt subject to garbage collection.

 

When the run command is issued, the gc-example rule fires. The first action of the rule retracts the factoid fact bound on the LHS of the rule. The fact is now considered to be garbage. The symbol gen1 contained in the fact is also marked as being garbage since the fact contains the only reference to it. The next action in the rule prints the value from the factoid fact bound to the variable ?g. Since CLIPS directly retrieves this value from the fact, if the fact and symbols associated with it had been immediately deallocated when the retract command was executed, these values would not be available when the printout command is executed.

 

Since garbage created by the RHS actions may be accessed by other RHS actions, CLIPS does not initiate garbage collection for garbage created by RHS actions until the rule has finished firing. In this example, once the gc-example rule has finished firing, since there are no outstanding references to the factoid fact or the gen1 symbol the data structures associated with these can be deallocated.

 

The garbage collection behavior would be changed by adding an assert command to the rule RHS:

 

(defrule gc-example

   ?f <- (factoid ?g)

   =>

   (retract ?f)

   (printout t "The value is " ?g crlf)

   (assert (info ?g)))

 

In this case, the factoid fact and the gen1 symbol would be marked as garbage as a result of the retract command, but the assertion of the info fact with the gen1 symbol removes the symbol from consideration for garbage collection. Once the rule finishes executing, however, the other data structures associated with the fact are still subject to garbage collection.

 

This next example is a simpler example of garbage collection that will be used to compare and contrast garbage collection triggered by the command prompt to that triggered by an embedding application.

 

CLIPS> (gensym*)

gen2

CLIPS>

 

The gensym* function entered at the command prompt returns the unique symbol gen2. This newly created symbol is assumed to be garbage until an outstanding reference to the symbol is established. In this case, once the return value has been displayed and control returned to the command prompt, garbage collection is initiated as part of the command prompt loop and the data structures associated with the symbol can be deallocated,

 

The following main routine is an equivalent embedded program that makes a call to the gensym* function.

 

main()
  {

   DATA_OBJECT rtn;


   InitializeEnvironment();
   

   FunctionCall("gensym*",NULL,&rtn);

  }

 

The key difference between this example and the command loop example is that the gen2 symbol returned to the command loop can be garbage collected after it is printed, but the value returned to the embedding main program can not be safely garbage collected until the embedding program has finished using it.

 

If the values returned to an embedding program are never garbage collected, continuous execution would result in a program eventually running out of memory. CLIPS addresses this issue by automatically invoking garbage collection for the following embedded functions: Assert, AssertString, Clear, DeleteInstance, DirectPutSlot, FunctionCall, MakeInstance, Reset, Send, SetDefglobalValue, Undefclass, Undeffacts, Undeffunction, Undefgeneric, Undefglobal, Undefinstances, Undefmethod, Undefrule, Undeftemplate, and UnmakeInstance. Calling one of these functions will not garbage collect any data returned from that call, but it could garbage collect data returned from prior calls.

 

The following main routine is an example of how garbage collection affects whether you can safely access data returned by CLIPS.

 

main()
  {

   DATA_OBJECT rtn;

   char *str1, *str2;


   InitializeEnvironment();
   

   FunctionCall("gensym*",NULL,&rtn);

   str1 = DOToString(rtn);

 

   /* Safe to refer to str1 here. */  

 

   FunctionCall("gensym*",NULL,&rtn);

   str2 = DOToString(rtn);

 

   /* Not safe to refer to str1 here. */

  }

 

The first call to FunctionCall could trigger garbage collection, but since no data has been returned yet to the embedding program this does not cause any problems. The next call to DOToString stores the string value in the DATA_OBJECT rtn in the str1 variable. At this point, str1 can be safely referenced.

 

The second call to FunctionCall could also trigger garbage collection. In this case, however, the value returned by the prior call to FunctionCall could be garbage collected as a result. Therefore it is not safe to reference the value stored in str1 after this point. This is a problem if, for example, you want to compare the value of str1 to str2.

 

There are two ways to work around this problem. The first is to create your own copies of str1 and str2. This is somewhat inconvenient since you have to determine the size of the strings, allocate space for them, copy them, and then delete them once theyÕre no longer needed. The second way is more convenient. CLIPS provides two functions, IncrementGCLocks and DecrementGCLocks, which allow you to temporarily disable garbage collection. Each call to IncrementGCLocks places a lock on the garbage collector. Each call to DecrementGCLocks removes a lock from the garbage collector. If the garbage collector has one or more locks place on it, it is disabled and garbage collection does not occur.

 

void     IncrementGCLocks();
void     DecrementGCLocks();

 

The use of these functions is demonstrated in the following revised main routine:

 

main()
  {

   DATA_OBJECT rtn;

   char *str1, *str2;


   InitializeEnvironment();
   

   IncrementGCLocks();

 

   FunctionCall("gensym*",NULL,&rtn);

   str1 = DOToString(rtn);

 

   /* Safe to refer to str1 here. */  

 

   FunctionCall("gensym*",NULL,&rtn);

   str2 = DOToString(rtn);

 

   /* Safe to refer to str1 here. */

 

   DecrementGCLocks();

  }

 

In this case, the second call to FunctionCall canÕt garbage collect the string referenced by str1, so it is safe to refer to this string after the call. The same effect could also be achieved by moving the IncrementGCLocks call after the first call to FunctionCall.

 

The garbage collector should not be disabled indiscriminately as shown in the following example:

 

main()
  {

   InitializeEnvironment();
   

   IncrementGCLocks();

  

   Load("mab.clp");

   Reset();

   Run(-1);

 

   DecrementGCLocks();

  }

 

First, while calling Reset could trigger garbage collection on values returned to the embedding program, in this case there are no such values. Second, while Load and Run wonÕt trigger garbage collection on values returned to the embedding program, they do trigger garbage collection to remove garbage generated during their execution. Garbage collection should only be disabled for brief periods of time. The primary execution of your program should occur with garbage collection enabled.

 

It is only necessary to consider the effects of garbage collection when an embedding program is retrieving data from CLIPS. When calls to a user function by CLIPS are made (such as to a user‑defined function), the possible consequences of garbage collection do not have to be considered. In this case, garbage collection will not be triggered for any data retrieved by the user function until after the user function has exited.

 


Section 2 ‑ Installing and Tailoring CLIPS

This section describes how to install and tailor CLIPS to meet specific needs.

2.1 Installing CLIPS

CLIPS executables for DOS, Windows 95/98/NT/XP, and MacOS are available for download from the internet. See Appendix A in the Basic Programming Guide for details. To tailor CLIPS or to install it on another machine, the user must port the source code and create a new executable version.

 

Testing of CLIPS 6.23 included the following hardware/software environments:

 

¥     Dell Dimension 8250 running Windows XP Professional with DJGPP 3.21 (for creating 32-bit protected mode DOS applications), Microsoft Visual C++ 6.0, Borland C++ 5.0, and CodeWarrior 9.4.

 

¥     Apple iBook running MacOS X 10.3.7 using CodeWarrior 9.4 and Xcode 1.2.

 

CLIPS was designed specifically for portability and has been installed on numerous other computers without making modifications to the source code. It should run on any system which supports an ANSI C or C++ compiler. Some compilers have extended syntax to support a particular platform which will add additional reserved words to the C language. In the event that this extended syntax conflicts with the CLIPS source, the user will have to edit the code. This usually only involves a global search-and-replace of the particular reserved word. The following steps de­scribe how to create a new executable version of CLIPS:

 

1)   Load the source code onto the user's system

      The following C source files are necessary to set up the basic CLIPS system:

 

agenda.h

dffnxpsr.h

globlpsr.h

prccode.h

analysis.h

dfinsbin.h

immthpsr.h

prcdrfun.h

argacces.h

dfinscmp.h

incrrset.h

prcdrpsr.h

bload.h

drive.h

inherpsr.h

prdctfun.h

bmathfun.h

ed.h

inscom.h

prntutil.h

bsave.h

emathfun.h

insfile.h

proflfun.h

classcom.h

engine.h

insfun.h

reorder.h

classexm.h

envrnmnt.h

insmngr.h

reteutil.h

classfun.h

evaluatn.h

insmoddp.h

retract.h

classinf.h

expressn.h

insmult.h

router.h

classini.h

exprnbin.h

inspsr.h

rulebin.h

classpsr.h

exprnops.h

insquery.h

rulebld.h

clips.h

exprnpsr.h

insqypsr.h

rulebsc.h

clsltpsr.h

extnfunc.h

iofun.h

rulecmp.h

cmptblty.h

factbin.h

lgcldpnd.h

rulecom.h

commline.h

factbld.h

match.h

rulecstr.h

conscomp.h

factcmp.h

memalloc.h

ruledef.h

constant.h

factcom.h

miscfun.h

ruledlt.h

constrct.h

factfun.h

modulbin.h

rulelhs.h

constrnt.h

factgen.h

modulbsc.h

rulepsr.h

crstrtgy.h

facthsh.h

modulcmp.h

scanner.h

cstrcbin.h

factlhs.h

moduldef.h

setup.h

cstrccmp.h

factmch.h

modulpsr.h

sortfun.h

cstrccom.h

factmngr.h

modulutl.h

strngfun.h

cstrcpsr.h

factqpsr.h

msgcom.h

strngrtr.h

cstrnbin.h

factqury.h

msgfun.h

symblbin.h

cstrnchk.h

factprt.h

msgpass.h

symblcmp.h

cstrncmp.h

factrete.h

msgpsr.h

symbol.h

cstrnops.h

factrhs.h

multifld.h

sysdep.h

cstrnpsr.h

filecom.h

multifun.h

textpro.h

cstrnutl.h

filertr.h

network.h

tmpltbin.h

default.h

generate.h

objbin.h

tmpltbsc.h

defins.h

genrcbin.h

objcmp.h

tmpltcmp.h

developr.h

genrccmp.h

object.h

tmpltdef.h

dffctbin.h

genrccom.h

objrtbin.h

tmpltfun.h

dffctbsc.h

genrcexe.h

objrtbld.h

tmpltlhs.h

dffctcmp.h

genrcfun.h

objrtcmp.h

tmpltpsr.h

dffctdef.h

genrcpsr.h

objrtfnx.h

tmpltrhs.h

dffctpsr.h

globlbin.h

objrtgen.h

tmpltutl.h

dffnxbin.h

globlbsc.h

objrtmch.h

userdata.h

dffnxcmp.h

globlcmp.h

parsefun.h

utility.h

dffnxexe.h

globlcom.h

pattern.h

watch.h

dffnxfun.h

globldef.h

pprint.h

 

 

agenda.c

edbasic.c

globlpsr.c

prcdrpsr.c

analysis.c

edmain.c

immthpsr.c

prdctfun.c

argacces.c

edmisc.c

incrrset.c

prntutil.c

bload.c

edstruct.c

inherpsr.c

proflfun.c

bmathfun.c

edterm.c

inscom.c

reorder.c

bsave.c

emathfun.c

insfile.c

reteutil.c

classcom.c

engine.c

insfun.c

retract.c

classexm.c

envrnmnt.c

insmngr.c

router.c

classfun.c

evaluatn.c

insmoddp.c

rulebin.c

classinf.c

expressn.c

insmult.c

rulebld.c

classini.c

exprnbin.c

inspsr.c

rulebsc.c

classpsr.c

exprnops.c

insquery.c

rulecmp.c

clsltpsr.c

exprnpsr.c

insqypsr.c

rulecom.c

commline.c

extnfunc.c

iofun.c

rulecstr.c

conscomp.c

factbin.c

lgcldpnd.c

ruledef.c

constrct.c

factbld.c

main.c

ruledlt.c

constrnt.c

factcmp.c

memalloc.c

rulelhs.c

crstrtgy.c

factcom.c

miscfun.c

rulepsr.c

cstrcbin.c

factfun.c

modulbin.c

scanner.c

cstrccom.c

factgen.c

modulbsc.c

sortfun.c

cstrcpsr.c

facthsh.c

modulcmp.c

strngfun.c

cstrnbin.c

factlhs.c

moduldef.c

strngrtr.c

cstrnchk.c

factmch.c

modulpsr.c

symblbin.c

cstrncmp.c

factmngr.c

modulutl.c

symblcmp.c

cstrnops.c

factprt.c

msgcom.c

symbol.c

cstrnpsr.c

factqpsr.c

msgfun.c

sysdep.c

cstrnutl.c

factqury.c

msgpass.c

textpro.c

default.c

factrete.c

msgpsr.c

tmpltbin.c

defins.c

factrhs.c

multifld.c

tmpltbsc.c

developr.c

filecom.c

multifun.c

tmpltcmp.c

dffctbin.c

filertr.c

objbin.c

tmpltdef.c

dffctbsc.c

generate.c

objcmp.c

tmpltfun.c

dffctcmp.c

genrcbin.c

objrtbin.c

tmpltlhs.c

dffctdef.c

genrccmp.c

objrtbld.c

tmpltpsr.c

dffctpsr.c

genrccom.c

objrtcmp.c

tmpltrhs.c

dffnxbin.c

genrcexe.c

objrtfnx.c

tmpltutl.c

dffnxcmp.c

genrcfun.c

objrtgen.c

userdata.c

dffnxexe.c

genrcpsr.c

objrtmch.c

userfunctions.c

dffnxfun.c

globlbin.c

parsefun.c

utility.c

dffnxpsr.c

globlbsc.c

pattern.c

watch.c

dfinsbin.c

globlcmp.c

pprint.c

 

dfinscmp.c

globlcom.c

prccode.c

 

drive.c

globldef.c

prcdrfun.c

 

 

      Additional files must also be included if one of the machine specific user interfaces is to be set  up. See the Utilities and Interfaces Guide for details on compiling the machine specific interfaces.

 

2)   Modify all include statements (if necessary)

      All of the Ò.cÓ files and most of the Ò.hÓ files have #include statements. These #include statements may have to be changed to either match the way the compiler searches for include files or to include a different ".h" file.

 

3)   Tailor CLIPS environment and/or features

      Edit the setup.h file and set any special options. CLIPS uses compiler directives to allow machine‑dependent features. The first flag in the setup.h file tells CLIPS on what kind of machine the code is being compiled. The default setting for this flag is GENERIC, which will create a ver­sion of CLIPS that will run on any computer. The user may set this flag for the userÕs type of system. If the system type is unknown, the first flag should be set to GENERIC. If you change the system type to anything other than GENERIC, make sure that the version number of your compiler is greater than or equal to the version number listed in the setup.h file (as earlier versions of a compiler may not support some system dependent features). Other flags in the setup.h file also allow a user to tailor the features in CLIPS to specific needs. For more information on using the flags, see section 2.2

 

4)   Compile all of the ".c" files to object code

      Use the standard compiler syntax for the user's machine. The ".h" files are include files used by the other files and do not need to be com­piled. Some options may have to be set, depending on the compiler.

 

      If user‑de­fined functions are needed, compile the source code for those functions as well and modify the UserFunctions or EnvUserFunctions definition in userfunctions.c to reflect the user's functions (see section 3 for more on user‑defined functions).

 

5)   Create the interactive CLIPS executable element

      To create the interactive CLIPS executable, link together all of the object files. This executable will provide the interactive interface defined in section 2.1 of the Basic Programming Guide.

2.1.1 Additional Considerations

Although compiling CLIPS should not be difficult even for inexperienced C program­mers, some non-obvious problems can occur. One type of problem is linking with inappropriate system libraries. Normally, default libraries are specified through the envi­ronment; i.e., not specified as a part of the compile/link process. On occasion, the default system libraries are inappropriate for use with CLIPS. For example, when using a compiler which supports different memory models, be sure to link with the system libraries that match the memory model under which the CLIPS code was compiled. The same can be said for floating‑point models. Some computers provide multiple ways of storing floating‑point numbers (typically differing in accuracy or speed of proc­essing). Be sure to link with system libraries that use the same storage formats with which the CLIPS code was compiled. Some additional considerations for compiling CLIPS with specific compilers and/or operating systems are described following.

 

DJGPP v3.21

The CLIPS 32 bit DOS executable for 386 or higher PCs was created using the free DJGPP C compiler. This executable can access memory beyond the DOS 640K limit, but your environment must have DMPI services available in order to run this executable. If you are running Windows or OS/2, DPMI services are provided for you. Information on this compiler is available at the WWW URL http://www.delorie.com/djgpp/. A free DPMI server is also available at this location.

 

The built-in MicroEMACS editor will not work with this compiler, so the EMACS_EDITOR compiler directive in setup.h should be set to 0. With the compiler installed, the following command will compile CLIPS

 

gcc -o clipsdos *.c -lm

 

UNIX

If the EX_MATH compiler directive is enabled, then the -lm option must be used when compiling CLIPS with the gcc command. Similary, if the EMACS_EDITOR compiler directive is enabled, the -ltermcap option must be used when compiling CLIPS. If all of the CLIPS source code is contained in the same directory and the compiler directives are set to their default values in the setup.h file, then the following command line will compile CLIPS

 

gcc -o clips *.c -lm –ltermcap

 

GCC

If the –O optimization option is specified, then the -fno-strict-aliasing option should also be specified. The –x c++ option can be used to force compilation of CLIPS as a C++ program. If used the -lstdc++ option should also be used to link with C++ libraries. The following command line will compile CLIPS as a C++ program

 

gcc -o clips -x c++ *.c -lstdc++ -ltermcap

2.2 Tailoring CLIPS

CLIPS makes use of compiler directives or setup flags to allow easier porting and recompiling of CLIPS. Compiler directives allow the incorporation of system‑dependent features into CLIPS and also make it easier to tailor CLIPS to specific applications. All avail­able compiler options are controlled by a set of flags defined in the setup.h file.

 

The first flag in setup.h indicates on what type of compiler/machine CLIPS is to run. The source code is sent out with the flag for GENERIC CLIPS turned on. When com­piled in this mode, all system‑dependent features of CLIPS are excluded and the program should run on any system. A number of other flags are available in this file, indi­cating the types of compilers/machines on which CLIPS has been compiled previ­ously. If the user's implementation matches one of the available flags, set that flag to 1 and turn the GENERIC flag off (set it to 0). The code for most of the features controlled by the compil­er/machine‑type flag is in the sysdep.c file.

 

Many other flags are provided in setup.h. Each flag is described below.

 

ALLOW_ENVIRONMENT_GLOBALS

                                             If this flag is on, then global variables are used to track the current environment and environment indices. If this flag is off, then no global variables are used by CLIPS. If this is disabled, then ENVIRONMENT_API_ONLY will be automatically enabled and EMACS_EDITOR will be automatically disabled. This is on in the standard CLIPS executable.

BASIC_IO                          This flag controls access to the basic I/O functions in CLIPS. These functions are printout, read, open, and close. If this flag is off, these functions are not available. This would be used to save some memory in systems which used custom I/O routines. This is on in the standard CLIPS executable.

BLOAD                               This flag controls access to the binary load command (bload). This would be used to save some memory in systems which require binary load but not save capability. This is off in the standard CLIPS executable.

BLOAD_AND_BSAVE     

                                             This flag controls access to the binary load and save commands. This would be used to save some memory in systems which require neither binary load nor binary save capability. This is on in the standard CLIPS executable.

BLOAD_INSTANCES

;                                             This flag controls the ability to load instances in binary format from a file via the bload‑instances command (see section 13.11.4.7 of the Basic Programming Guide). This is on in the standard CLIPS executable. Turning this flag off can save some memory.

BLOAD_ONLY                 This flag controls access to the binary and ASCII load commands (bload and load). This would be used to save some memory in systems which require binary load capability only. This flag is off in the standard CLIPS executable.

BLOCK_MEMORY          This option controls memory allocation. If the flag is on, memory is allocated from the operating system in large blocks. This can improve performance if the system memory allocation routines are extremely inefficient or place arbitrary restrictions on the number of memory allocations that can be made. This flag is off in the stan­dard CLIPS executable.

BSAVE_INSTANCES

;                                             This flag controls the ability to save instances in binary format to a file via the bsave‑instances command (see section 13.11.4.4 of the Basic Programming Guide). This is on in the standard CLIPS executable. Turning this flag off can save some memory.

CONSTRUCT_COMPILER        

                                             This flag controls the construct compiler functions. If it is turned on, constructs may be compiled to C code for use in a run‑time module (see section 5). This is off in the standard CLIPS executable.

DEBUGGING_FUNCTIONS       

                                             This flag controls access to commands such as agenda, facts, ppdefrule, ppdeffacts, etc. This would be used to save some memory in BLOAD_ONLY or RUN_TIME systems. This flag is on in the standard CLIPS executable.

DEFFACTS_CONSTRUCT         

                                             This flag controls the use of deffacts. If it is off, deffacts are not allowed which can save some memory and performance during resets. This is on in the standard CLIPS executable. If this flag is off, the (initial-fact) fact is still created during a reset if the DEFTEMPLATE_CONSTRUCT flag is on.

DEFFUNCTION_CONSTRUCT

;                                             This flag controls the use of deffunction. If it is off, deffunction is not allowed which can save some memory. This is on in the standard CLIPS executable.

DEFGENERIC_CONSTRUCT

;                                             This flag controls the use of defgeneric and defmethod. If it is off, defgeneric and defmethod are not allowed which can save some memory. This is on in the standard CLIPS executable.

DEFGLOBAL_CONSTRUCT

;                                             This flag controls the use of defglobal. If it is off, defglobal is not allowed which can save some memory. This is on in the standard CLIPS executable.

DEFINSTANCES_CONSTRUCT

                                             This flag controls the use of definstances (see section 9.6.1.1 of the Basic Programming Guide). If it is off, definstances are not allowed which can save some memory and performance during resets. This is on in the standard CLIPS executable. If this flag is off, the [initial-object] instance is still created during a reset if the INSTANCE_PATTERN_MATCHING flag is on.

DEFMODULE_CONSTRUCT

;                                             This flag controls the use of the defmodule construct. If it is off, then new defmodules cannot be defined (however the MAIN module will exist). This is on in the standard CLIPS executable.

DEFRULE_CONSTRUCT

                                             This flag controls the use of the defrule construct. If it is off, the defrule construct is not recognized by CLIPS. This is on in the standard CLIPS executable.

DEFTEMPLATE_CONSTRUCT

;                                             This flag controls the use of deftemplate. If it is off, deftemplate is not allowed which can save some memory. This is on in the standard CLIPS executable.

EMACS_EDITOR             This flag controls the integrated MicroEMACS editor. If it is turned on, the editor will be available. If it is turned off, the editor will not be available but about 40K of memory will be saved. NOTE: The editor is machine dependent and will not run on all machines. See the setup.h file for a description of which machines can support the editor. This is on in the standard CLIPS executable.

ENVIRONMENT_API_ONLY

                                             If this flag is on, then the standard embedded functions require their first argument to be a generic pointer to an environment. This is off in the standard CLIPS executable.

EX_MATH                         This flag indicates whether the extend­ed math package should be included in the compilation. If this flag is turned off (set to 0), the final executable will be about 25‑30K smaller, a consideration for machines with limited memory. This is on in the standard CLIPS executable.

EXT_IO                              This flag controls access to the extended I/O functions in CLIPS. These functions are format and readline. If this flag is off, these functions are not available. This would be used to save some memory in systems which used custom I/O rou­tines or only the basic I/O routines. This is on in the stan­dard CLIPS executable.

FACT_SET_QUERIES

;                                             This flag determines if the fact‑set query functions are available. These functions are any‑factp, do‑for‑fact, do‑for‑all‑facts, delayed‑do‑for‑all‑facts,, find‑fact, and find‑all‑facts,. This is on in the standard CLIPS executable. Turning this flag off can save some memory.

HELP_FUNCTIONS         If this flag is on, the on‑line help system will be available from the CLIPS top‑level interface. When this is turned on, the HELP_DEFAULT flag should be set to point to the full path name for the CLIPS help file. This is on in the standard CLIPS executable.

INSTANCE_SET_QUERIES

;                                             This flag determines if the instance‑set query functions are available. These functions are any‑instancep, do‑for‑instance, do‑for‑all‑instances, delayed‑do‑for‑all‑instances,, find‑instance, and find‑all‑instances,. This is on in the standard CLIPS executable. Turning this flag off can save some memory.

MULTIFIELD_FUNCTIONS      

                                             This flag controls access to the multifield manipulation func­tions in CLIPS. These functions are subseq$, delete$, insert$, replace$, explode$, implode$, nth$, member$, first$, rest$, progn$, and subsetp. The function create$ is always available regardless of the setting of this flag. This would be used to save some memory in systems which performed limited or no operations with multifield values. This flag is on in the standard CLIPS executable.

OBJECT_SYSTEM

;                                             This flag controls the use of defclass, definstances, and defmessage-handler. If it is off, these constructs are not allowed which can save some memory. If this flag is on, the MULTIFIELD_FUNCTIONS flag should also be on if you want to be able to manipulate multifield slots. This is on in the standard CLIPS executable.

PROFILING_FUNCTIONS         

                                             This flag controls access to the profiling func­tions in CLIPS. These functions are get-profile-percent-threshold, profile, profile-info, profile-reset, and set-profile-percent-threshold. This flag is on in the standard CLIPS executable.

RUN_TIME                        This flag will create a run‑time version of CLIPS for use with compiled constructs. It should be turned on only after the constructs-to-c function has been used to generate the C code representation of the constructs, but before compiling the constructs C code. When used, about 90K of memory can be saved from the basic CLIPS executable. See section 5 for a de­scription of how to use this. This is off in the standard CLIPS executable.

STRING_FUNCTIONS    

                                             This flag controls access to the string manipulation functions in CLIPS. These functions are str-cat, sym-cat, str‑length, str‑compare, upcase, lowcase, sub‑string, str‑index, eval, and build. This would be used to save some memory in systems which perform limited or no operations with strings. This flag is on in the standard CLIPS executable.

TEXTPRO_FUNCTIONS
This flag controls the CLIPS text-processing functions. It must be turned on to use the fetch, toss, and print-region functions in a user‑defined help system. It also must be turned on to use the on‑line help system. This is on in the standard CLIPS executable.

WINDOW_INTERFACE

                                             This flag indicates that a windowed interface is being used. In some cases, this may include CLIPS console applications (for example Win32 console applications as opposed to a DOS application). Currently, the help system uses this flag to determine whether it should handle more processing by itself or allow the interface to take care of more processing. This is off in the standard CLIPS executable.

 


Section 3 ‑ Integrating CLIPS with External Functions

One of the most important features of CLIPS is an ability to integrate CLIPS with external functions or applications. This section discusses how to add external functions to CLIPS and how to pass arguments to them and return values from them. A user can define external functions for use by CLIPS at any place a function can normally be called. In fact, the vast majority of system defined functions and commands provided by CLIPS are integrated with CLIPS in the exact same manner described in this section. The examples shown in this section are in C, but section 6 discusses how other languages can be com­bined with CLIPS. Prototypes for the functions listed in this section can be included by using the clips.h header file.

3.1 Declaring User‑Defined External Functions

All external func­tions must be described to CLIPS so they can be properly accessed by CLIPS programs. User‑defined functions are described to CLIPS by modifying the function UserFunctions or EnvUserFunctions (if the function is environment aware as described in section 9.4) which reside in the CLIPS userfunctions.c file. Within UserFunctions, a call should be made to the DefineFunction rou­tine for every function which is to be integrated with CLIPS. The user's source code then can be compiled and linked with CLIPS. Alternately, the user can call DefineFunction from their own initialization code—the only restrictions is that it must be called after CLIPS has been initialized and before the user-defined function is referenced.


int      DefineFunction(functionName,functionType,

                        functionPointer,actualFunctionName);

char    *functionName, functionType, *actualFunctionName;

int    (*functionPointer)();

An example UserFunctions declaration follows:

 

void UserFunctions()
  {

   /*========================================*/

   /* Declare your C functions if necessary. */

   /*========================================*/

 

   extern double rta();

   extern void *dummy();

 

   /*=========================================================*/

   /* Call DefineFunction to register user-defined functions. */

   /*=========================================================*/


   DefineFunction("rta",'d',PTIF rta,"rta");
   DefineFunction("mul",'l',PTIF mul,"mul");
  }

The first argument to DefineFunction is the CLIPS function name, a string representation of the name that will be used when calling the function from within CLIPS.

 

The second argument is the type of the value which will be returned to CLIPS. Note that this is not necessarily the same as the function type. Allowable return types are shown as follows:

 

Return Code

Return Type Expected

a

External Address

b

Boolean

c

Character

d

Double Precision Float

f

Single Precision Float

i

Integer

j

Unknown Data Type (Symbol, String, or Instance Name Expected)

k

Unknown Data Type (Symbol or String Expected)

l

Long Integer

m

Multifield

n

Unknown Data Type (Integer or Float Expected)

o

Instance Name

s

String

u

Unknown Data Type (Any Type Expected)

v

Void—No Return Value

w

Symbol

x

Instance Address

 

Boolean functions should return a value of type int (0 for the symbol FALSE and any other value for the symbol TRUE). String, symbol, instance name, external address, and instance address functions should return a pointer of type void *. Character return values are converted by CLIPS to a symbol of length one. Integer return values are converted by CLIPS to long integers for internal storage. Single precision float values are converted by CLIPS to double precision float values for internal storage. If a user function is not going to return a value to CLIPS, the func­tion should be defined as type void and this argument should be v for void. Return types o and x are only available if the object system has been enabled (see section 2.2).

 

Function types j, k, m, n, and u are all passed a data object as an argument in which the return value of function is stored. This allows a user defined function to return one of several possible return types. Function type u is the most general and can return any data type. By convention, function types j, k, m, and n return specific data types. CLIPS will signal an error if one of these functions return a disallowed type. See section 3.3.4 for more details on returning unknown data types.

 

The third argument is a pointer to the actual function, the compiled function name (an extern declaration of the function may be appropriate). The CLIPS name (first argu­ment) need not be the same as the actual function name (third argument). The macro identifier PTIF can be placed in front of a function name to cast it as a pointer to a function returning an integer (primarily to prevent warnings from compilers which allow function prototypes).

 

The fourth argument is a string representation of the third argument (the pointer to the actual C function). This name should be identical  to the third argument, but enclosed in quotation marks.

 

DefineFunction returns zero if the function was unsuccessfully called (e.g. bad function type parameter), otherwise a non‑zero value is returned.

 

User‑defined functions are searched before system functions. If the user defines a function which is the same as one of the defined functions already provided, the user function will be executed in its place. Appendix A of the Basic Programming Guide contains a list of function names used by CLIPS.

 

In place of DefineFunction, the DefineFunction2 function can be used to provide additional information to CLIPS about the number and types of arguments expected by a CLIPS function or command.

 

int      DefineFunction2(functionName,functionType,

                         functionPointer,actualFunctionName,

                         functionRestrictions);


char    *functionName, functionType, *actualFunctionName;

int    (*functionPointer)();

char    *functionRestrictions;

 

The first four arguments to DefineFunction2 are identical to the four arguments for DefineFunction. The fifth argument is a restriction string which indicates the number and types of arguments that the CLIPS function expects. The syntax format for the restriction string is

 

<min-args> <max-args> [<default-type> <types>*]

 

The values <min-args> and <max-args> must be specified in the string. Both values must either be a character digit (0-9) or the character *. A digit specified for <min-args> indicates that the function must have at least <min-args> arguments when called. The character * for this value indicates that the function does not require a minimum number of arguments. A digit specified for <max-args> indicates that the function must have no more than <max-args> arguments when called. The character * for this value indicates that the function does not prohibit a maximum number of arguments. The optional <default-type> is the assumed type for each argument for a function call. Following the <default-type>, additional type values may be supplied to indicate specific type values for each argument. The type codes for the arguments are as follows:

 

 

 

 

Type Code

Allowed Types

a

External Address

d

Float

e

Instance Address, Instance Name, or Symbol

f

Float

g

Integer, Float, or Symbol

h

Instance Address, Instance Name, Fact Address, Integer, or Symbol

i

Integer

j

Symbol, String, or Instance Name

k

Symbol or String

l

Integer

m

Multifield

n

Integer or Float

o

Instance Name

p

Instance Name or Symbol

q

Symbol, String, or Multifield

s

String

u

Any Data Type

w

Symbol

x

Instance Address

y

Fact Address

z

Fact address, Integer, or Symbol

 

 

Examples

The restriction string for a function requiring a minimum of three arguments is:

 

"3*"

 

The restriction string for a function requiring no more than five arguments is:

 

"*5"

 

The restriction string for a function requiring at least three and no more than five arguments (each of which must be an integer or float) is:

 

"35n"

 

The restriction string for a function requiring exactly six arguments (of which the first must be a string, the third an integer, and  the remaining arguments floats) is:

 

"66fsui"

3.2 Passing Arguments from CLIPS to External Func­tions

Although arguments are listed directly following a function name within a function call, CLIPS actually calls the function without any arguments. The arguments are stored internally by CLIPS and can be accessed by calling the argument access functions. Access functions are provided to determine both the number and types of arguments.

3.2.1 Determining the Number of Passed Arguments

User-defined functions should first determine that they have been passed the correct number of arguments. Several functions are provided for this purpose.

 

int      RtnArgCount();
int      ArgCountCheck(functionName,restriction,count);
int      ArgRangeCheck(functionName,min,max);


int      restriction, count, min, max;
char    *functionName;

A call to RtnArgCount will return an integer telling how many arguments with which the function was called. The function ArgCountCheck can be used for error checking if a function expects a minimum, maximum, or exact number of arguments (but not a combination of these restrictions). It returns an integer telling how many arguments with which the function was called (or -1 if the argument restriction for the function was unsatisfied). The first argument is the name of the function to be printed within the error message if the restriction is unsatisfied. The restriction argument should be one of the values NO_MORE_THAN, AT_LEAST, or EXACTLY. The count argument should contain a value for the number of arguments to be used in the restriction test. The function ArgRangeCheck can be used for error checking if a function expects a range of arguments. It returns an integer telling how many arguments with which the function was called (or -1 if the argument restriction for the function was unsatisfied). The first argument is the name of the function to be printed within the error message if the restriction is unsatisfied. The second argument is the minimum number of arguments and the third argument is the maximum number of arguments.

3.2.2 Passing Symbols, Strings, Instance Names, Floats, and Integers

Several access functions are provided to retrieve arguments that are symbols, strings, instance names, floats, and integers.

 

char    *RtnLexeme(argumentPosition);
double   RtnDouble(argumentPosition);
long     RtnLong(argumentPosition);

int      argumentPosition;

 

A call to RtnLexeme returns a character pointer from either a symbol, string;, or instance name data type (NULL is returned if the type is not SYMBOL, STRING, or INSTANCE_NAME), RtnDouble returns a floating‑point number from either an INTEGER or FLOAT data type, and RtnLong returns a long integer from either an INTEGER or FLOAT data type. The arguments have to be requested one at a time by specify­ing each argumentÕs position number as the argumentPosition to RtnLexeme, RtnDouble, or RtnLong. If the type of argu­ment is unknown, another function can be called to determine the type. See section 3.2.3 for a further discussion of unknown argument types. Do not store the pointer returned by RtnLexeme as part of a permanent data structure. When CLIPS performs garbage collection on symbols and strings, the pointer reference to the string may be rendered invalid. To store a permanent reference to a string, allocate storage for a copy of the string and then copy the string returned by RtnLexeme to the copyÕs storage area.

Example

The following code is for a function to be called from CLIPS called rta which will return the area of a right triangle.

 

                                /* This include definition      */
#include "clips.h"              /* should start each file which */
                                /* has CLIPS functions in it    */

 

/*

Use DefineFunction2("rta",'d',PTIF rta,"rta","22n");

*/

double rta()

  {

   double base, height;

 

   /*==================================*/

   /* Check for exactly two arguments. */

   /*==================================*/

 

   if (ArgCountCheck("rta",EXACTLY,2) == -1) return(-1.0);

 

   /*===============================================*/

   /* Get the values for the 1st and 2nd arguments. */

   /*===============================================*/

 

   base = RtnDouble(1);                                 

   height = RtnDouble(2);

 

   /*==================================*/

   /* Return the area of the triangle. */

   /*==================================*/

 

   return(0.5 * base * height);

  }

 

As previ­ously shown, rta also should be defined in UserFunctions. If the value passed from CLIPS is not the data type ex­pected, an error occurs. Section 3.2.3 describes a method for testing the data type of the passed arguments which would allow user-defined functions to do their own error handling. Once compiled and linked with CLIPS, the function rta could be called as shown following.

 

CLIPS> (rta 5.0 10.0)

25.0

CLIPS> (assert (right-triangle-area (rta 20.0 10.0)))

CLIPS> (facts)

f-0     (right-triangle-area 100.0)

For a total of 1 fact.

CLIPS>

3.2.3 Passing Unknown Data Types

Section 3.2.2 described how to pass data to and from CLIPS when the type of data is explicitly known. It also is possible to pass parameters of an unknown data type to and from external functions. To pass an unknown parameter to an external function, use the RtnUnknown function.

 

    #include "clips.h"           /* or "evaluatn.h" */

    DATA_OBJECT *RtnUnknown(argumentPosition, &argument);

    int    GetType(argument);
    int    GetpType(&argument);

    int    ArgTypeCheck(char *,argumentPosition,

                        expectedType,&argument);

    char  *DOToString(argument);
    char  *DOPToString(&argument);
    double DOToDouble(argument);
    double DOPToDouble(&argument);
    float  DOToFloat(argument);
    float  DOPToFloat(&argument);
    long   DOToLong(argument);
    long   DOPToLong(&argument);
    int    DOToInteger(argument);
    int    DOPToInteger(&argument);
    void  *DOToPointer(argument);
    void  *DOPToPointer(&argument);

    int argumentPosition, expectedType;
    DATA_OBJECT argument;

 

Function RtnUnknown should be called first. It copies the elements of the internal CLIPS structure that represent the unknown‑type argument into the DATA_OBJECT structure pointed to by the second argument. It also returns a pointer to that same structure, passed as the second argument. After ob­taining a pointer to the DATA_OBJECT structure, a number of macros can be used to extract type information and the arguments value.

 

Macros GetType or GetpType can be used to determine the type of argument and will return an integer (STRING, SYMBOL, FLOAT, INTEGER,  MULTIFIELD, INSTANCE_ADDRESS, INSTANCE_NAME, or EXTERNAL_ADDRESS) defined in the clips.h file. Once the data type is known, the functions DOToDouble, DOPToDouble, DOToFloat, or DOPToFloat (for FLOAT), DOToString, or DOPToString (for STRING, SYMBOL, or INSTANCE_NAME), DOToLong, DOPToLong, DOToInteger, or DOPToInteger (for INTEGER), and DOToPointer and DOPToPointer (for INSTANCE_ADDRESS and EXTERNAL_ADDRESS) can be used to extract the actual value of the variable from the DATA_OBJECT structure. Accessing multifield values is discussed in section 3.2.4. Do not store the pointer returned by DOToString or DOPToString as part of a permanent data structure. When CLIPS performs garbage collection on symbols and strings, the pointer reference to the string may be rendered invalid. To store a permanent reference to a string, allocate storage for a copy of the string and then copy the string returned by DOToString or DOPToString to the copyÕs storage area.

 

The function ArgTypeCheck can be used for error checking if a function expects a specific type of argument for a particular parameter. It returns a non-zero integer value if the parameter was of the specified type, otherwise it returns zero. The first argument is the name of the function to be printed within the error message if the type restriction is unsatisfied. The second argument is the index of the parameter to be tested. The third argument is the type restriction and must be one of the following CLIPS defined constants: STRING, SYMBOL, SYMBOL_OR_STRING, FLOAT, INTEGER, INTEGER_OR_FLOAT, MULTIFIELD, EXTERNAL_ADDRESS, INSTANCE_ADDRESS, INSTANCE_NAME, or INSTANCE_OR_INSTANCE_NAME. If the FLOAT type restriction is used, then integer values will be converted to floating‑point numbers. If the INTEGER type restriction is used, then floating‑point values will be converted to integers. The fourth argument is a pointer to a DATA_OBJECT structure in which the unknown parameter will be stored.

Example

The following function mul takes two arguments from CLIPS. Each argument should be either an integer or a float. Float arguments are rounded and converted to the nearest integer. Once converted, the two arguments are multiplied together and this value is returned. If an error occurs (wrong type or number of arguments), then the value 1 is returned.

 

#include <math.h>          /* ANSI C library header file */

#include "clips.h"

 

/*

Use DefineFunction2("mul",'l',PTIF mul,"mul","22n");

*/


long mul()

  {

   DATA_OBJECT temp;

   long firstNumber, secondNumber;

  

   /*==================================*/

   /* Check for exactly two arguments. */

   /*==================================*/

 

   if (ArgCountCheck("mul",EXACTLY,2) == -1)

     { return(1L); }

 

   /*=========================================================*/

   /* Get the first argument using the ArgTypeCheck function. */

   /* Return if the correct type has not been passed.         */

   /*=========================================================*/

 

   if (ArgTypeCheck("mul",1,INTEGER_OR_FLOAT,&temp) == 0)

     { return(1L); }

 

   /*===========================================================*/

   /* Convert the first argument to a long integer. If it's not */

   /* an integer, then it must be a float (so round it to the   */

   /* nearest integer using the C library ceil function.        */

   /*===========================================================*/

 

   if (GetType(temp) == INTEGER)

     { firstNumber = DOToLong(temp); }

   else /* the type must be FLOAT */

     { firstNumber = (long) ceil(DOToDouble(temp) - 0.5); }

 

   /*========================================================*/

   /* Get the second argument using the RtnUnknown function. */

   /* Note that no type error checking is performed.         */

   /*========================================================*/

  

   RtnUnknown(2,&temp);

 

   /*=========================================================*/

   /* Convert the second argument to a long integer. If it's  */

   /* not an integer or a float, then it's the wrong type.    */

   /*=========================================================*/

 

   if (GetType(temp) == INTEGER)

     { secondNumber = DOToLong(temp); }

   else if (GetType(temp) == FLOAT)

     { secondNumber = (long) ceil(DOToDouble(temp) - 0.5); }

   else

     { return(1L); }

 

   /*=========================================================*/

   /* Multiply the two values together and return the result. */

   /*=========================================================*/

 

   return (firstNumber * secondNumber);

  }

 

Once compiled and linked with CLIPS, the function mul could be called as shown following.

 

CLIPS> (mul 3 3)

9

CLIPS> (mul 3.1 3.1)

9

CLIPS> (mul 3.8 3.1)

12

CLIPS> (mul 3.8 4.2)

16

CLIPS>

3.2.4 Passing Multifield Values

Data passed from CLIPS to an external function may be stored in multifield values. To access a multifield value, the user first must call RtnUnknown or ArgTypeCheck to get the pointer. If the argument is of type MULTIFIELD, several macros can be used to access the values of the multifield value.

 

#include "clips.h"           /* or "evaluatn.h" */

 

int    GetDOLength(argument);

int    GetpDOLength(&argument);

int    GetDOBegin(argument);        

int    GetpDOBegin(&argument);  

int    GetDOEnd(argument);   

int    GetpDOEnd(&argument);   

int    GetMFType(multifieldPtr,fieldPosition);

void  *GetMFValue(multifieldPtr,fieldPosition); 

 

DATA_OBJECT argument;

void *multifieldPtr;

int fieldPosition;

 

Macros GetDOLength and GetpDOLength can be used to determine the length of a DATA_OBJECT or DATA_OBJECT_PTR respectively. The macros GetDOBegin, GetpDOBegin, GetDOEnd, GetpDOEnd can be used to determine the beginning and ending indices of a DATA_OBJECT or DATA_OBJECT_PTR containing a multifield value. Since multifield values are often extracted from arrays of other data structures (such as facts), these indices are used to indicate the beginning and ending positions within the array. Thus it is very important when traversing a multifield value to use indices that run from the begin index to the end index and not from one to the length of the multifield value. The begin index points to the first element in the multifield value and the end index points to the last element in the multifield value. A multifield value of length one will have the same values for the begin and end indices. A multifield value of length zero will have an end index that is one less than the begin index.

 

The macros GetMFType and GetMFValue can be used to examine the types and values of fields within a multifield value. The first argument to these macros should be the value retrieved from a DATA_OBJECT or DATA_OBJECT_PTR using the GetValue and GetpValue macros. The second argument is the index of the field within the multifield value. Once again, this argument should fall in the range between the begin index and the end index for the DATA_OBJECT from which the multifield value is stored. Macros ValueToString, ValueToDouble, ValueToLong, and ValueToInteger can be used to convert the retrieved value from GetMFValue to a C object of type char *, double, and long respectively. Do not store the pointer returned by ValueToString as part of a permanent data structure. When CLIPS performs garbage collection on symbols and strings, the pointer reference to the string may be rendered invalid. To store a permanent reference to a string, allocate storage for a copy of the string and then copy the string returned by ValueToString to the copyÕs storage area.

 

The multifield macros should only be used on DATA_OBJECTs that have type MULTIFIELD (e.g. the macro GetDOLength returns erroneous values if the type is not MULTIFIELD).

Examples

The following function returns the length of a multifield value. It returns -1 if an error occurs.

 

#include "clips.h"

 

/*

Use DefineFunction2("mfl",'l',PTIF MFLength,"MFLength","11m");

*/

 

long int MFLength()

  {

   DATA_OBJECT argument;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("mfl",EXACTLY,1) == -1) return(-1L);

 

   /*====================================================*/

   /* Check that the 1st argument is a multifield value. */

   /*====================================================*/

 

   if (ArgTypeCheck("mfl",1,MULTIFIELD,&argument) == 0)

     { return(-1L); }

  

   /*============================================*/

   /* Return the length of the multifield value. */

   /*============================================*/

 

   return ( (long) GetDOLength(argument));

  }

 

The following function counts the number of characters in the symbols and strings contained within a multifield value.

 

#include "clips.h"

 

/*

Use DefineFunction2("cmfc",'l',PTIF CntMFChars,"CntMFChars",

                    "11m");

*/

 

long int CntMFChars()

  {

   DATA_OBJECT argument;

   void *multifieldPtr;

   int end, i;

   long count = 0;

   char *tempPtr;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("cmfc",EXACTLY,1) == -1) return(0L);

 

   /*======================================================*/

   /* Check that the first argument is a multifield value. */

   /*======================================================*/

 

   if (ArgTypeCheck("cmfc",1,MULTIFIELD,&argument) == 0)

     { return(0L); }

 

   /*=====================================*/

   /* Count the characters in each field. */

   /*=====================================*/

 

   end = GetDOEnd(argument);

   multifieldPtr = GetValue(argument);

   for (i = GetDOBegin(argument); i <= end; i++)

     {

      if ((GetMFType(multifieldPtr,i) == STRING) ||

          (GetMFType(multifieldPtr,i) == SYMBOL))

        {

         tempPtr = ValueToString(GetMFValue(multifieldPtr,i));

         count += strlen(tempPtr);

        }

     }

 

   /*=============================*/

   /* Return the character count. */

   /*=============================*/

 

   return(count);

  }

3.3 Returning Values To CLIPS From External Func­tions

Functions which return doubles, floats, integers, long integers, characters, external addresses, and instance addresses can directly return these values to CLIPS. Other data types including the unknown (or unspecified) data type and multifield data type, must use functions provided by CLIPS to construct return values.

3.3.1 Returning Symbols, Strings, and Instance Names

CLIPS uses symbol tables to store all symbols, string;s, and instance names. Symbol tables increase both performance and memory efficiency during execution. If a user‑defined function returns a symbol, string, or an instance name (type 's', 'w', or 'o' in DefineFunction), the symbol must be stored in the CLIPS symbol table prior to use. Other types of returns (such as unknown and multifield values) may also contain symbols which must be added to the symbol table. These symbols can be added by calling the function AddSymbol and using the returned pointer value.

 

#include "clips.h"           /* or "symbol.h" */

 

void *AddSymbol(string);
char *string;

Example

This function reverses the character ordering in a string and returns the reversed string. The null string is returned if an error occurs.

 

#include <stdlib.h>            /* ANSI C library header file */

#include <stddef.h>            /* ANSI C library header file */

#include "clips.h"

 

/*

Use DefineFunction2("reverse-str",'s',PTIF Reverse,"Reverse",

                    "11s");

*/

 

void *Reverse()

  {

   DATA_OBJECT temp;

   char *lexeme, *tempString;

   void *returnValue;

   int i, length;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("reverse-str",EXACTLY,1) == -1)

     { return(AddSymbol("")); }

 

   /*=========================================================*/

   /* Get the first argument using the ArgTypeCheck function. */

   /*=========================================================*/

 

   if (ArgTypeCheck("reverse-str",1,STRING,&temp) == 0)

     { return(AddSymbol("")); }

   lexeme = DOToString(temp);

 

   /*========================================================*/

   /* Allocate temporary space to store the reversed string. */

   /*========================================================*/

 

   length = strlen(lexeme);

   tempString = (char *) malloc(length + 1);

 

   /*=====================*/

   /* Reverse the string. */

   /*=====================*/

 

   for (i = 0; i < length; i++)

     { tempString[length - (i + 1)] = lexeme[i]; }

   tempString[length] = '\0';

 

   /*=============================*/

   /* Return the reversed string. */

   /*=============================*/

 

   returnValue = AddSymbol(tempString);

   free(tempString);

   return(returnValue);

  }

3.3.2 Returning Boolean Values

A user function may return a boolean value in one of two ways. The user may define an integer function and use DefineFunction to declare it as a BOOLEAN type ('b'). The function should then either return the value TRUE or FALSE. Alternatively, the function may be declare to return a SYMBOL type ('w') or UNKNOWN type ('u') and return the value of FalseSymbol or TrueSymbol macro.

 

#include "clips.h"           /* or "symbol.h" */

 

#define FALSE 0

#define TRUE  1

 

void *FalseSymbol();

void *TrueSymbol();

Examples

This function returns true if its first argument is a number greater than zero. It uses a boolean return value.

 

#include "clips.h"

 

/*

Use DefineFunction2("positivep1",'b',positivep1,"positivep1",

                    "11n");

*/

 

int positivep1()

  {

   DATA_OBJECT temp;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("positivep1",EXACTLY,1) == -1)

     { return(FALSE); }

 

   /*=========================================================*/

   /* Get the first argument using the ArgTypeCheck function. */

   /*=========================================================*/

 

   if (ArgTypeCheck("positivep1",1,INTEGER_OR_FLOAT,&temp) == 0)

     { return(FALSE); }

 

   /*=====================================*/

   /* Determine if the value is positive. */

   /*=====================================*/

 

   if (GetType(temp) == INTEGER)

     { if (DOToLong(temp) <= 0L) return(FALSE); }

   else /* the type must be FLOAT */

     { if (DOToDouble(temp) <= 0.0) return(FALSE); }

 

   return(TRUE);

  }

 

This function also returns true if its first argument is a number greater than zero. It uses a symbolic return value.

 

#include "clips.h"

 

/*

Use DefineFunction("positivep2",'w',PTIF positivep2,"positivep2",

                   "11n");

*/

 

void *positivep2()

  {

   DATA_OBJECT temp;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("positivep1",EXACTLY,1) == -1)

     { return(FalseSymbol()); }

 

   /*=========================================================*/

   /* Get the first argument using the ArgTypeCheck function. */

   /*=========================================================*/

 

   if (ArgTypeCheck("positivep1",1,INTEGER_OR_FLOAT,&temp) == 0)

     { return(FalseSymbol()); }

 

   /*=====================================*/

   /* Determine if the value is positive. */

   /*=====================================*/

 

   if (GetType(temp) == INTEGER)

     { if (DOToLong(temp) <= 0L) return(FalseSymbol()); }

   else /* the type must be FLOAT */

     { if (DOToDouble(temp) <= 0.0) return(FalseSymbol()); }

 

   return(TrueSymbol());

  }

3.3.3 Returning External Addresses and Instance Addresses

A user function may return an external address or an instance address. The user should use DefineFunction to declare their function as returning an external address type ('a') or an instance address type ('x'). The function should then either return a pointer that has been typecast to (void *). Within CLIPS, the printed representation of an external address is

 

<Pointer-XXXXXXXX>

 

where XXXXXXXX is the external address. Note that it is up to the user to make sure that external addresses remain valid within CLIPS. The printed representation of an instance address is

 

<Instance-XXX>

 

where XXX is the name of the instance.

Example

This function uses the memory allocation function malloc to dynamically allocated 100 bytes of memory and then returns a pointer to the memory to CLIPS.

 

#include <stdlib.h>

#include "clips.h"

 

/*

Use DefineFunction2("malloc",'a',PTIF CLIPSmalloc,"CLIPSmalloc",

                    "00");

*/

 

void *CLIPSmalloc()

  { return((void *) malloc(100)); }

3.3.4 Returning Unknown Data Types

A user‑defined function also may return values of an unknown type. The user must declare the function as returning type unknown; i.e., place a 'u' for data type in the call to DefineFunction. The user function will be passed a pointer to a structure of type DATA_OBJECT (DATA_OBJECT_PTR) which should be modified to contain the return value. The user should set both the type and the value of the DATA_OBJECT. Note that the value of a DATA_OBJECT cannot be directly set to a double or long value (the functions AddLong and AddDouble should be used in a manner similar to AddSymbol). The actual return value of the user function is ignored.

 

#include "clips.h"           /* or "evaluatn.h" */

 

int    SetType(argument,type);

int    SetpType(&argument,type);
 

void  *SetValue(argument,value); 
void  *SetpValue(&argument,value);

void  *AddLong(longValue);
void  *AddDouble(doubleValue);

void  *GetValue(argument);   
void  *GetpValue(&argument);


char  *ValueToString(value);
double ValueToDouble(value);
long   ValueToLong(value);
int    ValueToInteger(value);

long longValue;
double doubleValue;
void *value;
int type;
DATA_OBJECT argument;

 

Macros SetType and SetpType can be used to set the type of a DATA_OBJECT or DATA_OBJECT_PTR respectively. The type parameter should be one of the following CLIPS defined constants (note that these are not strings): SYMBOL, STRING,  INTEGER, FLOAT, EXTERNAL_ADDRESS, INSTANCE_NAME, or INSTANCE_ADDRESS. Macros SetValue (for DATA_OBJECTs) and SetpValue (for DATA_OBJECT_PTRs) can be used to set the value of a DATA_OBJECT. The functions AddSymbol (for symbols, strings and instance names), AddLong (for integers) and AddDouble (for floats) can be used to produce values that can be used with these macros (external addresses and instance addresses can be used directly). Macros GetValue (for DATA_OBJECTs) and GetpValue (for DATA_OBJECT_PTRs) can be used to retrieve the value of a DATA_OBJECT. Note that the value for an external address or an instance address can be retrieved directly using one of these macros. For other data types, the macros ValueToString (for symbols, strings, and instance names), ValueToLong (for integers), ValueToInteger (for integers), and ValueToDouble (for floats) can be used to convert the retrieved value from a DATA_OBJECT to a C object of type char *, double, long, or integer respectively.

Example

This function "cubes" its argument returning either an integer or float depending upon the type of the original argument. It returns the symbol FALSE upon an error.

 

#include "clips.h"

 

/*

Use DefineFunction2("cube",'u',PTIF cube,"cube","11n");

*/

 

void cube(

  DATA_OBJECT_PTR returnValuePtr)

  {

   void *value;

   long longValue;

   double doubleValue;

 

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("cube",EXACTLY,1) == -1)

     {

      SetpType(returnValuePtr,SYMBOL);

      SetpValue(returnValuePtr,FalseSymbol());

      return;

     }

 

   /*=========================================================*/

   /* Get the first argument using the ArgTypeCheck function. */

   /*=========================================================*/

 

   if (! ArgTypeCheck("cube",1,INTEGER_OR_FLOAT,returnValuePtr))

     {

      SetpType(returnValuePtr,SYMBOL);

      SetpValue(returnValuePtr,FalseSymbol());

      return;

     }

 

   /*===========================================================*/

   /* Cube the argument. Note that the return value DATA_OBJECT */

   /* is used to retrieve the function's argument and return    */

   /* the function's return value.                              */

   /*===========================================================*/

 

   if (GetpType(returnValuePtr) == INTEGER)

     {

      value = GetpValue(returnValuePtr);

      longValue = ValueToLong(value);

      value = AddLong(longValue * longValue * longValue);

     }

   else /* the type must be FLOAT */

     {

      value = GetpValue(returnValuePtr);

      doubleValue = ValueToDouble(value);

      value = AddDouble(doubleValue * doubleValue * doubleValue);

     }

 

   /*=====================================================*/

   /* Set the value of the return DATA_OBJECT. The return */

   /* type does not have to be changed since it will be   */

   /* the same as the 1st argument to the function.       */

   /*=====================================================*/

 

   SetpValue(returnValuePtr,value);

   return;

  }

3.3.5 Returning Multifield Values

Multifield values can also be returned from an external function. When defining such an external function, the data type should be set to 'm' in the call to DefineFunction. Note that a multifield value can also be returned from a 'u' function, whereas only a multifield value should be returned from an 'm' function. As with returning unknown data types, the user function will be passed a pointer of type DATA_OBJECT_PTR which can be modified to set up a multifield value. The following macros and functions are useful for this purpose:

 

void  *CreateMultifield(size);

int    SetMFType(multifieldPtr,fieldPosition,type); 

void  *SetMFValue(multifieldPtr,fieldPosition,value);

int    SetDOBegin(returnValue,fieldPosition);     

int    SetpDOBegin(&returnValue,fieldPosition);   

int    SetDOEnd(returnValue,fieldPosition);     

int    SetpDOEnd(&returnValue,fieldPosition);

void   SetMultifieldErrorValue(&returnValue); 

 

DATA_OBJECT returnValue;

Unsigned size;

int fieldPosition, type;

void *multifieldPtr;

void *value;

 

If a new multifield is to be created from an existing multifield, then the type and value of the existing multifield can be copied and the begin and end indices can be modified to obtain the appropriate subfields of the multifield value. If you wish to create a new multifield value that is not part of an existing multifield value, then use the function CreateMultifield. Given an integer argument, this function will create a multifield value of the specified size with valid indices ranging from one to the given size (zero is a legitimate parameter to create a multifield value with no fields). The macros SetMFType and SetMFValue can be used to set the types and values of the fields of the newly created multifield value. Both macros accept as their first argument the value returned by CreateMultifield. The second argument should be an integer representing the position of the multifield value to be set. The third argument is the same as the arguments used for SetType and SetValue macros.

 

Do not set the value or type of any field within a multifield value that has been returned to you by CLIPS. Use these macros only on multifield values created using the CreateMultifield function.

 

The macros SetDOBegin, SetpDOBegin, SetDOEnd, SetpDOEnd can be used to assign values to the begin and end indices of a DATA_OBJECT or DATA_OBJECT_PTR containing a multifield value. These macros are useful for creating ÒnewÓ multifield values by manipulating the indices of a currently existing multifield value. For example, a function that returns the first field of a multifield value could do so by setting the end index equal to the begin index (if the length of the multifield value was greater than zero).

 

The function SetMultifieldErrorValue can be used to create a multifield value of length zero (which is useful to return as an error value). Its only parameter is a DATA_OBJECT_PTR which is appropriately modified to create a zero length multifield value.

Examples

The following example creates a multifield value with two fields, a word and a number:

 

#include "clips.h"

 

/*

Use DefineFunction2("sample4",'m',PTIF sample4,"sample4","00");

*/

 

void sample4(

  DATA_OBJECT_PTR returnValuePtr)

  {

   void *multifieldPtr;

 

   /*===================================*/

   /* Check for exactly zero arguments. */

   /*===================================*/

 

   if (ArgCountCheck("sample4",EXACTLY,0) == -1)

     {

      SetMultifieldErrorValue(returnValuePtr);

      return;

     }

 

   /*========================================*/

   /* Create a multi-field value of length 2 */

   /*========================================*/

 

   multifieldPtr = CreateMultifield(2);

 

   /*============================================*/

   /* The first field in the multi-field value   */

   /* will be a SYMBOL. Its value will be        */

   /* "altitude".                                */

   /*============================================*/

 

   SetMFType(multifieldPtr,1,SYMBOL);

   SetMFValue(multifieldPtr,1,AddSymbol("altitude"));

 

   /*===========================================*/

   /* The second field in the multi-field value */

   /* will be a FLOAT. Its value will be 900.   */

   /*===========================================*/

 

   SetMFType(multifieldPtr,2,FLOAT);

   SetMFValue(multifieldPtr,2,AddDouble(900.0));

 

   /*======================================================*/

   /* Assign the type and value to the return DATA_OBJECT. */

   /*======================================================*/

 

   SetpType(returnValuePtr,MULTIFIELD);

   SetpValue(returnValuePtr,multifieldPtr);

 

   /*=================================================*/

   /* The length of our multi-field value will be 2.  */

   /* Since we will create our own multi-field value  */

   /* the begin and end indexes to our function will  */

   /* be 1 and the length of the multi-field value    */

   /* respectively. If we are examining a multi-field */

   /* value, or using an existing multi-field value   */

   /* to create a new multi-field value, then the     */

   /* begin and end indexes may not correspond to 1   */

   /* and the length of the multi-field value.        */

   /*=================================================*/

 

   SetpDOBegin(returnValuePtr,1);

   SetpDOEnd(returnValuePtr,2);

 

   return;

  }

 

The following example returns all but the first field of a multifield value:

 

#include "clips.h"

 

/*

Use DefineFunction2("rest",'m',PTIF rest,"rest","11m");

*/

 

void rest(

  DATA_OBJECT_PTR returnValuePtr)

  {

   /*=================================*/

   /* Check for exactly one argument. */

   /*=================================*/

 

   if (ArgCountCheck("rest",EXACTLY,1) == -1)

     {

      SetMultifieldErrorValue(returnValuePtr);

      return;

     }

 

   /*=========================*/

   /* Check for a MULTIFIELD. */

   /*=========================*/

 

   if (ArgTypeCheck("rest",1,MULTIFIELD,returnValuePtr) == 0)

     {

      SetMultifieldErrorValue(returnValuePtr);

      return;

     }

 

   /*===================================================*/

   /* Don't bother with a zero length multifield value. */

   /*===================================================*/

 

   if (GetpDOBegin(returnValuePtr) > GetpDOEnd(returnValuePtr))

     { return; }

 

   /*===================================*/

   /* Increment the begin index by one. */

   /*===================================*/

 

   SetpDOBegin(returnValuePtr,GetpDOBegin(returnValuePtr) + 1);

  }

3.4 User‑Defined Function Example

This section lists the steps needed to define and implement a user‑defined function. The example given is somewhat trivial, but it demonstrates the point. The user function merely triples a number and returns the new value.

 

1)   Copy all of the CLIPS source code file to the user directory.

 

2)   Define the user function in a new file.


#include "clips.h"

double TripleNumber()
  {

   return(3.0 * RtnDouble(1));

  }

 

The preceding function does the job just fine. The following function, however, accom­plishes the same purpose while providing error handling on arguments and allowing either an integer or double return value.


#include "clips.h"

void TripleNumber(

  DATA_OBJECT_PTR returnValuePtr)  

  {

   void        *value;

   long         longValue;

   double       doubleValue;

 

   /*===============================================*/

   /* If illegal arguments are passed, return zero. */

   /*===============================================*/

 

   if (ArgCountCheck("triple",EXACTLY,1) == -1)

     {

      SetpType(returnValuePtr,INTEGER);

      SetpValue(returnValuePtr,AddLong(0L));

      return;

     }

 

   if (! ArgTypeCheck("triple",1,INTEGER_OR_FLOAT,returnValuePtr))

     {

      SetpType(returnValuePtr,INTEGER);

      SetpValue(returnValuePtr,AddLong(0L));

      return;

     }

 

   /*====================*/

   /* Triple the number. */

   /*====================*/

 

   if (GetpType(returnValuePtr) == INTEGER)

     {

      value = GetpValue(returnValuePtr);

      longValue = 3 * ValueToLong(value);

      SetpValue(returnValuePtr,AddLong(longValue));

     }

   else /* the type must be FLOAT */

     {

      value = GetpValue(returnValuePtr);

      doubleValue = 3.0 * ValueToDouble(value);

      SetpValue(returnValuePtr,AddDouble(doubleValue));

     }

 

   return;

  }

 

3)   Define the constructs which use the new function in a new file (or in an existing constructs file). For example:

 

(deffacts init‑data
   (data 34)
   (data 13.2))

 

(defrule get‑data
   (data ?num)
   =>
   (printout t "Tripling " ?num crlf)
   (assert (new-value (triple ?num))))

 

(defrule get‑new‑value
   (new‑value ?num)
   =>
   (printout t crlf "Now equal to " ?num crlf))

 

4)   Modify the CLIPS userfunctions.c file to include the new UserFunctions definition.  

 

void UserFunctions()

  {

   /* The following code is used with the second example */

   /* of the TripleFunction listed in step 2.            */


   extern void TripleNumber(DATA_OBJECT_PTR);

   DefineFunction2("triple",'u',PTIF TripleNumber, "TripleNumber",

                   "11n");
 

   /* Alternately, if the TripleFunction with a double return */

   /* value from step 2 was used, the following declaration   */

   /* and DefineFunction2 call should be used in place of the */

   /* one above.                                              */

 

   /*

   extern double TripleNumber(void);

 

   DefineFunction2("triple",'d',PTIF TripleNumber, "TripleNumber","11n");

   */

 }

 

5)   Compile the CLIPS files along with any files which contain user‑defined functions.

 

6)   Link all object code files.

 

7)   Execute new CLIPS executable. Load the constructs file and test the new function.


Section 4 ‑ Embedding CLIPS

CLIPS was designed to be embedded within other programs. When CLIPS is used as an em­bedded application, the user must provide a main program. Calls to CLIPS are made like any other subroutine. To embed CLIPS, add the following include state­ments to the user's main program file:

 

#include <stdio.h>
#include "clips.h"

 

(These statements may have to be tailored so the compiler on the user's system can find the CLIPS include file.)  The userÕs main program must initialize CLIPS by calling the function InitializeEnvironment at some time prior to loading constructs. UserFunctions and EnvUserFunctions also must be defined, regardless of whether CLIPS calls any external functions. Compile and link all of the user's code with all CLIPS files except the object version of main.c. When running CLIPS as an embedded pro­gram, many of the capabilities available in the interactive interface (in addition to others) are available through function calls. The functions are documented in the following sec­tions. Prototypes for these functions can be included by using the clips.h header file.

4.1 Environment Functions

The following function calls control the CLIPS environment:

4.1.1 AddClearFunction

int   AddClearFunction(clearItemName,clearFunction,priority);

char *clearItemName;

void (*clearFunction)();

int   priority;

 

void clearFunction();

 

Purpose:                              Adds a user defined function to the list of functions which are called when the CLIPS clear  command is executed.

 

Arguments:                        1)   The name of the new clear item.

                                             2)   A pointer to the function which is to be called whenever a clear command is executed. This function must except an environment pointer if the environment companion function is used (see section 9.2).

                                             3)   The priority of the clear item which determines the order in which clear items are called (higher priority items are called first). The values -2000 to 2000 are reserved for CLIPS system defined clear items and should not be used for user defined clear items.

 

Returns:                              Returns a zero value if the clear item could not be added, otherwise a non-zero value is returned.

4.1.2 AddPeriodicFunction

    int   AddPeriodicFunction(periodicItemName,periodicFunction,

                              priority);

    char *periodicItemName;

    void (*periodicFunction)();

    int   priority;

 

    void periodicFunction();

 

Purpose:                              Adds a user defined function to the list of functions which are called periodically while CLIPS is executing. This ability was primarily included to allow interfaces to process events and update displays during CLIPS execution. Care should be taken not to use any operations in a periodic function which would affect CLIPS data structures constructively or destructively, i.e. CLIPS internals may be examined but not modified during a periodic function.

 

Arguments:                        1)   The name of the new periodic item.

                                             2)   A pointer to a function which is to be called periodically while CLIPS is executing. This function must except an environment pointer if the environment companion function is used (see section 9.2).

                                             3)   The priority of the periodic item which determines the order in which periodic items are called (higher priority items are called first). The values -2000 to 2000 are reserved for CLIPS system defined periodic items and should not be used for user defined periodic items.

 

Returns:                              Returns a zero value if the periodic item could not be added, otherwise a non-zero value is returned.

4.1.3 AddResetFunction

    int   AddResetFunction(resetItemName,resetFunction,priority);

    char *resetItemName;

    void (*resetFunction)();

    int   priority;

 

    void resetFunction();

 

Purpose:                              Adds a user defined function to the list of functions which are called when the CLIPS reset  command is executed.

 

Arguments:                        1)   The name of the new reset item.

                                             2)   A pointer to the function which is to be called whenever a reset command is executed. This function must except an environment pointer if the environment companion function is used (see section 9.2).

                                             3)   The priority of the reset item which determines the order in which reset items are called (higher priority items are called first). The values -2000 to 2000 are reserved for CLIPS system defined reset items and should not be used for user defined reset items.

 

Returns:                              Returns a zero value if the reset item could not be added, otherwise a non-zero value is returned.

4.1.4 BatchStar

    int   BatchStar(fileName);
    char *fileName;

 

Purpose:                              Evaluates the series of commands stored in the specified file without replacing standard input (the C equivalent of the CLIPS batch* command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; Zero if the file couldnÕt be opened or 1 if the file was opened.

 

Other:                                  The BatchStar function is not available for use in run-time programs.

4.1.5 Bload

    int   Bload(fileName);
    char *fileName;

 

Purpose:                              Loads a binary image of constructs into the CLIPS data base (the C equivalent of the CLIPS bload command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; if zero, an error occurred. A positive one is returned upon success.

4.1.6 Bsave

    int   Bsave(fileName);
    char *fileName;

 

Purpose:                              Saves a binary image of constructs from the CLIPS data base (the C equivalent of the CLIPS bsave command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; if zero, an error occurred. A positive one is returned upon success.

4.1.7 Build

    int Build(constructString);

    char *constructString;

 

Purpose:                              Allows a construct to be defined (the C equivalent of the CLIPS build command).

 

Arguments:                        1)   A string containing the construct to be added.

                                            

Returns:                              Returns an integer. 1 if the construct was successfully parsed, otherwise 0.

 

Other:                                  The Build function is not available for use in run-time programs (since individual constructs canÕt be added or deleted).

4.1.8 Clear

    void Clear();

 

Purpose:                              Clears the CLIPS environment (the C equivalent of the CLIPS clear command).

 

Arguments:                         None.

 

Returns:                              No meaningful return value.

 

Other:                                  This function can trigger garbage collection.

4.1.9 Eval

    int Eval(expressionString,&result);

    char *expressionString;

    DATA_OBJECT result;

 

Purpose:                              Allows an expression to be evaluated (the C equivalent of the CLIPS eval command).

 

Arguments:                        1)   A string containing the expression to be evaluated.

                                             2)   CallerÕs buffer for storing the result of the evaluation. See sections 3.2.3 and 3.2.4 for information on getting the value stored in a DATA_OBJECT.

 

Returns:                              Returns an integer. 1 if the expression was successfully evaluated, otherwise 0.

 

Other:                                  The Eval function is not available for use in run-time programs.

4.1.10 FunctionCall

    int FunctionCall(functionName,arguments,&result);

    char *functionName,*arguments;

    DATA_OBJECT result;

 

Purpose:                              Allows CLIPS system functions, deffunctions and generic functions to be called from C.

 

Arguments:                        1)   The name of the system function, deffunction or generic function to be called.

                                             2)   A string containing any constant arguments separated by blanks (this argument can be NULL).

                                             3)   CallerÕs buffer for storing the result of the function call. See sections 3.2.3 and 3.2.4 for information on getting the value stored in a DATA_OBJECT.

 

Returns:                              An integer; TRUE (1) if an error occurred while evaluating the function, otherwise FALSE (0).

 

Other:                                  This function can trigger garbage collection.

 

Example

 

DATA_OBJECT rtn;

   

FunctionCall("+","1 2",&rtn);

4.1.11 GetAutoFloatDividend

    int   GetAutoFloatDividend();

 

Purpose:                              Returns the current  value of the auto‑float dividend behavior (the C equivalent of the CLIPS get-auto-float-dividend command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.1.12 GetDynamicConstraintChecking

    int   GetDynamicConstraintChecking();

 

Purpose:                              Returns the current  value of the dynamic constraint checking behavior (the C equivalent of the CLIPS  get‑dynamic‑constraint‑checking command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.1.13 GetSequenceOperatorRecognition

    int   GetSequenceOperatorRecognition();

 

Purpose:                              Returns the current  value of the sequence operator recognition behavior (the C equivalent of the CLIPS get-sequence-operator-recognition command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.1.14 GetStaticConstraintChecking

    int   GetStaticConstraintChecking();

 

Purpose:                              Returns the current  value of the static constraint checking behavior (the C equivalent of the CLIPS  get‑static‑constraint‑checking command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.1.15 InitializeEnvironment

    void InitializeEnvironment();

 

Purpose:                              Initializes the CLIPS system. Must be called prior to any other CLIPS function call. NOTE: This function should be called only once.

 

Arguments:                         None.

 

Returns:                              No meaningful return value.

4.1.16 Load

    int   Load(fileName);
    char *fileName;

 

Purpose:                              Loads a set of constructs into the CLIPS data base (the C equivalent of the CLIPS load command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; Zero if the file couldnÕt be opened, -1 if the file was opened but an error occurred while loading, and 1 if the file was opened an no errors occurred while loading. If syntactic errors are in the constructs, Load still will attempt to read the en­tire file and error notices will be sent to werror.

 

Other:                                  The load function is not available for use in run-time programs (since individual constructs canÕt be added or deleted). To execute different sets of constructs, the switching feature must be used in a run-time program (see section 5 for more details).

4.1.17 RemoveClearFunction

    int   RemoveClearFunction(clearItemName);

    char *clearItemName;

 

Purpose:                              Removes a named function from the list of functions to be called during a clear command.

 

Arguments:                         The name associated with the user‑defined clear function. This is the same name that was used when the clear function was added with the function AddClearFunction.

 

Returns:                              Returns the integer value 1 if the named function was found and removed, otherwise 0 is returned.

4.1.18 RemovePeriodicFunction

    int   RemovePeriodicFunction(periodicItemName);

    char *periodicItemName;

 

Purpose:                              Removes a named function from the list of functions which are called periodically while CLIPS is executing.

 

Arguments:                         The name associated with the user‑defined periodic function. This is the same name that was used when the periodic function was added with the function AddPeriodicFunction.

 

Returns:                              Returns the integer value 1 if the named function was found and removed, otherwise 0 is returned.

4.1.19 RemoveResetFunction

    int   RemoveResetFunction(resetItemName);

    char *resetItemName;

 

 

Purpose:                              Removes a named function from the list of functions to be called during a reset command.

 

Arguments:                         The name associated with the user‑defined reset function. This is the same name that was used when the reset function was added with the function AddResetFunction.

 

Returns:                              Returns the integer value 1 if the named function was found and removed, otherwise 0 is returned.

4.1.20 Reset

    void Reset();

 

Purpose:                              Resets the CLIPS environment (the C equivalent of the CLIPS reset command).

 

Arguments:                         None.

 

Returns:                              No meaningful return value.

 

Other:                                  This function can trigger garbage collection.

4.1.21 Save

    int   Save(fileName);
    char *fileName;

 

Purpose:                              Saves a set of constructs to the specified file (the C equivalent of the CLIPS save command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; if zero, an error occurred while opening the file. If non‑zero no errors were detected while performing the save.

4.1.22 SetAutoFloatDividend

    int   SetAutoFloatDividend(value);

    int   value;

 

Purpose:                              Sets the auto‑float dividend behavior (the C equivalent of the CLIPS set-auto-float-dividend command). When this behavior is enabled (by default) the dividend of the division function is automatically converted to a floating point number.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.1.23 SetDynamicConstraintChecking

    int   SetDynamicConstraintChecking(value);

    int   value;

 

Purpose:                              Sets the value of the dynamic constraint checking behavior (the C equivalent of the CLIPS command set‑dynamic‑constraint-checking). When this behavior is disabled (FALSE by default), newly created data objects (such as deftemplate facts and instances) do not have their slot values checked for constraint violations. When this behavior is enabled (TRUE), the slot values are checked for constraint violations. The return value for this function is the old value for the behavior.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.1.24 SetSequenceOperator Recognition

    int   SetSequenceOperatorRecognition(value);

    int   value;

 

Purpose:                              Sets the sequence operator recognition behavior (the C equivalent of the CLIPS set-sequence-operator-recognition command). When this behavior is disabled (by default) multifield variables found in function calls are treated as a single argument. When this behaviour is enabled, multifield variables are expanded and passed as separate arguments in the function call.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.1.25 SetStaticConstraintChecking

    int   SetStaticConstraintChecking(value);

    int   value;

 

Purpose:                              Sets the value of the static constraint checking behavior (the C equivalent of the CLIPS command set‑static‑constraint-checking). When this behavior is disabled (FALSE), constraint violations are not checked when function calls and constructs are parsed. When this behavior is enabled (TRUE by default), constraint violations are checked when function calls and constructs are parsed. The return value for this function is the old value for the behavior.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.2 Debugging Functions

The following function call controls the CLIPS debugging aids:

4.2.1 DribbleActive

    int DribbleActive();

 

Purpose:                              Determines if the storing of dribble information is active.

 

Arguments:                         None.

 

Returns:                              Zero if dribbling is not active, non-zero otherwise.

4.2.2 DribbleOff

    int DribbleOff();

 

Purpose:                              Turns off the storing of dribble information (the C equivalent of the CLIPS dribble-off command).

 

Arguments:                         None.

 

Returns:                              A zero if an error occurred closing the file; otherwise a one.

4.2.3 DribbleOn

    int   DribbleOn(fileName);

    char *fileName;

 

Purpose:                              Allows the dribble function of CLIPS to be turned on (the C equivalent of the CLIPS dribble-on command).

 

Arguments:                         The name of the file in which to store dribble information. Only one dribble file may be opened at a time.

 

Returns:                              A zero if an error occurred opening the file; otherwise a one.

4.2.4 GetWatchItem

    int   GetWatchItem(item);

    char *item;

 

Purpose:                              Returns the current value of a watch item.

 

Arguments:                         The item to be activated or deactivated which should be one of the following strings: facts, rules, activations, focus, compilations, statistics, globals, instances, slots, messages, message‑handlers, generic‑functions, method, or deffunctions.

 

Returns:                              Returns 1 if the watch item is enabled, 0 if the watch item is disabled, and -1 if the watch item does not exist.

4.2.5 Unwatch

    int   Unwatch(item);

    char *item;

 

Purpose:                              Allows the tracing facilities of CLIPS to be deactivated (the C equivalent of the CLIPS unwatch command).

 

Arguments:                         The item to be deactivated which should be one of the following strings: facts, rules, activations, focus, compilations, statistics, globals, deffunctions, instances, slots, messages, message‑handlers, generic‑functions, methods, or all. If all is se­lected, all possible watch items will not be traced.

 

Returns:                              A one if the watch item was successfully set; otherwise a zero.

4.2.6 Watch

    int   Watch(item);

    char *item;

 

Purpose:                              Allows the tracing facilities of CLIPS to be activated (the C equivalent of the CLIPS watch command).

 

Arguments:                         The item to be activated which should be one of the following strings: facts, rules, activations, focus, compilations, statistics, globals, deffunctions, instances, slots, messages, message‑handlers, generic‑functions, methods, or all. If all is se­lected, all possible watch items will be traced.

 

Returns:                              A one if the watch item was successfully set; otherwise a zero.

4.3 Deftemplate Functions

The following function calls are used for manipulating deftemplates.

4.3.1 DeftemplateModule

    char *DeftemplateModule(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Returns the module in which a deftemplate is defined (the C equivalent of the CLIPS deftemplate-module command).

 

Arguments:                        A generic pointer to a deftemplate.

 

Returns:                              A string containing the name of the module in which the deftemplate is defined.

4.3.2 DeftemplateSlotAllowedValues

    void DeftemplateSlotAllowedValues(deftemplatePtr,slotName,&result);

    void *deftemplatePtr;

    char *slotName;

    DATA_OBJECT result;

                     

Purpose:                              Groups the allowed-values for a slot into a multifield data object. This function is the C equivalent of the CLIPS deftemplate-slot‑allowed-values function.

 

Arguments:                         1) A generic pointer to a deftemplate data structure.

                                             2) Name of the slot.

                                             3) Pointer to the data object in which to store the multifield. The multifield functions described in section 3.2.4 can be used to retrieve the allowed values from the list.

 

Returns:                              No meaningful return value.

4.3.3 DeftemplateSlotCardinality

    void DeftemplateSlotCardinality(deftemplatePtr,slotName,result);

    void *deftemplatePtr;

    char *slotName;

    DATA_OBJECT *result;

                     

Purpose:                              Groups the cardinality information for a slot into a multifield data object. This function is the C equivalent of the CLIPS deftemplate-slot-cardinality function.

 

Arguments:                         1) A generic pointer to a deftemplate data structure.

                                             2) Name of the slot.

                                             3) Pointer to the data object in which to store the multifield.

 

Returns:                              No meaningful return value.

4.3.4 DeftemplateSlotDefaultP

    int DeftemplateSlotDefaultP(deftemplatePtr,slotName);
    void *deftemplatePtr,

    char *slotName;

 

Purpose:                              Determines if the specified slot has a default value. This function is the C equivalent of the CLIPS deftemplate-slot-defaultp function.

 

Arguments:                        1)   A generic pointer to a deftemplate data structure.

                                             2)   The name of the slot.

                                            

Returns:                              One of the following defined integer constants:


NO_DEFAULT
STATIC_DEFAULT
DYNAMIC_DEFAULT

4.3.5 DeftemplateSlotDefaultValue

    void DeftemplateSlotDefaultValue(deftemplatePtr,slotName,result);

    void *defclassPtr;

    char *slotName;

    DATA_OBJECT *result;

                     

Purpose:                              Returns the default value in the data object. This function is the C equivalent of the CLIPS deftemplate-slot-default-value function.

 

Arguments:                         1) A generic pointer to a deftemplate data structure.

                                             2) Name of the slot.

                                             3) Pointer to the data object in which to store the default value.

 

Returns:                              No meaningful return value.

4.3.6 DeftemplateSlotExistP

    int DeftemplateSlotExistP(deftemplatePtr,slotName);
    void *deftemplatePtr,

    char *slotName;

 

Purpose:                              Determines if the specified slot exists. This function is the C equivalent of the CLIPS deftemplate-slot-existp function.

 

Arguments:                        1)   A generic pointer to a deftemplate data structure.

                                             2)   The name of the slot.

                                            

Returns:                              An integer: If the slot is defined in the specified deftemplate, then 1 is returned, otherwise 0 is returned.

4.3.7 DeftemplateSlotMultiP

    int DeftemplateSlotMultiP(deftemplatePtr,slotName);
    void *deftemplatePtr,

    char *slotName;

 

Purpose:                              Determines if the specified slot is a multifield slot. This function is the C equivalent of the CLIPS deftemplate-slot-multip function.

 

Arguments:                        1)   A generic pointer to a deftemplate data structure.

                                             2)   The name of the slot.

                                            

Returns:                              An integer: If the slot in the specified deftemplate is a multifield slot, then 1 is returned, otherwise 0 is returned.

4.3.8 DeftemplateSlotNames

    void DeftemplateSlotNames(deftemplatePtr,&theValue);

    void *deftemplatePtr;

    DATA_OBJECT slotNames;

 

Purpose:                              Retrieves the list of slot names associated with a deftemplate (the C equivalent of the CLIPS deftemplate-slot-names function).

 

Arguments:                        1)   A generic pointer to a deftemplate data structure.

                                             2)   A pointer to a DATA_OBJECT in which to place a multifield value containing the deftemplateÕs slot name symbols. For implied deftemplates, a multifield value containing the single symbol implied is returned. See sections 3.2.3 and 3.2.4 for information on getting the value stored in a DATA_OBJECT.

 

Returns:                              No meaningful value.

4.3.9 DeftemplateSlotRange

    void DeftemplateSlotRange(deftemplatePtr,slotName,result);

    void *deftemplatePtr;

    char *slotName;

    DATA_OBJECT *result;

                     

Purpose:                              Groups the numeric range information for a slot into a multifield data object. This function is the C equivalent of the CLIPS deftemplate-slot‑range function.

 

Arguments:                         1) A generic pointer to a deftemplate data structure.

                                             2) Name of the slot.

                                             3) Pointer to the data object in which to store the multifield.

 

Returns:                              No meaningful return value.

4.3.10 DeftemplateSlotSingleP

    int DeftemplateSlotSingleP(deftemplatePtr,slotName);
    void *deftemplatePtr,

    char *slotName;

 

Purpose:                              Determines if the specified slot is a single-field slot. This function is the C equivalent of the CLIPS deftemplate-slot-singlep function.

 

Arguments:                        1)   A generic pointer to a deftemplate data structure.

                                             2)   The name of the slot.

                                            

Returns:                              An integer: If the slot in the specified deftemplate is a single-field slot, then 1 is returned, otherwise 0 is returned.

4.3.11 DeftemplateSlotTypes

    void DeftemplateSlotTypes(deftemplatePtr,slotName,result);

    void *deftemplatePtr;

    char *slotName;

    DATA_OBJECT *result;

                     

Purpose:                              Groups the names of the primitive data types allowed for a slot into a multifield data object. This function is the C equivalent of the CLIPS deftemplate-slot-types function.

 

Arguments:                         1) A generic pointer to a deftemplate data structure.

                                             2) Name of the slot.

                                             3) Pointer to the data object in which to store the multifield.

 

Returns:                              No meaningful return value.

4.3.12 FindDeftemplate

    void *FindDeftemplate(deftemplateName);

    char *deftemplateName;

 

Purpose:                              Returns a generic pointer to a named deftemplate.

 

Arguments:                         The name of the deftemplate to be found.

 

Returns:                              A generic pointer to the named deftemplate if it exists, otherwise NULL.

4.3.13 GetDeftemplateList

    void GetDeftemplateList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of deftemplates in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-deftemplate-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the deftemplate names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.3.14 GetDeftemplateName

    char *GetDeftemplateName(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Returns the name of a deftemplate.

 

Arguments:                         A generic pointer to a deftemplate data structure.

 

Returns:                              A string containing the name of the deftemplate.

4.3.15 GetDeftemplatePPForm

    char *GetDeftemplatePPForm(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Returns the pretty print representation of a deftemplate.

 

Arguments:                         A generic pointer to a deftemplate data structure.

 

Returns:                              A string containing the pretty print representation of the deftemplate (or the NULL pointer if no pretty print representation exists).

4.3.16 GetDeftemplateWatch

    unsigned GetDeftemplateWatch(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Indicates whether or not a particular deftemplate is being watched.

 

Arguments:                         A generic pointer to a deftemplate data structure.

 

Returns:                              An integer; one (1) if the deftemplate is being watched, otherwise a zero (0).

4.3.17 GetNextDeftemplate

    void *GetNextDeftemplate(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Provides access to the list of deftemplates.

 

Arguments:                         A generic pointer to a deftemplate data structure (or NULL to get the first deftemplate).

 

Returns:                              A generic pointer to the first deftemplate in the list of deftemplates if deftemplatePtr is NULL, otherwise a generic pointer to the deftemplate immediately following deftemplatePtr in the list of deftemplates. If deftemplatePtr is the last deftemplate in the list of deftemplates, then NULL is returned.

4.3.18 IsDeftemplateDeletable

    int   IsDeftemplateDeletable(deftemplatePtr);
    void *deftemplatePtr;

 

Purpose:                              Indicates whether or not a particular deftemplate can be deleted.

 

Arguments:                         A generic pointer to a deftemplate data structure.

 

Returns:                              An integer; zero (0) if the deftemplate cannot be deleted, otherwise a one (1).

4.3.19 ListDeftemplates

    void ListDeftemplates(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of deftemplates (the C equivalent of the CLIPS list‑deftemplates command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the deftemplates to be listed. A NULL pointer indicates that deftemplate in all modules should be listed.

 

Returns:                              No meaningful return value.

4.3.20 SetDeftemplateWatch

    void SetDeftemplateWatch(newState,deftemplatePtr);

    unsigned    newState;

   void *deftemplatePtr;

 

Purpose:                              Sets the facts watch item for a specific deftemplate.

 

Arguments:                         The new facts watch state and a generic pointer to a deftemplate data structure.

4.3.21 Undeftemplate

    int   Undeftemplate(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Removes a deftemplate from CLIPS (the C equivalent of the CLIPS undeftemplate command).

 

Arguments:                         A generic pointer to a deftemplate data structure. If the NULL pointer is used, then all deftemplates will be deleted.

 

Returns:                              An integer; zero (0) if the deftemplate could not be deleted, otherwise a one (1).

 

Other:                                  This function can trigger garbage collection.

 

 

4.4 Fact Functions

The following function calls manipulate and display information about facts.

 4.4.1 Assert

    void *Assert(factPtr);

    void *factPtr;

 

Purpose:                              Adds a fact created using the function CreateFact to the fact-list. If the fact was asserted successfully, Assert will return a pointer to the fact. Otherwise, it will return NULL (i.e., the fact was already in the fact‑list).

 

Arguments:                         A generic pointer to the fact created using CreateFact. The values of the fact should be initialized before calling Assert.

 

Returns:                              A generic pointer to a fact structure. If the fact was asserted successfully, Assert will return a generic pointer to the fact. Otherwise, it will return NULL (i.e., the fact was already in the fact‑list).

 

Other:                                  This function can trigger garbage collection.

 

WARNING:                       If the return value from Assert is stored as part of a persistent data structure or in a static data area, then the function IncrementFactCount should be called to insure that the fact cannot be disposed while external references to the fact still exist.

4.4.2 AssertString

    void *AssertString(string);

    char *string;

 

Purpose:                              Asserts a fact into the CLIPS fact‑list (the C equivalent of the CLIPS assert-string command).

 

Arguments:                         One argument; a pointer to a string containing a list of primitive data types (symbols, strings, integers, floats, and/or instance names).

 

Returns:                              A generic pointer to a fact structure.

 

Other:                                  This function can trigger garbage collection.

 

WARNING:                       If the return value from AssertString is stored as part of a persistent data structure or in a static data area, then the function IncrementFactCount should be called to insure that the fact cannot be disposed while external references to the fact still exist.

 

Examples

If the following deftemplate has been processed by CLIPS,

 

(deftemplate example

   (multislot v)

   (slot w (default 9))

   (slot x)

   (slot y)

   (multislot z))

 

then the following fact

 

(example (x 3) (y red) (z 1.5 b))

 

can be added to the fact-list using the function shown below.

 

void AddExampleFact1()

  {

   AssertString("(example (x 3) (y red) (z 1.5 b))");

  }

 

To construct a string based on variable data, use the C library function sprintf as shown following.

 

void VariableFactAssert(

  int number,

  char *status)

  {

   char tempBuffer[50];

   sprintf(tempBuffer,"(example (x %d) (y %s))",number,status);

   AssertString(tempBuffer);

  }

4.4.3 AssignFactSlotDefaults

    int AssignFactSlotDefaults(theFact);

    void *theFact;

 

Purpose:                              Assigns default values to a fact.

 

Arguments:                         A generic pointer to a fact data structure.

 

Returns:                              Boolean value. TRUE if the default values were successfully set, otherwise FALSE.

4.4.4 CreateFact

    void *CreateFact(deftemplatePtr);

    void *deftemplatePtr;

 

Purpose:                              Function CreateFact returns a pointer to a fact structure with factSize fields. Once this fact structure is obtained, the fields of the fact can be given values by using  PutFactSlot and AssignFactSlotDefaults. Function Assert should be called when the fact is ready to be asserted.

 

Arguments:                         A generic pointer to a deftemplate data structure (which indicates the type of fact being created).

 

Returns:                              A generic pointer to a fact data structure.

 

Other:                                  Use the CreateFact function to create a new fact and then the PutFactSlot function to set one or more slot values. The AssignFactSlotDefaults function is then used to assign default values for slots not set with the PutFactSlot function. Finally, the Assert function is called with the new fact.

 

                                             Since CreateFact requires a generic deftemplate pointer, it is not possible to use it to create ordered facts unless the associated implied deftemplate has already been created. In cases where the implied deftemplate has not been created, the function AssertString can be used to create ordered facts.

 

                                             This function allows individual fields of a fact to be assigned under programmer control. This is useful, for example, if a fact asserted from an external function needs to contain an external address or an instance address (since the function AssertString does not permit these data types). For most situations in which a fact needs to be asserted, however, the AssertString function should be preferred (it is slighter slower than using the CreateFact and Assert functions, but it is much easier to use and less prone to being used incorrectly).

                                            

Examples

If the following deftemplate has been processed by CLIPS,

 

(deftemplate example

   (multislot v)

   (slot w (default 9))

   (slot x)

   (slot y)

   (multislot z))

 

then the following fact

 

(example (x 3) (y red) (z 1.5 b))

 

can be added to the fact-list using the function shown below.

 

void AddExampleFact2()

  {

   void *newFact;

   void *templatePtr;

   void *theMultifield;

   DATA_OBJECT theValue;

 

   /*============================================================*/

   /* Disable garbage collection. It's only necessary to disable */

   /* garbage collection when calls are made into CLIPS from an  */

   /* embedding program. It's not necessary to do this when the  */

   /* the calls to user code are made by CLIPS (such as for      */

   /* user-defined functions) or in the case of this example,    */

   /* there are no calls to functions which can trigger garbage  */

   /* collection (such as Send or FunctionCall.                  */

   /*============================================================*/

 

   IncrementGCLocks();

 

   /*==================*/

   /* Create the fact. */

   /*==================*/

  

   templatePtr = FindDeftemplate("example");

   newFact = CreateFact(templatePtr);

   if (newFact == NULL) return;

  

   /*==============================*/

   /* Set the value of the x slot. */

   /*==============================*/

  

   theValue.type = INTEGER;

   theValue.value = AddLong(3);

   PutFactSlot(newFact,"x",&theValue);

  

   /*==============================*/

   /* Set the value of the y slot. */

   /*==============================*/

  

   theValue.type = SYMBOL;

   theValue.value = AddSymbol("red");

   PutFactSlot(newFact,"y",&theValue);

  

   /*==============================*/

   /* Set the value of the z slot. */

   /*==============================*/

  

   theMultifield = CreateMultifield(2);

   SetMFType(theMultifield,1,FLOAT);

   SetMFValue(theMultifield,1,AddDouble(1.5));

   SetMFType(theMultifield,2,SYMBOL);

   SetMFValue(theMultifield,2,AddSymbol("b"));

   SetDOBegin(theValue,1);

   SetDOEnd(theValue,2);

 

   theValue.type = MULTIFIELD;

   theValue.value = theMultifield;

   PutFactSlot(newFact,"z",&theValue);

  

   /*=================================*/

   /* Assign default values since all */

   /* slots were not initialized.     */

   /*=================================*/

  

   AssignFactSlotDefaults(newFact);

 

   /*==========================================================*/

   /* Enable garbage collection. Each call to IncrementGCLocks */

   /* should have a corresponding call to DecrementGCLocks.    */

   /*==========================================================*/

 

   DecrementGCLocks();

 

   /*==================*/

   /* Assert the fact. */

   /*==================*/

  

   Assert(newFact);

  }

4.4.5 DecrementFactCount

    void DecrementFactCount(factPtr);
    void *factPtr;

 

Purpose:                              This function should only be called to reverse the effects of a previous call to IncrementFactCount. As long as an fact's count is greater than zero, the memory allocated to it cannot be released for other use.

 

Arguments:                         A generic pointer to a fact.

                                            

Returns:                              No meaningful return value.

4.4.6 FactDeftemplate

    void *FactDeftemplate(factPtr);
    void *factPtr;

 

Purpose:                              Returns the deftemplate associated with a fact.

 

Arguments:                        A generic pointer to a fact data structure.

 

Returns:                              Returns a generic pointer to the deftemplate data structure associated with the fact.

4.4.7 FactExistp

    long  FactExistp(factPtr);

    void *factPtr;

 

Purpose:                              Indicates whether a fact is still in the fact-list or has been retracted (the C equivalent of the CLIPS fact-existp function).

 

Arguments:                        1)   A generic pointer to a fact data structure.

 

Returns:                              An integer; zero (0) if the fact is not in the fact-list, other­wise a one (1).

4.4.8 FactIndex

    long int FactIndex(factPtr);

    void *factPtr;

 

Purpose:                              Returns the fact index of a fact (the C equivalent of the CLIPS fact-index command).

 

Arguments:                         A generic pointer to a fact data structure.

 

Returns:                              A long integer (the fact-index of the fact).

4.4.9 Facts

    void Facts(logicalName,theModule,start,end,max);

   char *logicalName;

   void *theModule;

   long start, end, max;

 

Purpose:                              Prints the list of all facts currently in the fact‑list (the C equivalent of the CLIPS facts command). Output is sent to the logical name wdisplay.

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the facts to be listed (all facts visible to that module). A NULL pointer indicates that all facts in all modules should be listed.

                                             3)   The start index of the facts to be listed. Facts with indices less than this value are not listed. A value of -1 indicates that the argument is unspecified and should not restrict the facts printed.

                                             4)   The end index of the facts to be listed. Facts with indices greater than this value are not listed. A value of -1 indicates that the argument is unspecified and should not restrict the facts printed.

                                             5)   The maximum number of facts to be listed. Facts in excess of this limit are not listed. A value of -1 indicates that the argument is unspecified and should not restrict the facts printed.

 

Returns:                              No meaningful return value.

4.4.10 FactSlotNames

    void FactSlotNames(factPtr,&theValue);

    void *factPtr;

    DATA_OBJECT slotNames;

 

Purpose:                              Retrieves the list of slot names associated with a fact (the C equivalent of the CLIPS fact-slot-names function).

 

Arguments:                        1)   A generic pointer to a fact data structure.

                                             2)   A pointer to a DATA_OBJECT in which to place a multifield value containing the factÕs slot name symbols. For ordered facts, a multifield value containing the single symbol implied is returned. See sections 3.2.3 and 3.2.4 for information on getting the value stored in a DATA_OBJECT.

 

Returns:                              No meaningful value.

4.4.11 GetFactDuplication

    int   GetFactDuplication();

 

Purpose:                              Returns the current  value of the fact duplication behavior (the C equivalent of the CLIPS get-fact-duplication command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.4.12 GetFactList

 

    void GetFactList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of facts visible to the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-fact-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the deffacts names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.4.13 GetFactListChanged

    int GetFactListChanged();

Purpose:                              Determines if any changes to the fact list have occurred. If this function returns a non-zero integer, it is the user's responsibility to call SetFactListChanged(0) to reset the internal flag. Otherwise, this function will continue to return non-zero even when no changes have occurred. This function is primarily used to determine when to update a display tracking the fact list.

 

Arguments:                         None.

 

Returns:                              0 if no changes to the fact list have occurred, non-zero otherwise.

4.4.14 GetFactPPForm

    void  GetFactPPForm(buffer,bufferLength,factPtr);

    char *buffer;

    unsigned bufferLength;

    void *factPtr;

 

Purpose:                              Returns the pretty print representation of a fact in the caller's buffer.

 

Arguments:                        1)   A pointer to the caller's character buffer.

                                             2)   The maximum number of characters which could be stored in the caller's buffer (not including space for the terminating null character).

                                             3)   A generic pointer to a fact data structure.

 

Returns:                              No meaningful return value. The fact pretty print form is stored in the caller's buffer.

4.4.15 GetFactSlot

    int GetFactSlot(factPtr,slotName,&theValue);

    void *factPtr;

    char *slotName;

    DATA_OBJECT theValue;

 

Purpose:                              Retrieves a slot value from a fact.

 

Arguments:                        1)   A generic pointer to a fact data structure.

                                             2)   The name of the slot to be retrieved (NULL should be used for the implied multifield slot of an implied deftemplate).

                                             3)   A pointer to a DATA_OBJECT in which to place the slotÕs value. See sections 3.2.3 and 3.2.4 for information on getting the value stored in a DATA_OBJECT.

 

Returns:                              Boolean value. TRUE if the slot value was successfully retrieved, otherwise FALSE.

4.4.16 GetNextFact

    void *GetNextFact(factPtr);

    void *factPtr;

 

Purpose:                              Provides access to the fact-list.

 

Arguments:                         A generic pointer to a fact data structure (or NULL to get the first fact in the fact-list).

 

Returns:                              A generic pointer to the first fact in the fact-list if factPtr is NULL, otherwise a generic pointer to the fact immediately following factPtr in the fact-list. If factPtr is the last fact in the fact-list, then NULL is returned.

 

Other:                                  Once this generic pointer to the fact structure is obtained, the fields of the fact can be examined by using the macros GetMFType and GetMFValue. The values of a fact obtained using this function should never be changed. See CreateFact for details on accessing deftemplate facts.

 

WARNING:                       Do not call this function with a pointer to a fact that has been retracted. If the return value from GetNextFact is stored as part of a persistent data structure or in a static data area, then the function IncrementFactCount should be called to insure that the fact cannot be disposed while external references to the fact still exist.

4.4.17 GetNextFactInTemplate

    void *GetNextFactInTemplate(templatePtr,factPtr);

    void *templatePtr;

    void *factPtr;

 

Purpose:                              Provides access to the list of facts for a particular deftemplate.

 

Arguments:                        1)   A generic pointer to a deftemplate.

                                             2)   A generic pointer to a fact data structure (or NULL to get the first fact from the deftemplateÕs fact-list).

 

Returns:                              A generic pointer to the first fact of the specified deftemplate if factPtr is NULL, otherwise a generic pointer to the next fact of the specified deftemplate immediately following factPtr. If factPtr is the last fact belonging to the deftemplate, then NULL is returned.

 

Other:                                  Once this generic pointer to the fact structure is obtained, the fields of the fact can be examined by using the macros GetMFType and GetMFValue. The values of a fact obtained using this function should never be changed. See CreateFact for details on accessing deftemplate facts.

 

WARNING:                       Do not call this function with a pointer to a fact that has been retracted. If the return value from GetNextFactInTemplate is stored as part of a persistent data structure or in a static data area, then the function IncrementFactCount should be called to insure that the fact cannot be disposed while external references to the fact still exist.

4.4.18 IncrementFactCount

    void IncrementFactCount(factPtr);
    void *factPtr;

 

Purpose:                              This function should be called for each external copy of  pointer to a fact to let CLIPS know that such an outstanding external reference exists. As long as an fact's count is greater than zero, CLIPS will not release its memory because there may be outstanding pointers to the fact. However, the fact can still be functionally retracted, i.e. the fact will appear to no longer be in the fact-list. The fact address always can be safely examined using the fact access functions as long as the count for the fact is greater than zero. Retracting an already retracted fact will have no effect, however, the function AddFact should not be called twice for the same pointer created using CreateFact. Note that this function only needs to be called if you are storing pointers to facts that may later be referenced by external code after the fact has been retracted.

 

Arguments:                         A generic pointer to a fact.

                                            

Returns:                              No meaningful return value.

4.4.19 LoadFacts

    int   LoadFacts(fileName);
    char *fileName;

 

Purpose:                              Loads a set of facts into the CLIPS data base (the C equivalent of the CLIPS load-facts command).

 

Arguments:                         A string representing the name of the file.

 

Returns:                              Returns an integer; if zero, an error occurred while opening the file. If non‑zero no errors were detected while performing the load.

4.4.20 LoadFactsFromString

    int   LoadFactsFromString(inputString,maximumPosition);
    char *inputString;

   int maximumPosition;

 

Purpose:                              Loads a set of facts into the CLIPS data base using a string as the input source (in a manner similar to the CLIPS load-facts command).

 

Arguments:                        1)   A string containing the fact definitions to be loaded.

                                             2)   The maximum number of characters to be read from the string. A value of -1 indicates the entire string.

 

Returns:                              Returns an integer; if zero, an error occurred while processing the string.

4.4.21 PPFact

    void   PPFact(factPtr,logicalName,ignoreDefaultFlag);
    void *factPtr;

   char *logicalName;

   int ignoreDefaultsFlag;

 

Purpose:                              Displays a single fact (the C equivalent of the CLIPS ppfact command).

 

Arguments:                        1)   A generic pointer to a fact.

                                             2)   The logical name to which the listing output is sent.

                                             3)   The integer 1 to exclude slots from display where the current value is the same as the static default, otherwise the integer 0 to display all slots regardless of their current value.

 

Returns:                              No meaningful return value.

4.4.22 PutFactSlot

    int PutFactSlot(factPtr,slotName,&theValue);

    void *factPtr;

    char *slotName;

    DATA_OBJECT theValue;

 

Purpose:                              Sets the slot value of a fact.

 

Arguments:                        1)   A generic pointer to a fact data structure.

                                             2)   The name of the slot to be set (NULL should be used for the implied multifield slot of an implied deftemplate).

                                             3)   A pointer to a DATA_OBJECT that contains the slotÕs new value. A multifield or implied multifield slot should only be passed a multifield value. A single field slot should only be passed a single field value. See sections 3.3.3 and 3.3.4 for information on setting the value stored in a DATA_OBJECT.

 

Returns:                              Boolean value. TRUE if the slot value was successfully set, otherwise FALSE.

 

Warning:                             Do not use this function to change the slot value of a fact that has already been asserted. This function should only be used on facts created using CreateFact.

4.4.23 Retract

    int Retract(factPtr);
    void *factPtr;

 

Purpose:                              Retracts a fact from the CLIPS fact‑list (the C equivalent of the CLIPS retract command).

 

Arguments:                         A generic pointer to a fact structure (usually captured as the return value from a call to AssertString or Assert). If the NULL pointer is used, then all facts will  be retracted.

 

Returns:                              An integer; zero (0) if fact already has been retracted, other­wise a one (1).

 

Other:                                  The caller of RetractFact is responsible for insuring that the fact passed as an argument is still valid. The functions IncrementFactCount and DecrementFactCount can be used to inform CLIPS whether a fact is still in use.

 

This function can trigger garbage collection.

4.4.24 SaveFacts

    int   SaveFacts(fileName,saveScope,NULL);
    char *fileName;

   int   saveScope;

 

Purpose:                              Saves the facts in the fact‑list to the specified file (the C equivalent of the CLIPS save-facts command).

 

Arguments:                         A string representing the name of the file and an integer constant representing the scope for the facts being saved which should be either LOCAL_SAVE or VISIBLE_SAVE. The third argument is used internally by the CLIPS save‑facts command and should be set to NULL when called from user code.

 

Returns:                              Returns an integer; if zero, an error occurred while opening the file. If non‑zero no errors were detected while performing the save.

4.4.25 SetFactDuplication

    int   SetFactDuplication(value);

    int   value;

 

Purpose:                              Sets the fact duplication behavior (the C equivalent of the CLIPS set‑fact‑duplication command). When this behavior is disabled (by default), asserting a duplicate of a fact already in the fact‑list produces no effect. When enabled, the duplicate fact is asserted with a new fact‑index.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.4.26 SetFactListChanged

    void SetFactListChanged(changedFlag);

    int changedFlag;

Purpose:                              Sets the internal boolean flag which indicates when changes to the fact list have occurred. This function is normally used to reset the flag to zero after GetFactListChanged() returns non-zero.

 

Arguments:                         An integer indicating whether changes in the fact list have occurred (non-zero) or not (0).

 

Returns:                              Nothing useful.

4.5 Deffacts Functions

The following function calls are used for manipulating deffacts.

4.5.1 DeffactsModule

    char *DeffactsModule(theDeffacts);

    void *theDeffacts;

 

Purpose:                              Returns the module in which a deffacts is defined (the C equivalent of the CLIPS deffacts-module command).

 

Arguments:                        A generic pointer to a deffacts.

 

Returns:                              A string containing the name of the module in which the deffacts is defined.

4.5.2 FindDeffacts

    void *FindDeffacts(deffactsName);

    char *deffactsName;

 

Purpose:                              Returns a generic pointer to a named deffacts.

 

Arguments:                         The name of the deffacts to be found.

 

Returns:                              A generic pointer to the named deffacts if it exists, otherwise NULL.

4.5.3 GetDeffactsList

 

    void GetDeffactsList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of deffacts in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-deffacts-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the deffacts names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.5.4 GetDeffactsName

    char *GetDeffactsName(deffactsPtr);

    void *deffactsPtr;

 

Purpose:                              Returns the name of a deffacts.

 

Arguments:                         A generic pointer to a deffacts data structure.

 

Returns:                              A string containing the name of the deffacts.

4.5.5 GetDeffactsPPForm

    char *GetDeffactsPPForm(deffactsPtr);

    void *deffactsPtr;

 

Purpose:                              Returns the pretty print representation of a deffacts.

 

Arguments:                         A generic pointer to a deffacts data structure.

 

Returns:                              A string containing the pretty print representation of the deffacts (or the NULL pointer if no pretty print representation exists).

4.5.6 GetNextDeffacts

    void *GetNextDeffacts(deffactsPtr);

    void *deffactsPtr;

 

Purpose:                              Provides access to the list of deffacts.

 

Arguments:                         A generic pointer to a deffacts data structure (or NULL to get the first deffacts).

 

Returns:                              A generic pointer to the first deffacts in the list of deffacts if deffactsPtr is NULL, otherwise a generic pointer to the deffacts immediately following deffactsPtr in the list of deffacts. If deffactsPtr is the last deffacts in the list of deffacts, then NULL is returned.

4.5.7 IsDeffactsDeletable

    int   IsDeffactsDeletable(deffactsPtr);
    void *deffactsPtr;

 

Purpose:                              Indicates whether or not a particular deffacts can be deleted.

 

Arguments:                         A generic pointer to a deffacts data structure.

 

Returns:                              An integer; zero (0) if the deffacts cannot be deleted, otherwise a one (1).

4.5.8 ListDeffacts

    void ListDeffacts(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of deffacts (the C equivalent of the CLIPS list‑deffacts command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the deffacts to be listed. A NULL pointer indicates that deffacts in all modules should be listed.

 

Returns:                              No meaningful return value.

4.5.9 Undeffacts

    int   Undeffacts(deffactsPtr);

    void *deffactsPtr;

 

Purpose:                              Removes a deffacts construct from CLIPS (the C equivalent of the CLIPS undeffacts command).

 

Arguments:                         A generic pointer to a deffacts data structure. If the NULL pointer is used, then all deffacts will be deleted.

 

Returns:                              An integer; zero (0) if the deffacts could not be deleted, otherwise a one (1).

 

Other:                                  This function can trigger garbage collection.

4.6 Defrule Functions

The following function calls are used for manipulating defrules.

4.6.1 DefruleHasBreakpoint

    int  DefruleHasBreakpoint(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Indicates whether or not a particular defrule has a breakpoint set.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; one (1) if a breakpoint exists for the rule, otherwise a zero (0).

4.6.2 DefruleModule

    char *DefruleModule(theDefrule);

    void *theDefrule;

 

Purpose:                              Returns the module in which a defrule is defined (the C equivalent of the CLIPS defrule-module command).

 

Arguments:                        A generic pointer to a defrule.

 

Returns:                              A string containing the name of the module in which the defrule is defined.

4.6.3 FindDefrule

    void *FindDefrule(defruleName);

    char *defruleName;

 

Purpose:                              Returns a generic pointer to a named defrule.

 

Arguments:                         The name of the defrule to be found.

 

Returns:                              A generic pointer to the named defrule if it exists, otherwise NULL.

4.6.4 GetDefruleList

    void GetDefruleList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of defrules in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-defrule-list function)..

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the defrule names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.6.5 GetDefruleName

    char *GetDefruleName(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Returns the name of a defrule.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              A string containing the name of the defrule.

4.6.6 GetDefrulePPForm

    char *GetDefrulePPForm(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Returns the pretty print representation of a defrule.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              A string containing the pretty print representation of the defrule (or the NULL pointer if no pretty print representation exists).

4.6.7 GetDefruleWatchActivations

    unsigned GetDefruleWatchActivations(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Indicates whether or not a particular defrule is being watched for activations.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; one (1) if the defrule is being watched for activations, otherwise a zero (0).

4.6.8 GetDefruleWatchFirings

    unsigned GetDefruleWatchFirings(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Indicates whether or not a particular defrule is being watched for rule firings.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; one (1) if the defrule is being watched for rule firings, otherwise a zero (0).

4.6.9 GetIncrementalReset

    int   GetIncrementalReset();

 

Purpose:                              Returns the current  value of the incremental reset behavior (the C equivalent of the CLIPS get-incremental-reset command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if the behavior is disabled and TRUE (1) if the behavior is enabled.

4.6.10 GetNextDefrule

    void *GetNextDefrule(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Provides access to the list of defrules.

 

Arguments:                         A generic pointer to a defrule data structure (or NULL to get the first defrule).

 

Returns:                              A generic pointer to the first defrule in the list of defrules if defrulePtr is NULL, otherwise a generic pointer to the defrule immediately following defrulePtr in the list of defrules. If defrulePtr is the last defrule in the list of defrules, then NULL is returned.

4.6.11 IsDefruleDeletable

    int   IsDefruleDeletable(defrulePtr);
    void *defrulePtr;

 

Purpose:                              Indicates whether or not a particular defrule can be deleted.

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; zero (0) if the defrule cannot be deleted, otherwise a one (1).

4.6.12 ListDefrules

    void ListDefrules(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of defrules (the C equivalent of the CLIPS list‑defrules command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the defrules to be listed. A NULL pointer indicates that defrules in all modules should be listed.

 

Returns:                              No meaningful return value.

4.6.13 Matches

    int Matches(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Prints the partial matches and activations of a defrule (the C equivalent of the CLIPS matches command).

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; zero (0) if the rule was not found, otherwise a one (1).

4.6.14 Refresh

    int   Refresh(defrulePtr);
    void *defrulePtr;

 

Purpose:                              Refreshes a rule (the C equivalent of the CLIPS refresh command).

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; zero (0) if the rule was not found, otherwise a one (1).

4.6.15 RemoveBreak

    int RemoveBreak(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Removes a breakpoint for the specified defrule (the C equivalent of the CLIPS remove-break command).

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              An integer; zero (0) if a breakpoint did not exist for the rule, otherwise a one (1).

4.6.16 SetBreak

    void SetBreak(defrulePtr);

    void *defrulePtr;

 

Purpose:                              Adds a breakpoint for the specified defrule (the C equivalent of the CLIPS set-break command).

 

Arguments:                         A generic pointer to a defrule data structure.

 

Returns:                              No meaningful return value.

4.6.17 SetDefruleWatchActivations

    void SetDefruleWatchActivations(newState,defrulePtr);

    unsigned    newState;

   void *defrulePtr;

 

Purpose:                              Sets the activations watch item for a specific defrule.

 

Arguments:                         The new activations watch state and a generic pointer to a defrule data structure.

4.6.18 SetDefruleWatchFirings

    void SetDefruleWatchFirings(newState,defrulePtr);

    unsigned    newState;

   void *defrulePtr;

 

Purpose:                              Sets the rule firing watch item for a specific defrule.

 

Arguments:                         The new rule firing watch state and a generic pointer to a defrule data structure.

4.6.19 SetIncrementalReset

    int   SetIncrementalReset(value);

    int   value;

 

Purpose:                              Sets the incremental reset behavior. When this behavior is enabled (by default), newly defined rules are update based upon the current state of the fact‑list. When disabled, newly defined rules are only updated by facts added after the rule is defined (the C equivalent of the CLIPS set-incremental-reset command).

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.6.20 ShowBreaks

    void ShowBreaks(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of all rule breakpoints (the C equivalent of the CLIPS show-breaks command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module for which the breakpoints are to be listed. A NULL pointer indicates that the the breakpoints in all modules should be listed.

 

Returns:                              No meaningful return value.

4.6.21 Undefrule

    int   Undefrule(defrulePtr);
    void *defrulePtr;

 

Purpose:                              Removes a defrule from CLIPS (the C equivalent of the CLIPS undefrule command).

 

Arguments:                         A generic pointer to a defrule data structure. If the NULL pointer is used, then all defrules will be deleted.

 

Returns:                              An integer; zero (0) if the defrule could not be deleted, otherwise a one (1).

 

Other:                                  This function can trigger garbage collection.

4.7 Agenda Functions

The following function calls are used for manipulating the agenda.

4.7.1 AddRunFunction

    int    AddRunFunction(runItemName,runFunction,priority);
    char  *runItemName;

    void (*runFunction)();

    int    priority;

 

    void runFunction();

 

Purpose:                              Allows a user-defined function to be called after each rule firing. Such a feature is useful, for example, when bringing data in from some type of external device which does not operate in a synchronous manner. A user may define an external function which will be called by CLIPS after every rule is fired to check for the existence of new data.

 

Arguments:                        1)   The name associated with the user‑defined run function. This name is used by the function RemoveRunFunction.

                                             2)   A pointer to the user-defined function which is to be called after every rule firing. This function must except an environment pointer if the environment companion function is used (see section 9.2).

                                             3)   The priority of the run item which determines the order in which run items are called (higher priority items are called first). The values -2000 to 2000 are reserved for CLIPS system defined run items and should not be used for user defined run items.

 

Returns:                              Returns a zero value if the run item could not be added, otherwise a non-zero value is returned.

 

Example

This following function checks to see if a key on the keyboard has been hit. If a key has been hit, then the fact (stop-processing) is asserted into the fact-list.

 

void CheckKB()

  {

   if (CheckKeyboardStatus() == KB_HIT)

     { AssertString("stop‑processing"); }

  }

 

This function can now be added to the list of functions called after every rule firing by making the following function call.

 

AddRunFunction("check‑kb",checkKB,3000);

4.7.2 Agenda

    void Agenda(logicalName,theModule)

   char *logicalName;

   void *theModule;

 

Purpose:                              Prints the list of rules currently on the agenda (the C equivalent of the CLIPS agenda command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the agenda to be listed. A NULL pointer indicates that the agendas of all modules should be listed.

 

Returns:                              No meaningful return value.

4.7.3 ClearFocusStack

    void ClearFocusStack();

 

Purpose:                              Removes all modules from the focus stack (the C equivalent of the CLIPS clear-focus-stack command).

 

Arguments:                         None.

 

Returns:                              No meaningful return value.

4.7.4 DeleteActivation

    int   DeleteActivation(activationPtr);
    void *activationPtr;

 

Purpose:                              Removes an activation from the agenda.

 

Arguments:                         A generic pointer to an activation data structure. If the NULL pointer is used, then all activations will be deleted.

 

Returns:                              An integer; zero (0) if the activation could not be deleted, otherwise a one (1).

4.7.5 Focus

    void Focus(defmodulePtr);

    void *defmodulePtr;

 

Purpose:                              Sets the current focus (the C equivalent of the CLIPS  focus command).

 

Arguments:                         A generic pointer to a defmodule data structure.

 

Returns:                              No meaningful value.

4.7.6 GetActivationName

    char *GetActivationName(activationPtr);

    void *activationPtr;

 

Purpose:                              Returns the name of the defrule from which the activation was generated.

 

Arguments:                         A generic pointer to an activation data structure.

 

Returns:                              A string containing a defrule name.

4.7.7 GetActivationPPForm

    void  GetActivationPPForm(buffer,bufferLength,activationPtr);

    char *buffer;

    unsigned   bufferLength;

    void *activationPtr;

 

Purpose:                              Returns the pretty print representation of an agenda activation in the caller's buffer.

 

Arguments:                        1)   A pointer to the caller's character buffer.

                                             2)   The maximum number of characters which could be stored in the caller's buffer (not including space for the terminating null character).

                                             3)   A generic pointer to an activation data structure.

4.7.8 GetActivationSalience

    int   GetActivationSalience(activationPtr);

    void *activationPtr;

 

Purpose:                              Returns the salience value associated with an activation. This salience value may be different from the the salience value of the defrule which generated the activation (due to dynamic salience).

 

Arguments:                         A generic pointer to an activation data structure.

 

Returns:                              The integer salience value of an activation.

4.7.9 GetAgendaChanged

    int GetAgendaChanged();

Purpose:                              Determines if any changes to the agenda of rule activations have occurred. If this function returns a non-zero integer, it is the user's responsibility to call SetAgendaChanged(0) to reset the internal flag. Otherwise, this function will continue to return non-zero even when no changes have occurred. This function is primarily used to determine when to update a display tracking rule activations.

 

Arguments:                         None.

 

Returns:                              0 if no changes to the agenda have occurred, non-zero otherwise.

4.7.10 GetFocus

    void *GetFocus();

 

Purpose:                              Returns the module associated with the current focus (the C equivalent of the CLIPS  get-focus function).

 

Arguments:                         None.

 

Returns:                              A generic pointer to a defmodule data structure (or NULL if the focus stack is empty).

4.7.11 GetFocusStack

    void GetFocusStack(&returnValue);

   DATA_OBJECT returnValue;

 

Purpose:                              Returns the module names in the focus stack as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-focus-stack function).

 

Arguments:                         A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the defrule names from the list.

4.7.12 GetNextActivation

    void *GetNextActivation(activationPtr);

    void *activationPtr;

 

Purpose:                              Provides access to the list of activations on the agenda.

 

Arguments:                         A generic pointer to an activation data structure (or NULL to get the first activation on the agenda).

 

Returns:                              A generic pointer to the first activation on the agenda if activationPtr is NULL, otherwise a generic pointer to the activation immediately following activationPtr on the agenda. If activationPtr is the last activation on the agenda, then NULL is returned.

4.7.13 GetSalienceEvaluation

    int   GetSalienceEvaluation();

 

Purpose:                              Returns the current  salience evaluation behavior (the C equivalent of the CLIPS get-salience-evaluation command).

 

Arguments:                         None.

 

Returns:                              An integer (see SetSalienceEvaluation for the list of defined constants).

4.7.14 GetStrategy

    int   GetStrategy();

 

Purpose:                              Returns the current  conflict resolution strategy (the C equivalent of the CLIPS get-strategy command).

 

Arguments:                         None.

 

Returns:                              An integer (see SetStrategy for the list of defined strategy constants).

4.7.15 ListFocusStack

    void ListFocusStack(logicalName);

    char *logicalName;

 

Purpose:                              Prints the current focus stack (the C equivalent of the CLIPS list-focus-stack command).

 

Arguments:                         The logical name to which the listing output is sent.

 

Returns:                              No meaningful return value.

4.7.16 PopFocus

    void *PopFocus();

 

Purpose:                              Removes the current focus from the focus stack and returns the module associated with that focus (the C equivalent of the CLIPS  pop-focus function).

 

Arguments:                         None.

 

Returns:                              A generic pointer to a defmodule data structure.

4.7.17 RefreshAgenda

    void RefreshAgenda(theModule);

    void *theModule;

 

Purpose:                              Recomputes the salience values for all activations on the agenda and then reorders the agenda (the C equivalent of the CLIPS refresh-agenda command).

 

Arguments:                         A generic pointer to the module containing the agenda to be refreshed. A NULL pointer indicates that the agendas of all modules should be refreshed.

 

Returns:                              No meaningful return value.run

4.7.18 RemoveRunFunction

    int   RemoveRunFunction(runItemName);

    char *runItemName;

 

 

Purpose:                              Removes a named function from the list of functions to be called after every rule firing.

 

Arguments:                         The name associated with the user‑defined run function. This is the same name that was used when the run function was added with the function AddRunFunction.

 

Returns:                              Returns the integer value 1 if the named function was found and removed, otherwise 0 is returned.

4.7.19 ReorderAgenda

    void ReorderAgenda(theModule);

    void *theModule;

 

Purpose:                              Reorders the agenda based on the current conflict resolution strategy and current activation saliences.

 

Arguments:                         A generic pointer to the module containing the agenda to be reordered. A NULL pointer indicates that the agendas of all modules should be reordered.

 

Returns:                              No meaningful return value.

4.7.20 Run

    long int Run(runLimit);
    long int runLimit;

 

Purpose:                              Allows rules to execute  (the C equivalent of the CLIPS run command).

 

Arguments:                         An integer which defines how many rules should fire before returning. If runLimit is a negative integer, rules will fire until the agenda is empty.

 

Returns:                              Returns an integer value; the number of rules that were fired.

4.7.21 SetActivationSalience

    int   SetActivationSalience(activationPtr,newSalience);

    void *activationPtr;

    int   newSalience;

 

Purpose:                              Sets the salience value of an activation. The salience value of the defrule which generated the activation is unchanged.

 

Arguments:                        1)   A generic pointer to an activation data structure.

                                             2)   The new salience value (which is not restricted to the ‑10000 to +10000 range).

 

Returns:                              The old salience value of the activation.

 

Other:                                  The function ReorderAgenda should be called after salience values have been changed to update the agenda.

4.7.22 SetAgendaChanged

    void SetAgendaChanged(changedFlag);

    int changedFlag;

Purpose:                              Sets the internal boolean flag which indicates when changes to the agenda of rule activations have occurred. This function is normally used to reset the flag to zero after GetAgendaChanged() returns non-zero.

 

Arguments:                         An integer indicating whether changes in the agenda have occurred (non-zero) or not (0).

 

Returns:                              Nothing useful.

4.7.23 SetSalienceEvaluation

    int   SetSalienceEvaluation(value);

    int   value;

 

Purpose:                              Sets the salience evaluation behavior (the C equivalent of the CLIPS set-salience-evaluation command).

 

Arguments:                         The new value for the behavior – one of the following defined integer constants:


WHEN_DEFINED
WHEN_ACTIVATED
EVERY_CYCLE

 

Returns:                              Returns the old value for the behavior.

4.7.24 SetStrategy

    int   SetStrategy(value);

    int   value;

 

Purpose:                              Sets the conflict resolution strategy (the C equivalent of the CLIPS set-strategy command).

 

Arguments:                         The new value for the behavior – one of the following defined integer constants:


DEPTH_STRATEGY
BREADTH_STRATEGY
LEX_STRATEGY
MEA_STRATEGY
COMPLEXITY_STRATEGY
SIMPLICITY_STRATEGY
RANDOM_STRATEGY

 

Returns:                              Returns the old value for the strategy.

4.8 Defglobal Functions

The following function calls are used for manipulating defglobals.

4.8.1 DefglobalModule

    char *DefglobalModule(theDefglobal);

    void *theDefglobal;

 

Purpose:                              Returns the module in which a defglobal is defined (the C equivalent of the CLIPS defglobal-module command).

 

Arguments:                        A generic pointer to a defglobal.

 

Returns:                              A string containing the name of the module in which the defglobal is defined.

4.8.2 FindDefglobal

    void *FindDefglobal(globalName);

    char *globalName;

 

Purpose:                              Returns a generic pointer to a named defglobal.

 

Arguments:                         The name of the defglobal to be found (e.g. x for ?*x*).

 

Returns:                              A generic pointer to the named defglobal if it exists, otherwise NULL.

4.8.3 GetDefglobalList

    void GetDefglobalList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of defglobals in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-defglobal-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the defglobal names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.8.4 GetDefglobalName

    char *GetDefglobalName(defglobalPtr);

    void *defglobalPtr;

 

Purpose:                              Returns the name of a defglobal.

 

Arguments:                         A generic pointer to a defglobal data structure.

 

Returns:                              A string containing the name of the defglobal (e.g. x for ?*x*).

4.8.5 GetDefglobalPPForm

    char *GetDefglobalPPForm(defglobalPtr);

    void *defglobalPtr;

 

Purpose:                              Returns the pretty print representation of a defglobal.

 

Arguments:                        A generic pointer to a defglobal data structure.

 

Returns:                              A string containing the pretty print representation of the defglobal (or the NULL pointer if no pretty print representation exists).

4.8.6 GetDefglobalValue

    int   GetDefglobalValue(globalName,&vPtr);

    char *globalName;

    DATA_OBJECT vPtr;

 

Purpose:                              Returns the value of a defglobal.

 

Arguments:                        1)   The name of the global variable to be retrieved (e.g. y for ?*y*).

                                             2)   A pointer to a DATA_OBJECT in which the value is stored (see sections 3.2.3 and 3.3.4 for details on this data structure).

 

Returns:                              An integer; zero (0) if the defglobal was not found, other­wise a one (1). The DATA_OBJECT vPtr is assigned the current value of the defglobal.

4.8.7 GetDefglobalValueForm

    void  GetDefglobalValueForm(buffer,bufferLength,defglobalPtr);

    char *buffer;

    unsigned   bufferLength;

    void *defglobalPtr;

 

Purpose:                              Returns a printed representation of a defglobal and its current value in the caller's buffer. For example,

 

                                             ?*x* = 5

 

Arguments:                        1)   A pointer to the callerÕs character buffer.

                                             2)   The maximum number of characters which could be stored in the caller's buffer (not including space for the terminating null character).

                                             3)   A generic pointer to a defglobal data structure.

4.8.8 GetDefglobalWatch

    unsigned GetDefglobalWatch(defglobalPtr);

    void *defglobalPtr;

 

Purpose:                              Indicates whether or not a particular defglobal is being watched.

 

Arguments:                         A generic pointer to a defglobal data structure.

 

Returns:                              An integer; one (1) if the defglobal is being watched, otherwise a zero (0).

4.8.9 GetGlobalsChanged

    int GetGlobalsChanged();

Purpose:                              Determines if any changes to global variables have occurred. If this function returns a non-zero integer, it is the user's responsibility to call SetGlobalsChanged(0) to reset the internal flag. Otherwise, this function will continue to return non-zero even when no changes have occurred. This function is primarily used to determine when to update a display tracking global variables.

 

Arguments:                         None.

 

Returns:                              0 if no changes to global variables have occurred, non-zero otherwise.

4.8.10 GetNextDefglobal

    void *GetNextDefglobal(defglobalPtr);

    void *defglobalPtr;

 

Purpose:                              Provides access to the list of defglobals.

 

Arguments:                         A generic pointer to a defglobal data structure (or NULL to get the first defglobal).

 

Returns:                              A generic pointer to the first defglobal in the list of defglobals if defglobalPtr is NULL, otherwise a generic pointer to the defglobal immediately following defglobalPtr in the list of defglobals. If defglobalPtr is the last defglobal in the list of defglobals, then NULL is returned.

4.8.11 GetResetGlobals

    int   GetResetGlobals();

 

Purpose:                              Returns the current  value of the reset global variables behavior (the C equivalent of the CLIPS  get‑reset‑globals command).

 

Arguments:                         None.

 

Returns:                              An integer; FALSE (0) if globals are not reset and TRUE (1) if globals are reset.

4.8.12 IsDefglobalDeletable

    int   IsDefglobalDeletable(defglobalPtr);
    void *defglobalPtr;

 

Purpose:                              Indicates whether or not a particular defglobal can be deleted.

 

Arguments:                         A generic pointer to a defglobal data structure.

 

Returns:                              An integer; zero (0) if the defglobal cannot be deleted, otherwise a one (1).

4.8.13 ListDefglobals

    void ListDefglobals(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of defglobals (the C equivalent of the CLIPS list‑defglobals command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the defglobals to be listed. A NULL pointer indicates that defglobals in all modules should be listed.

 

Returns:                              No meaningful return value.

4.8.14 SetDefglobalValue

    int   SetDefglobalValue(globalName,&vPtr);

    char *globalName;

    DATA_OBJECT vPtr;

 

Purpose:                              Sets the value of a defglobal.

 

Arguments:                        1)   The name of the global variable to be set (e.g. y for ?*y*).

                                             2)   A pointer to a DATA_OBJECT in which the new value is contained (see sections 3.2.3 and 3.3.4 for details on this data structure).

 

Returns:                              An integer; zero (0) if the defglobal was not found, other­wise a one (1).

 

Other:                                  This function can trigger garbage collection.

4.8.15 SetDefglobalWatch

    void SetDefglobalWatch(newState,defglobalPtr);

    unsigned newState;

   void *defglobalPtr;

 

Purpose:                              Sets the globals watch item for a specific defglobal.

 

Arguments:                         The new globals watch state and a generic pointer to a defglobal data structure.

4.8.16 SetGlobalsChanged

    void SetGlobalsChanged(changedFlag);

    int changedFlag;

Purpose:                              Sets the internal boolean flag which indicates when changes to global variables have occurred. This function is normally used to reset the flag to zero after GetGlobalsChanged() returns non-zero.

 

Arguments:                         An integer indicating whether changes in global variables have occurred (non-zero) or not (0).

 

Returns:                              Nothing useful.

4.8.17 SetResetGlobals

    int   SetResetGlobals(value);

    int   value;

 

Purpose:                              Sets the reset-globals behavior (the C equivalent of the CLIPS  set‑reset‑globals command). When this behavior is enabled (by default) global variables are reset to their original values when the reset command is performed.

 

Arguments:                         The new value for the behavior: TRUE (1) to enable the behavior and FALSE (0) to disable it.

 

Returns:                              Returns the old value for the behavior.

4.8.18 ShowDefglobals

    void ShowDefglobals(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of defglobals and their current values (the C equivalent of the CLIPS show‑defglobals command).

 

Arguments:                          1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the defglobals to be displayed. A NULL pointer indicates that defglobals in all modules should be displayed.

 

Returns:                              No meaningful return value.

4.8.19 Undefglobal

    int   Undefglobal(defglobalPtr);

    void *defglobalPtr;

 

Purpose:                              Removes a defglobal from CLIPS (the C equivalent of the CLIPS undefglobal command).

 

Arguments:                         A generic pointer to a defglobal data structure. If the NULL pointer is used, then all defglobals will be deleted.

 

Returns:                              An integer; zero (0) if the defglobal could not be deleted, otherwise a one (1).

 

Other:                                  This function can trigger garbage collection.

4.9 Deffunction Functions

The following function calls are used for manipulating deffunctions.

4.9.1 DeffunctionModule

    char *DeffunctionModule(theDeffunction);

    void *theDeffunction;

 

Purpose:                              Returns the module in which a deffunction is defined (the C equivalent of the CLIPS deffunction-module command).

 

Arguments:                        A generic pointer to a deffunction.

 

Returns:                              A string containing the name of the module in which the deffunction is defined.

4.9.2 FindDeffunction

    void *FindDeffunction(deffunctionName);

    char *deffunctionName;

 

Purpose:                              Returns a generic pointer to a named deffunction.

 

Arguments:                         The name of the deffunction to be found.

 

Returns:                              A generic pointer to the named deffunction if it exists, otherwise NULL.

4.9.3 GetDeffunctionList

    void GetDeffunctionList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of deffunctions in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-deffunction-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the deffunction names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.9.4 GetDeffunctionName

    char *GetDeffunctionName(deffunctionPtr);

    void *deffunctionPtr;

 

Purpose:                              Returns the name of a deffunction.

 

Arguments:                         A generic pointer to a deffunction data structure.

 

Returns:                              A string containing the name of the deffunction.

4.9.5 GetDeffunctionPPForm

    char *GetDeffunctionPPForm(deffunctionPtr);

    void *deffunctionPtr;

 

Purpose:                              Returns the pretty print representation of a deffunction.

 

Arguments:                         A generic pointer to a deffunction data structure.

 

Returns:                              A string containing the pretty print representation of the deffunction (or the NULL pointer if no pretty print representation exists).

4.9.6 GetDeffunctionWatch

    unsigned GetDeffunctionWatch(deffunctionPtr);

    void *deffunctionPtr;

 

Purpose:                              Indicates whether or not a particular deffunction is being watched.

 

Arguments:                         A generic pointer to a deffunction data structure.

 

Returns:                              An integer; one (1) if the deffunction is being watched, otherwise a zero (0).

4.9.7 GetNextDeffunction

    void *GetNextDeffunction(deffunctionPtr);

    void *deffunctionPtr;

 

Purpose:                              Provides access to the list of deffunctions.

 

Arguments:                         A generic pointer to a deffunction data structure (or NULL to get the first deffunction).

 

Returns:                              A generic pointer to the first deffunction in the list of deffunctions if deffunctionPtr is NULL, otherwise a generic pointer to the deffunction immediately following deffunctionPtr in the list of deffunctions. If deffunctionPtr is the last deffunction in the list of deffunctions, then NULL is returned.

4.9.8 IsDeffunctionDeletable

    int   IsDeffunctionDeletable(deffunctionPtr);
    void *deffunctionPtr;

 

Purpose:                              Indicates whether or not a particular deffunction can be deleted.

 

Arguments:                         A generic pointer to a deffunction data structure.

 

Returns:                              An integer; zero (0) if the deffunction cannot be deleted, otherwise a one (1).

4.9.9 ListDeffunctions

    void ListDeffunctions(logicalName,theModule);

    char *logicalName;

    void *theModule;

 

Purpose:                              Prints the list of deffunction (the C equivalent of the CLIPS list‑deffunctions command).

 

Arguments:                        1)   The logical name to which the listing output is sent.

                                             2)   A generic pointer to the module containing the deffunctions to be listed. A NULL pointer indicates that deffunctions in all modules should be listed.

 

Returns:                              No meaningful return value.

4.9.10 SetDeffunctionWatch

    void SetDeffunctionWatch(newState,deffunctionPtr);

    unsigned newState;

   void *deffunctionPtr;

 

Purpose:                              Sets the deffunctions watch item for a specific deffunction.

 

Arguments:                         The new deffunctions watch state and a generic pointer to a deffunction data structure.

4.9.11 Undeffunction

    int   Undeffunction(deffunctionPtr);
    void *deffunctionPtr;

 

Purpose:                              Removes a deffunction from CLIPS (the C equivalent of the CLIPS undeffunction command).

 

Arguments:                         A generic pointer to the deffunction (NULL means to delete all deffunctions).

 

Returns:                              An integer; zero (0) if the deffunction could not be deleted, otherwise a one (1).

 

Other:                                  This function can trigger garbage collection.

4.10 Defgeneric Functions

The following function calls are used for manipulating generic functions.

4.10.1 DefgenericModule

    char *DefgenericModule(theDefgeneric);

    void *theDefgeneric;

 

Purpose:                              Returns the module in which a defgeneric is defined (the C equivalent of the CLIPS defgeneric-module command).

 

Arguments:                        A generic pointer to a defgeneric.

 

Returns:                              A string containing the name of the module in which the defgeneric is defined.

4.10.2 FindDefgeneric

    void *FindDefgeneric(defgenericName);

    char *defgenericName;

 

Purpose:                              Returns a generic pointer to a named generic function.

 

Arguments:                         The name of the generic  to be found.

 

Returns:                              A generic pointer to the named generic function if it exists, otherwise NULL.

4.10.3 GetDefgenericList

    void GetDefgenericList(&returnValue,theModule);

   DATA_OBJECT returnValue;

   void *theModule;

 

Purpose:                              Returns the list of defgenerics in the specified module as a multifield value in the returnValue DATA_OBJECT (the C equivalent of the CLIPS  get-defgeneric-list function).

 

Arguments:                        1)   A pointer to the callerÕs DATA_OBJECT in which the return value will be stored. The multifield functions described in section 3.2.4 can be used to retrieve the defgeneric names from the list.

                                             2)   A generic pointer to the module from which the list will be extracted. A NULL pointer indicates that the list is to be extracted from al l modules.

 

Returns:                              No meaningful return value.

4.10.4 GetDefgenericName

    char *GetDefgenericName(defgenericPtr);

    void *defgenericPtr;