1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright (c) 2018-2026, Stefan Meislinger <sm@opengate.at>                |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/results.h"
#include "gate/exceptions.hpp"
#include "gate/platforms.h"
#include "gate/strings.hpp"

#include <stdlib.h>
#include <stdio.h>

#if !defined(GATEXX_NO_EXCEPTIONS)
#   if __cplusplus >= 201103L
#       include <exception>
#   endif
#endif

namespace gate
{

    Throwable::~Throwable() noexcept
    {

    }


    Error::Error(result_t result, char const* source, int32_t errCode) noexcept
    {
        gate_mem_clear(&this->info, sizeof(this->info));
        this->info.result_code = result;
        this->info.error_code = errCode;
        this->info.source = source;
        if (this->info.error_code == 0)
        {
            this->info.error_code = gate_platform_get_last_error();
        }
    }

    Error::~Error() noexcept
    {
    }

    result_t Error::getResult() const noexcept
    {
        return this->info.result_code;
    }
    char const* Error::getMessage() const noexcept
    {
        return gate_result_text(this->info.result_code);
    }
    char const* Error::getSource() const noexcept
    {
        return this->info.source;
    }
    int32_t Error::getErrorCode() const noexcept
    {
        return this->info.error_code;
    }



    Exception::Exception(result_t result, char const* msg, char const* src, int32_t errCode) noexcept
    {
        gate_mem_clear(&this->info, sizeof(this->info));
        this->info.result_code = result;
        this->info.error_code = errCode;
        if (msg == NULL)
        {
            msg = gate_result_text(result);
        }
        size_t msglen = gate_str_length(msg);
        size_t srclen = gate_str_length(src);
        if (msglen >= sizeof(this->info.message))
        {
            msglen = sizeof(this->info.message) - 1;
        }
        if (srclen >= sizeof(this->info.source))
        {
            srclen = sizeof(this->info.source) - 1;
        }
        if (msglen > 0)
        {
            gate_mem_copy(this->info.message, msg, msglen);
        }
        if (srclen > 0)
        {
            gate_mem_copy(this->info.source, src, srclen);
        }
        this->info.message[msglen] = 0;
        this->info.source[srclen] = 0;
        if (this->info.error_code == 0)
        {
            this->info.error_code = gate_platform_get_last_error();
        }
    }
    Exception::Exception(exception_info_t const& xinfo)
    {
        Mem::copy(this->info, xinfo);
    }


    Exception::~Exception() noexcept
    {
    }

    result_t Exception::getResult() const noexcept
    {
        return this->info.result_code;
    }
    char const* Exception::getMessage() const noexcept
    {
        return this->info.message;
    }
    char const* Exception::getSource() const noexcept
    {
        return this->info.source;
    }
    int32_t Exception::getErrorCode() const noexcept
    {
        return this->info.error_code;
    }


    ExceptionInfo::ExceptionInfo()
        : exception_info_t(exception_info_t())
    {
        this->result_code = results::Ok;
    }

    ExceptionInfo::ExceptionInfo(exception_info_t const& src)
    {
        exception_info_t* dest = static_cast<exception_info_t*>(this);
        gate_mem_copy(dest, &src, sizeof(exception_info_t));
    }

    bool_t ExceptionInfo::failed() const noexcept
    {
        return GATE_FAILED(this->result_code);
    }

    bool_t ExceptionInfo::succeeded() const noexcept
    {
        return GATE_SUCCEEDED(this->result_code);
    }

    void ExceptionInfo::raise() const
    {
        if (GATE_FAILED(this->result_code))
        {
            raiseException(this->result_code, this->message, this->source, this->error_code);
        }
    }


    GATEXX_ATTR_NORETURN void raise(Error errObj)
    {
#if defined(GATEXX_NO_EXCEPTIONS)
        gate::panic(errObj.getResult(), errObj.getSource());
#else
        throw errObj;
#endif
    }

    GATEXX_ATTR_NORETURN void raiseError(result_t resultCode, char const* src, int32_t errCode)
    {
#if defined(GATE_DEBUG_MODE)
        printf("ERROR: %d %s %d\n", resultCode, src ? src : "??", errCode);
#endif

#if defined(GATEXX_NO_EXCEPTIONS)
        gate::panic(resultCode, src);
#else
        throw Error(resultCode, src, errCode);
#endif
    }

    GATEXX_ATTR_NORETURN void raise(Exception xcptObj)
    {
#if defined(GATEXX_NO_EXCEPTIONS)
        gate::panic(xcptObj.getResult(), xcptObj.getSource());
#else
        throw xcptObj;
#endif
    }


