source: cpp/frams/util/extvalue.h @ 963

Last change on this file since 963 was 851, checked in by Maciej Komosinski, 6 years ago

Getting int or float value casted from null or invalid is an ERROR (but still returns 0)

  • Property svn:eol-style set to native
File size: 10.1 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2015  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#ifndef _EXTVALUE_H_
6#define _EXTVALUE_H_
7
8#include "sstring.h"
9#include <frams/param/param.h>
10#include <common/nonstd_stl.h>
11#include <common/threads.h>
12
13#define EXTVALUEUNION
14template <int A, int B> struct CompileTimeMax { enum { val = A > B ? A : B }; };
15#define EXTVALUEUNIONSIZE CompileTimeMax<sizeof(ExtObject),sizeof(SString)>::val
16
17//#define DEBUG_EXTOBJECT(txt) printf("%p ExtObj::" txt "\n",this)
18#define DEBUG_EXTOBJECT(txt)
19
20enum ExtPType
21{
22        TUnknown = 0, TInt, TDouble, TString, TObj, TInvalid
23};
24
25/**
26   destructable object
27   */
28class DestrBase
29{
30public:
31        int refcount;
32        DestrBase() :refcount(0) {}
33        void incref() { refcount++; }
34        void decref() { refcount--; if (refcount == 0) delete this; }
35        virtual ~DestrBase() {}
36};
37
38enum SerializationFormat { NativeSerialization, JSONSerialization };
39
40/**
41   object reference.
42   */
43class ExtObject
44{
45        int subtype;                    //< 0/1=Generic/DPC Object,  0/2=Standalone/Shared Param
46        void incref() const;
47        void decref() const;
48public:
49        union {
50                void* object;           //< generic object, will use param
51                DestrBase *dbobject;    //< object with refcounting, will be deleted if refcount goes to 0
52        };
53        union {
54                Param* param;           //< if object!=0
55                ParamInterface *paraminterface; //< if object==0
56        };
57
58        void copyFrom(const ExtObject& src) { subtype = src.subtype; object = src.object; param = src.param; }
59
60        void* operator new(size_t s, void* mem) { return mem; }
61#ifdef _MSC_VER
62        void operator delete(void* mem, void* t) {}
63#endif
64        void* operator new(size_t s) { return malloc(sizeof(ExtObject)); }
65        void operator delete(void* mem) { free(mem); }
66        ///@param tmp_param can be used for temporary storage, the result ParamInterface* is only valid for as long as tmp_param is valid
67        ParamInterface *getParamInterface(Param &tmp_param) const { if (subtype & 2) { tmp_param.setParamTab(param->getParamTab()); tmp_param.select(object); return &tmp_param; } return paraminterface; }
68        const char* interfaceName() const { if (isEmpty()) return "Empty"; return (subtype & 2) ? param->getName() : paraminterface->getName(); }
69        bool matchesInterfaceName(ParamInterface* pi) const { return !strcmp(interfaceName(), pi->getName()); }
70        void* getTarget() const { return (subtype & 1) ? dbobject : object; }
71        void* getTarget(const char* classname, bool through_barrier = true, bool warn = true) const;
72        bool callDelegate(const char* delegate, ExtValue *args, ExtValue *ret);
73        void setEmpty() { decref(); subtype = 0; param = NULL; object = NULL; }
74        int isEmpty() const { return !param; }
75        static const ExtObject& empty() { static const ExtObject e((ParamInterface*)NULL); return e; }
76        ExtObject(const ExtObject& src) { DEBUG_EXTOBJECT("(const&)"); src.incref(); copyFrom(src); }
77        void operator=(const ExtObject& src) { src.incref(); decref(); copyFrom(src); }
78        bool makeUnique();//< @return false if nothing has changed
79
80        bool operator==(const ExtObject& src) const;
81
82        SString toString() const;
83        SString serialize_inner(SerializationFormat format) const;
84        SString serialize(SerializationFormat format) const;
85
86        ExtObject(Param *p, void *o) :subtype(2), object(o), param(p) { DEBUG_EXTOBJECT("(Param,void)"); }
87        ExtObject(ParamInterface *p = 0) :subtype(0), object(0), paraminterface(p) { DEBUG_EXTOBJECT("(ParamInterface)"); }
88        ExtObject(Param *p, DestrBase *o) :subtype(1 + 2), dbobject(o), param(p) { DEBUG_EXTOBJECT("(Param,DestrBase)"); incref(); }
89        ExtObject(ParamInterface *p, DestrBase *o) :subtype(1), dbobject(o), paraminterface(p) { DEBUG_EXTOBJECT("(ParamInterface,DestrBase)"); incref(); }
90
91        ~ExtObject() { DEBUG_EXTOBJECT("~"); decref(); }
92
93        class Serialization
94        {
95                std::vector<ExtObject> refs;
96                int level;
97        public:
98                Serialization() :level(0) {}
99                void begin();
100                void end();
101                int add(const ExtObject& o);
102                void replace(const ExtObject& o, const ExtObject& other);
103                void remove(const ExtObject& o);
104                const ExtObject* get(int ref);
105        };
106
107};
108
109extern THREAD_LOCAL_DECL(ExtObject::Serialization, ExtObject_serialization);
110
111class ExtValue
112{
113public:
114        ExtPType type;
115#ifdef EXTVALUEUNION
116        intptr_t data[(EXTVALUEUNIONSIZE + sizeof(intptr_t) - 1) / sizeof(intptr_t)];
117        paInt& idata() const { return (paInt&)data[0]; };
118        double& ddata() const { return *(double*)data; };
119        ExtObject& odata() const { return *(ExtObject*)data; };
120        SString& sdata() const { return *(SString*)data; };
121#else
122        union {
123                paInt i;
124                double d;
125                SString *s;
126                ExtObject *o;
127        };
128        paInt& idata() const { return (paInt&)i; };
129        double& ddata() const { return (double&)d; };
130        ExtObject& odata() const { return *o; };
131        SString& sdata() const { return *s; };
132#endif
133
134        void* operator new(size_t s, void* mem) { return mem; }
135        void* operator new(size_t s) { return ::operator new(s); }
136
137        ExtValue() :type(TUnknown) {}
138        ~ExtValue() { setEmpty(); }
139        ExtValue(paInt v) { seti(v); }
140        ExtValue(double v) { setd(v); }
141        ExtValue(const SString &v) { sets(v); }
142        ExtValue(const ExtObject &srco) { seto(srco); }
143        static ExtValue invalid() { ExtValue v; v.setInvalid(); return v; }
144        static const ExtValue& empty() { static const ExtValue v; return v; }
145        static const ExtValue& zero() { static const ExtValue v(0); return v; }
146
147        enum CompareResult
148        {
149                ResultLower = -1, ResultEqual = 0, ResultHigher = 1,
150                ResultEqualUnordered,
151                ResultUnequal_RelaxedEqual,
152                ResultUnequal_RelaxedUnequal,
153                ResultMismatch_RelaxedUnequal,
154                ResultMismatch
155        };
156        // performs all script value comparisons.
157        // relaxed comparison (internal use only, not available in scripts) works like regular == with additional null~=0, notnull!~0
158        // and is used for pseudo-boolean conversion allowing for expressions like "if (null) ..."
159        CompareResult compare(const ExtValue& src) const;
160
161        enum CmpOperator { CmpFIRST, CmpEQ = CmpFIRST, CmpNE, CmpGE, CmpLE, CmpGT, CmpLT,/*relaxed (not)equal*/CmpREQ, CmpRNE };
162        static const char* cmp_op_names[];
163        struct CmpContext { const ExtValue *v1, *v2; };
164        // interpret compare() result, optional context controls error messages
165        // @return 0=false, 1=true, -1=undefined (null in script)
166        static int interpretCompare(CmpOperator op, CompareResult result, CmpContext *context = NULL);
167
168        void divInt(paInt a);
169        void divDouble(double a);
170        void modInt(paInt a);
171        void modDouble(double a);
172
173        int operator==(const ExtValue& src) const;
174        void operator+=(const ExtValue& src);
175        void operator-=(const ExtValue& src);
176        void operator*=(const ExtValue& src);
177        void operator/=(const ExtValue& src);
178        void operator%=(const ExtValue& src);
179        void operator=(const ExtValue& src)
180        {
181                setr(src);
182        }
183        ExtValue(const ExtValue& src)
184                :type(TUnknown) {
185                set(src);
186        }
187        void setEmpty();
188        void setInvalid() { setEmpty(); type = TInvalid; }
189        void setError(const SString& msg);
190        bool makeUnique() { return (type == TObj) && odata().makeUnique(); } //< @return false if nothing has changed
191        ExtPType getType() const { return type; }
192        void *getObjectTarget(const char* classname, bool warn = true) const;
193        void setInt(paInt v) { if (type != TInt) setri(v); else idata() = v; }
194        void setDouble(double v) { if (type != TDouble) setrd(v); else ddata() = v; }
195        void setString(const SString &v) { if (type != TString) setrs(v); else sdata() = v; }
196        void setObject(const ExtObject &src) { if (type != TObj) setro(src); else odata() = src; }
197        static bool parseInt(const char* s, paInt &result, bool strict, bool error);
198        static bool parseDouble(const char* s, double &result, bool error);
199        static paInt getInt(const char* s, bool strict = false);//< @param strict=true will fail on floating point
200        static double getDouble(const char* s);
201        paInt getInt() const;
202        double getDouble() const;
203        SString getString() const;
204        const SString* getStringPtr() const;//< @return pointer to the internal sstring object or NULL if the current type is not string
205        SString serialize(SerializationFormat format) const;
206        ExtObject getObject() const;
207        bool isNull() const { return (type == TUnknown) || ((type == TObj) && odata().isEmpty()); }
208        SString typeDescription() const;//< @return human readable type name (used in error messages)
209        SString typeAndValue() const;//< @return type and value (used in error messages)
210        const char* parseNumber(const char* in, ExtPType strict_type = TUnknown);
211        const char* deserialize(const char* in);//< @return first character after the succesfully parsed string or NULL if failed
212        const char* deserialize_inner(const char* in);
213        static ParamInterface *findDeserializableClass(const char* name);
214        static PtrListTempl<ParamInterface*> &getDeserializableClasses();
215        template<typename T> class AddDeserializable
216        {
217        public:
218                AddDeserializable() { ExtValue::getDeserializableClasses() += &T::getStaticParam(); }
219        };
220
221        static SString formatTime(char fmt, double value);
222        static SString format(const SString& fmt, const ExtValue **values, int count);
223
224        ExtValue getExtType();
225
226private: // setrx - release and set, setx - assume released
227        void setr(const ExtValue& src) { setEmpty(); set(src); }
228        void set(const ExtValue& src);
229        void setri(paInt v) { setEmpty(); seti(v); }
230        void setrd(double v) { setEmpty(); setd(v); }
231        void seti(paInt v) { type = TInt; idata() = v; }
232        void setd(double v) { type = TDouble; ddata() = v; }
233#ifdef EXTVALUEUNION
234        void setrs(const SString &v) { setEmpty(); sets(v); }
235        void setro(const ExtObject &src) { setEmpty(); seto(src); }
236        void sets(const SString &v) { type = TString; new(data)SString(v); }
237        void seto(const ExtObject &src) { type = TObj; new(data)ExtObject(src); }
238#else
239        void setrs(const SString &v) { setEmpty(); sets(v); }
240        void setro(const ExtObject &src) { setEmpty(); seto(src); }
241        void sets(const SString &v) { type = TString; s = new SString(v); }
242        void seto(const ExtObject &src) { type = TObj; o = new ExtObject(src); }
243#endif
244
245};
246
247#define REGISTER_DESERIALIZABLE(name) ExtValue::AddDeserializable<name> deserializable_autoinit_ ## name;
248
249class ErrorObject : public DestrBase
250{
251public:
252        SString message;
253        static Param& getParam();
254        static Param& getStaticParam() { return getParam(); }
255        static ExtObject makeDynamicObject(ErrorObject* e);
256        static const SString TO_STRING_PREFIX;
257#define STATRICKCLASS ErrorObject
258        PARAMGETDEF(toString);
259        PARAMPROCDEF(p_newfromstring);
260#undef STATRICKCLASS
261};
262
263#endif
Note: See TracBrowser for help on using the repository browser.