squirrel.cpp

Go to the documentation of this file.
00001 /* $Id: squirrel.cpp 20632 2010-08-26 22:01:16Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include <stdarg.h>
00013 #include "../stdafx.h"
00014 #include "../debug.h"
00015 #include "squirrel_std.hpp"
00016 #include "../fileio_func.h"
00017 #include <sqstdaux.h>
00018 #include <../squirrel/sqpcheader.h>
00019 #include <../squirrel/sqvm.h>
00020 
00021 void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
00022 {
00023   SQChar buf[1024];
00024 
00025 #ifdef _SQ64
00026   scsnprintf(buf, lengthof(buf), _SC("Error %s:%ld/%ld: %s"), source, line, column, desc);
00027 #else
00028   scsnprintf(buf, lengthof(buf), _SC("Error %s:%d/%d: %s"), source, line, column, desc);
00029 #endif
00030 
00031   /* Check if we have a custom print function */
00032   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00033   engine->crashed = true;
00034   SQPrintFunc *func = engine->print_func;
00035   if (func == NULL) {
00036     scfprintf(stderr, _SC("%s"), buf);
00037   } else {
00038     (*func)(true, buf);
00039   }
00040 }
00041 
00042 void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00043 {
00044   va_list arglist;
00045   SQChar buf[1024];
00046 
00047   va_start(arglist, s);
00048   scvsnprintf(buf, lengthof(buf), s, arglist);
00049   va_end(arglist);
00050 
00051   /* Check if we have a custom print function */
00052   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00053   if (func == NULL) {
00054     scfprintf(stderr, _SC("%s"), buf);
00055   } else {
00056     (*func)(true, buf);
00057   }
00058 }
00059 
00060 void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
00061 {
00062   /* Set the print function to something that prints to stderr */
00063   SQPRINTFUNCTION pf = sq_getprintfunc(vm);
00064   sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc);
00065 
00066   /* Check if we have a custom print function */
00067   SQChar buf[1024];
00068   scsnprintf(buf, lengthof(buf), _SC("Your script made an error: %s\n"), error);
00069   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00070   SQPrintFunc *func = engine->print_func;
00071   if (func == NULL) {
00072     scfprintf(stderr, _SC("%s"), buf);
00073   } else {
00074     (*func)(true, buf);
00075   }
00076 
00077   /* Print below the error the stack, so the users knows what is happening */
00078   sqstd_printcallstack(vm);
00079   /* Reset the old print function */
00080   sq_setprintfunc(vm, pf);
00081 }
00082 
00083 SQInteger Squirrel::_RunError(HSQUIRRELVM vm)
00084 {
00085   const SQChar *sErr = 0;
00086 
00087   if (sq_gettop(vm) >= 1) {
00088     if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sErr))) {
00089       Squirrel::RunError(vm, sErr);
00090       return 0;
00091     }
00092   }
00093 
00094   Squirrel::RunError(vm, _SC("unknown error"));
00095   return 0;
00096 }
00097 
00098 void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00099 {
00100   va_list arglist;
00101   SQChar buf[1024];
00102 
00103   va_start(arglist, s);
00104   scvsnprintf(buf, lengthof(buf) - 2, s, arglist);
00105   va_end(arglist);
00106   scstrcat(buf, _SC("\n"));
00107 
00108   /* Check if we have a custom print function */
00109   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00110   if (func == NULL) {
00111     scprintf(_SC("%s"), buf);
00112   } else {
00113     (*func)(false, buf);
00114   }
00115 }
00116 
00117 void Squirrel::AddMethod(const char *method_name, SQFUNCTION proc, uint nparam, const char *params, void *userdata, int size)
00118 {
00119   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00120 
00121   if (size != 0) {
00122     void *ptr = sq_newuserdata(vm, size);
00123     memcpy(ptr, userdata, size);
00124   }
00125 
00126   sq_newclosure(this->vm, proc, size != 0 ? 1 : 0);
00127   if (nparam != 0) sq_setparamscheck(this->vm, nparam, OTTD2SQ(params));
00128   sq_setnativeclosurename(this->vm, -1, OTTD2SQ(method_name));
00129   sq_newslot(this->vm, -3, SQFalse);
00130 }
00131 
00132 void Squirrel::AddConst(const char *var_name, int value)
00133 {
00134   sq_pushstring(this->vm, OTTD2SQ(var_name), -1);
00135   sq_pushinteger(this->vm, value);
00136   sq_newslot(this->vm, -3, SQTrue);
00137 }
00138 
00139 void Squirrel::AddConst(const char *var_name, bool value)
00140 {
00141   sq_pushstring(this->vm, OTTD2SQ(var_name), -1);
00142   sq_pushbool(this->vm, value);
00143   sq_newslot(this->vm, -3, SQTrue);
00144 }
00145 
00146 void Squirrel::AddClassBegin(const char *class_name)
00147 {
00148   sq_pushroottable(this->vm);
00149   sq_pushstring(this->vm, OTTD2SQ(class_name), -1);
00150   sq_newclass(this->vm, SQFalse);
00151 }
00152 
00153 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
00154 {
00155   sq_pushroottable(this->vm);
00156   sq_pushstring(this->vm, OTTD2SQ(class_name), -1);
00157   sq_pushstring(this->vm, OTTD2SQ(parent_class), -1);
00158   if (SQ_FAILED(sq_get(this->vm, -3))) {
00159     DEBUG(misc, 0, "[squirrel] Failed to initialize class '%s' based on parent class '%s'", class_name, parent_class);
00160     DEBUG(misc, 0, "[squirrel] Make sure that '%s' exists before trying to define '%s'", parent_class, class_name);
00161     return;
00162   }
00163   sq_newclass(this->vm, SQTrue);
00164 }
00165 
00166 void Squirrel::AddClassEnd()
00167 {
00168   sq_newslot(vm, -3, SQFalse);
00169   sq_pop(vm, 1);
00170 }
00171 
00172 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
00173 {
00174   assert(!this->crashed);
00175   int top = sq_gettop(this->vm);
00176   /* Go to the instance-root */
00177   sq_pushobject(this->vm, instance);
00178   /* Find the function-name inside the script */
00179   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00180   if (SQ_FAILED(sq_get(this->vm, -2))) {
00181     sq_settop(this->vm, top);
00182     return false;
00183   }
00184   sq_settop(this->vm, top);
00185   return true;
00186 }
00187 
00188 bool Squirrel::Resume(int suspend)
00189 {
00190   assert(!this->crashed);
00191   this->crashed = !sq_resumecatch(this->vm, suspend);
00192   return this->vm->_suspended != 0;
00193 }
00194 
00195 void Squirrel::ResumeError()
00196 {
00197   assert(!this->crashed);
00198   sq_resumeerror(this->vm);
00199 }
00200 
00201 void Squirrel::CollectGarbage()
00202 {
00203   sq_collectgarbage(this->vm);
00204 }
00205 
00206 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
00207 {
00208   assert(!this->crashed);
00209   /* Store the stack-location for the return value. We need to
00210    * restore this after saving or the stack will be corrupted
00211    * if we're in the middle of a DoCommand. */
00212   SQInteger last_target = this->vm->_suspended_target;
00213   /* Store the current top */
00214   int top = sq_gettop(this->vm);
00215   /* Go to the instance-root */
00216   sq_pushobject(this->vm, instance);
00217   /* Find the function-name inside the script */
00218   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00219   if (SQ_FAILED(sq_get(this->vm, -2))) {
00220     DEBUG(misc, 0, "[squirrel] Could not find '%s' in the class", method_name);
00221     sq_settop(this->vm, top);
00222     return false;
00223   }
00224   /* Call the method */
00225   sq_pushobject(this->vm, instance);
00226   if (SQ_FAILED(sq_call(this->vm, 1, ret == NULL ? SQFalse : SQTrue, SQTrue, suspend))) return false;
00227   if (ret != NULL) sq_getstackobj(vm, -1, ret);
00228   /* Reset the top, but don't do so for the AI main function, as we need
00229    *  a correct stack when resuming. */
00230   if (suspend == -1 || !this->IsSuspended()) sq_settop(this->vm, top);
00231   /* Restore the return-value location. */
00232   this->vm->_suspended_target = last_target;
00233 
00234   return true;
00235 }
00236 
00237 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
00238 {
00239   HSQOBJECT ret;
00240   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00241   if (ret._type != OT_STRING) return false;
00242   *res = strdup(ObjectToString(&ret));
00243   return true;
00244 }
00245 
00246 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
00247 {
00248   HSQOBJECT ret;
00249   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00250   if (ret._type != OT_INTEGER) return false;
00251   *res = ObjectToInteger(&ret);
00252   return true;
00253 }
00254 
00255 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
00256 {
00257   HSQOBJECT ret;
00258   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00259   if (ret._type != OT_BOOL) return false;
00260   *res = ObjectToBool(&ret);
00261   return true;
00262 }
00263 
00264 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook)
00265 {
00266   int oldtop = sq_gettop(vm);
00267 
00268   /* First, find the class */
00269   sq_pushroottable(vm);
00270   sq_pushstring(vm, OTTD2SQ(class_name), -1);
00271   if (SQ_FAILED(sq_get(vm, -2))) {
00272     DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s'", class_name);
00273     sq_settop(vm, oldtop);
00274     return false;
00275   }
00276 
00277   /* Create the instance */
00278   if (SQ_FAILED(sq_createinstance(vm, -1))) {
00279     DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s'", class_name);
00280     sq_settop(vm, oldtop);
00281     return false;
00282   }
00283 
00284   if (instance != NULL) {
00285     /* Find our instance */
00286     sq_getstackobj(vm, -1, instance);
00287     /* Add a reference to it, so it survives for ever */
00288     sq_addref(vm, instance);
00289   }
00290   sq_remove(vm, -2); // Class-name
00291   sq_remove(vm, -2); // Root-table
00292 
00293   /* Store it in the class */
00294   sq_setinstanceup(vm, -1, real_instance);
00295   if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
00296 
00297   if (instance != NULL) sq_settop(vm, oldtop);
00298 
00299   return true;
00300 }
00301 
00302 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
00303 {
00304   return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
00305 }
00306 
00307 Squirrel::Squirrel()
00308 {
00309   this->vm = sq_open(1024);
00310   this->print_func = NULL;
00311   this->global_pointer = NULL;
00312   this->crashed = false;
00313 
00314   /* Handle compile-errors ourself, so we can display it nicely */
00315   sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
00316   sq_notifyallexceptions(this->vm, SQTrue);
00317   /* Set a good print-function */
00318   sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
00319   /* Handle runtime-errors ourself, so we can display it nicely */
00320   sq_newclosure(this->vm, &Squirrel::_RunError, 0);
00321   sq_seterrorhandler(this->vm);
00322 
00323   /* Set the foreigh pointer, so we can always find this instance from within the VM */
00324   sq_setforeignptr(this->vm, this);
00325 
00326   sq_pushroottable(this->vm);
00327   squirrel_register_global_std(this);
00328 }
00329 
00330 class SQFile {
00331 private:
00332   FILE *file;
00333   size_t size;
00334   size_t pos;
00335 
00336 public:
00337   SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
00338 
00339   size_t Read(void *buf, size_t elemsize, size_t count)
00340   {
00341     assert(elemsize != 0);
00342     if (this->pos + (elemsize * count) > this->size) {
00343       count = (this->size - this->pos) / elemsize;
00344     }
00345     if (count == 0) return 0;
00346     size_t ret = fread(buf, elemsize, count, this->file);
00347     this->pos += ret * elemsize;
00348     return ret;
00349   }
00350 };
00351 
00352 static SQInteger _io_file_lexfeed_ASCII(SQUserPointer file)
00353 {
00354   char c;
00355   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
00356   return 0;
00357 }
00358 
00359 static SQInteger _io_file_lexfeed_UTF8(SQUserPointer file)
00360 {
00361   static const SQInteger utf8_lengths[16] =
00362   {
00363     1, 1, 1, 1, 1, 1, 1, 1, /* 0000 to 0111 : 1 byte (plain ASCII) */
00364     0, 0, 0, 0,             /* 1000 to 1011 : not valid */
00365     2, 2,                   /* 1100, 1101 : 2 bytes */
00366     3,                      /* 1110 : 3 bytes */
00367     4                       /* 1111 : 4 bytes */
00368   };
00369   static unsigned char byte_masks[5] = {0, 0, 0x1F, 0x0F, 0x07};
00370   unsigned char inchar;
00371   SQInteger c = 0;
00372   if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00373   c = inchar;
00374 
00375   if (c >= 0x80) {
00376     SQInteger tmp;
00377     SQInteger codelen = utf8_lengths[c >> 4];
00378     if (codelen == 0) return 0;
00379 
00380     tmp = c & byte_masks[codelen];
00381     for (SQInteger n = 0; n < codelen - 1; n++) {
00382       tmp <<= 6;
00383       if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00384       tmp |= inchar & 0x3F;
00385     }
00386     c = tmp;
00387   }
00388   return c;
00389 }
00390 
00391 static SQInteger _io_file_lexfeed_UCS2_LE(SQUserPointer file)
00392 {
00393   wchar_t c;
00394   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (SQChar)c;
00395   return 0;
00396 }
00397 
00398 static SQInteger _io_file_lexfeed_UCS2_BE(SQUserPointer file)
00399 {
00400   unsigned short c;
00401   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
00402     c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
00403     return (SQChar)c;
00404   }
00405   return 0;
00406 }
00407 
00408 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
00409 {
00410   SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
00411   if (ret == 0) return -1;
00412   return ret;
00413 }
00414 
00415 /* static */ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
00416 {
00417   size_t size;
00418   FILE *file = FioFOpenFile(filename, "rb", AI_DIR, &size);
00419   SQInteger ret;
00420   unsigned short us;
00421   unsigned char uc;
00422   SQLEXREADFUNC func;
00423 
00424   if (file != NULL) {
00425     SQFile f(file, size);
00426     ret = fread(&us, 1, sizeof(us), file);
00427     /* Most likely an empty file */
00428     if (ret != 2) us = 0;
00429 
00430     switch (us) {
00431       case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
00432         fseek(file, -2, SEEK_CUR);
00433         if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
00434           FioFCloseFile(file);
00435           return SQ_OK;
00436         }
00437         FioFCloseFile(file);
00438         return sq_throwerror(vm, _SC("Couldn't read bytecode"));
00439       }
00440       case 0xFFFE: func = _io_file_lexfeed_UCS2_BE; break; // UTF-16 little endian
00441       case 0xFEFF: func = _io_file_lexfeed_UCS2_LE; break; // UTF-16 big endian
00442       case 0xBBEF: // UTF-8
00443         if (fread(&uc, 1, sizeof(uc), file) == 0) {
00444           FioFCloseFile(file);
00445           return sq_throwerror(vm, _SC("I/O error"));
00446         }
00447         if (uc != 0xBF) {
00448           FioFCloseFile(file);
00449           return sq_throwerror(vm, _SC("Unrecognized encoding"));
00450         }
00451         func = _io_file_lexfeed_UTF8;
00452         break;
00453       default: func = _io_file_lexfeed_ASCII; fseek(file, -2, SEEK_CUR); break; // ASCII
00454     }
00455 
00456     if (SQ_SUCCEEDED(sq_compile(vm, func, &f, OTTD2SQ(filename), printerror))) {
00457       FioFCloseFile(file);
00458       return SQ_OK;
00459     }
00460     FioFCloseFile(file);
00461     return SQ_ERROR;
00462   }
00463   return sq_throwerror(vm, _SC("cannot open the file"));
00464 }
00465 
00466 /* static */ bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
00467 {
00468   /* Make sure we are always in the root-table */
00469   if (in_root) sq_pushroottable(vm);
00470 
00471   /* Load and run the script */
00472   if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
00473     sq_push(vm, -2);
00474     if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue, 100000))) {
00475       sq_pop(vm, 1);
00476       return true;
00477     }
00478   }
00479 
00480   DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
00481   return false;
00482 }
00483 
00484 bool Squirrel::LoadScript(const char *script)
00485 {
00486   return LoadScript(this->vm, script);
00487 }
00488 
00489 Squirrel::~Squirrel()
00490 {
00491   /* Clean up the stuff */
00492   sq_pop(this->vm, 1);
00493   sq_close(this->vm);
00494 }
00495 
00496 void Squirrel::InsertResult(bool result)
00497 {
00498   sq_pushbool(this->vm, result);
00499   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00500   vm->Pop();
00501 }
00502 
00503 void Squirrel::InsertResult(int result)
00504 {
00505   sq_pushinteger(this->vm, result);
00506   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00507   vm->Pop();
00508 }
00509 
00510 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
00511 {
00512   vm->DecreaseOps(ops);
00513 }
00514 
00515 bool Squirrel::IsSuspended()
00516 {
00517   return this->vm->_suspended != 0;
00518 }
00519 
00520 bool Squirrel::HasScriptCrashed()
00521 {
00522   return this->crashed;
00523 }
00524 
00525 void Squirrel::ResetCrashed()
00526 {
00527   this->crashed = false;
00528 }
00529 
00530 void Squirrel::CrashOccurred()
00531 {
00532   this->crashed = true;
00533 }
00534 
00535 bool Squirrel::CanSuspend()
00536 {
00537   return sq_can_suspend(this->vm);
00538 }

Generated on Fri Feb 4 20:53:46 2011 for OpenTTD by  doxygen 1.6.1