    GATEXX_ATTR_NORETURN void raiseException(result_t resultCode, char const* msg, char const* src, int32_t errCode)
    {
        if (!msg)
        {
            msg = gate_result_text(resultCode);<--- Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?
        }
#if defined(GATE_DEBUG_MODE)
        printf("EXCEPTION: %d %s [%s]\n", resultCode, msg, src ? src : "??");
#endif

#if defined(GATEXX_NO_EXCEPTIONS)
        gate::panic(resultCode, src);
#elif !defined(GATE_EXCEPTIONS_ADVANCED)
        throw Exception(resultCode, msg, src, errCode);
#else
        switch (resultCode)
        {
        case GATE_RESULT_ERROR:             throw exceptions::Error(msg, src, errCode);
        case GATE_RESULT_FAILED:            throw exceptions::Failed(msg, src, errCode);
        case GATE_RESULT_CANCELED:          throw exceptions::Canceled(msg, src, errCode);
        case GATE_RESULT_INVALIDARG:        throw exceptions::InvalidArg(msg, src, errCode);
        case GATE_RESULT_ACCESSDENIED:      throw exceptions::AccessDenied(msg, src, errCode);
        case GATE_RESULT_PERMISSIONDENIED:  throw exceptions::PermissionDenied(msg, src, errCode);
        case GATE_RESULT_NOTDEFINED:        throw exceptions::NotDefined(msg, src, errCode);
        case GATE_RESULT_NOTAVAILABLE:      throw exceptions::NotAvailable(msg, src, errCode);
        case GATE_RESULT_NOTIMPLEMENTED:    throw exceptions::NotImplemented(msg, src, errCode);
        case GATE_RESULT_NOMATCH:           throw exceptions::NoMatch(msg, src, errCode);
        case GATE_RESULT_NOTSUPPORTED:      throw exceptions::NotSupported(msg, src, errCode);
        case GATE_RESULT_NOTREQUIRED:       throw exceptions::NotRequired(msg, src, errCode);
        case GATE_RESULT_NOTREADY:          throw exceptions::NotReady(msg, src, errCode);
        case GATE_RESULT_SECURITYBREACH:    throw exceptions::SecurityBreach(msg, src, errCode);
        case GATE_RESULT_ALREADYEXISTS:     throw exceptions::AlreadyExists(msg, src, errCode);
        case GATE_RESULT_INVALIDSTATE:      throw exceptions::InvalidState(msg, src, errCode);

            // RESOURCE ACCESS ERRORS
        case GATE_RESULT_OUTOFMEMORY:       throw exceptions::OutOfMemory(msg, src, errCode);
        case GATE_RESULT_OUTOFRESOURCES:    throw exceptions::OutOfResources(msg, src, errCode);
        case GATE_RESULT_OUTOFBOUNDS:       throw exceptions::OutOfBounds(msg, src, errCode);
        case GATE_RESULT_NULLPOINTER:       throw exceptions::NullPointer(msg, src, errCode);
        case GATE_RESULT_BADCAST:           throw exceptions::BadCast(msg, src, errCode);
        case GATE_RESULT_ARITHMETICERROR:   throw exceptions::ArithmeticError(msg, src, errCode);
        case GATE_RESULT_OVERFLOW:          throw exceptions::Overflow(msg, src, errCode);
        case GATE_RESULT_UNDERFLOW:         throw exceptions::Underflow(msg, src, errCode);
        case GATE_RESULT_LOCKED:            throw exceptions::Locked(msg, src, errCode);
        case GATE_RESULT_TIMEOUT:           throw exceptions::Timeout(msg, src, errCode);
        case GATE_RESULT_BADADDRESS:        throw exceptions::BadAddress(msg, src, errCode);
        case GATE_RESULT_BLOCKED:           throw exceptions::Blocked(msg, src, errCode);
        case GATE_RESULT_DEVICEERROR:       throw exceptions::DeviceError(msg, src, errCode);

            // EXECUTION ERRORS
        case GATE_RESULT_EXECUTIONFAILED:       throw exceptions::ExecutionFailed(msg, src, errCode);
        case GATE_RESULT_EXECUTIONINTERRUPTED:  throw exceptions::ExecutionInterrupted(msg, src, errCode);
        case GATE_RESULT_CRITICALERROR:         throw exceptions::CriticalError(msg, src, errCode);
        case GATE_RESULT_UNKNOWNEXCEPTION:      throw exceptions::UnknownException(msg, src, errCode);
        case GATE_RESULT_PRECONDITIONFAILED:    throw exceptions::PreconditionFailed(msg, src, errCode);
        case GATE_RESULT_PREPARATIONFAILED:     throw exceptions::PreparationFailed(msg, src, errCode);
        case GATE_RESULT_BADINSTRUCTION:        throw exceptions::BadInstruction(msg, src, errCode);

            // DATA ERRORS
        case GATE_RESULT_INVALIDHEADER:     throw exceptions::InvalidHeader(msg, src, errCode);
        case GATE_RESULT_INVALIDDATA:       throw exceptions::InvalidData(msg, src, errCode);
        case GATE_RESULT_INVALIDCONTENT:    throw exceptions::InvalidContent(msg, src, errCode);
        case GATE_RESULT_INCORRECTSIZE:     throw exceptions::IncorrectSize(msg, src, errCode);
        case GATE_RESULT_INCORRECTTYPE:     throw exceptions::IncorrectType(msg, src, errCode);
        case GATE_RESULT_ENDOFSTREAM:       throw exceptions::EndOfStream(msg, src, errCode);
        case GATE_RESULT_INVALIDINPUT:      throw exceptions::InvalidInput(msg, src, errCode);
        case GATE_RESULT_INVALIDOUTPUT:     throw exceptions::InvalidOutput(msg, src, errCode);
        case GATE_RESULT_BUFFERTOOSMALL:    throw exceptions::BufferTooSmall(msg, src, errCode);
        case GATE_RESULT_NODATA:            throw exceptions::NoData(msg, src, errCode);

            // PROGRAM ERRORS
        case GATE_RESULT_APPLICATIONERROR:  throw exceptions::ApplicationError(msg, src, errCode);
        case GATE_RESULT_LOGICALERROR:      throw exceptions::LogicalError(msg, src, errCode);
        case GATE_RESULT_USERERROR:         throw exceptions::UserError(msg, src, errCode);

            // UNSPECIFIED ERRORS 
        case GATE_RESULT_UNKNOWNERROR:      throw exceptions::UnknownError(msg, src, errCode);
        default:                            throw Exception(resultCode, msg, src, errCode);
        }
#endif
    }

    gate_exception_info_t catchCurrentException() noexcept
    {
        gate_exception_info_t ret;
        gate_mem_clear(&ret, sizeof(ret));

#if defined(GATEXX_NO_EXCEPTIONS)
        ret.result_code = results::Ok;
#else
        try
        {
#if __cplusplus >= 201103L
            std::exception_ptr xcpt_ptr = std::current_exception();
            if (xcpt_ptr)
                std::rethrow_exception(xcpt_ptr);
            ret.result_code = results::Ok;
#else
            throw;
#endif
        }
        catch (Throwable const& th)
        {
            ret.result_code = th.getResult();
            ret.error_code = th.getErrorCode();
            gate_str_print_text(ret.message, sizeof(ret.message), th.getMessage(), gate_str_length(th.getMessage()));
            gate_str_print_text(ret.source, sizeof(ret.source), th.getSource(), gate_str_length(th.getSource()));
        }
        catch (...)
        {
            ret.result_code = results::UnknownException;
        }
#endif
        return ret;
    }

    gate_exception_info_t catchException(IRunnable& runner) noexcept
    {
        gate_exception_info_t ret;
        gate_mem_clear(&ret, sizeof(ret));

#if defined(GATEXX_NO_EXCEPTIONS)
        runner.run();
        ret.result_code = results::Ok;
#else
        try
        {
            runner.run();
            ret.result_code = results::Ok;
        }
        catch (Throwable const& th)
        {
            ret.result_code = th.getResult();
            ret.error_code = th.getErrorCode();
            gate_str_print_text(ret.message, sizeof(ret.message), th.getMessage(), gate_str_length(th.getMessage()));
            gate_str_print_text(ret.source, sizeof(ret.source), th.getSource(), gate_str_length(th.getSource()));
        }
        catch (...)
        {
            ret.result_code = results::UnknownException;
        }
#endif
        return ret;
    }
    gate_exception_info_t catchException(gate_entrypoint_t dispatcher, void* param) noexcept
    {
        gate_exception_info_t ret;
        gate_mem_clear(&ret, sizeof(ret));

#if defined(GATEXX_NO_EXCEPTIONS)
            ret.result_code = dispatcher(param);
#else
        try
        {
            ret.result_code = dispatcher(param);
        }
        catch (Throwable const& th)
        {
            ret.result_code = th.getResult();
            ret.error_code = th.getErrorCode();
            gate_str_print_text(ret.message, sizeof(ret.message), th.getMessage(), gate_str_length(th.getMessage()));
            gate_str_print_text(ret.source, sizeof(ret.source), th.getSource(), gate_str_length(th.getSource()));
        }
        catch (...)
        {
            ret.result_code = results::UnknownException;
        }
#endif
        return ret;
    }

    Result<Void, result_t> makeResult(result_t const& resultCode)
    {
        Result<Void, result_t> ret;
        if (GATE_SUCCEEDED(resultCode))
        {
            ret.createValue(Void());
        }
        else
        {
            ret.createError(resultCode);
        }
        return ret;
    }

    VoidResult makeOk()
    {
        VoidResult ret;
        ret.createValue(Void());
        return ret;
    }


    ResultValue<result_t, ResultErrorId> makeErr(result_t const& errCode)
    {
        return ResultValue<result_t, ResultErrorId>(errCode);
    }

    ResultValue<result_t, ResultErrorId> makeErr(results::ResultType const& errCode)
    {
        return ResultValue<result_t, ResultErrorId>(static_cast<gate_result_t>(errCode));
    }


} // end of namespace gate