rtl.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. var pas = {};
  2. var rtl = {
  3. version: 10101,
  4. quiet: false,
  5. debug_load_units: false,
  6. debug_rtti: false,
  7. debug: function(){
  8. if (rtl.quiet || !console || !console.log) return;
  9. console.log(arguments);
  10. },
  11. error: function(s){
  12. rtl.debug('Error: ',s);
  13. throw s;
  14. },
  15. warn: function(s){
  16. rtl.debug('Warn: ',s);
  17. },
  18. checkVersion: function(v){
  19. if (rtl.version != v) throw "expected rtl version "+v+", but found "+rtl.version;
  20. },
  21. hasString: function(s){
  22. return rtl.isString(s) && (s.length>0);
  23. },
  24. isArray: function(a) {
  25. return Array.isArray(a);
  26. },
  27. isFunction: function(f){
  28. return typeof(f)==="function";
  29. },
  30. isModule: function(m){
  31. return rtl.isObject(m) && rtl.hasString(m.$name) && (pas[m.$name]===m);
  32. },
  33. isImplementation: function(m){
  34. return rtl.isObject(m) && rtl.isModule(m.$module) && (m.$module.$impl===m);
  35. },
  36. isNumber: function(n){
  37. return typeof(n)==="number";
  38. },
  39. isObject: function(o){
  40. var s=typeof(o);
  41. return (typeof(o)==="object") && (o!=null);
  42. },
  43. isString: function(s){
  44. return typeof(s)==="string";
  45. },
  46. getNumber: function(n){
  47. return typeof(n)==="number"?n:NaN;
  48. },
  49. getChar: function(c){
  50. return ((typeof(c)==="string") && (c.length===1)) ? c : "";
  51. },
  52. getObject: function(o){
  53. return ((typeof(o)==="object") || (typeof(o)==='function')) ? o : null;
  54. },
  55. isPasClass: function(type){
  56. return (rtl.isObject(type) && type.hasOwnProperty('$classname') && rtl.isObject(type.$module));
  57. },
  58. isPasClassInstance: function(type){
  59. return (rtl.isObject(type) && rtl.isPasClass(type.$class));
  60. },
  61. hexStr: function(n,digits){
  62. return ("000000000000000"+n.toString(16).toUpperCase()).slice(-digits);
  63. },
  64. m_loading: 0,
  65. m_loading_intf: 1,
  66. m_intf_loaded: 2,
  67. m_loading_impl: 3, // loading all used unit
  68. m_initializing: 4, // running initialization
  69. m_initialized: 5,
  70. module: function(module_name, intfuseslist, intfcode, impluseslist, implcode){
  71. if (rtl.debug_load_units) rtl.debug('rtl.module name="'+module_name+'" intfuses='+intfuseslist+' impluses='+impluseslist+' hasimplcode='+rtl.isFunction(implcode));
  72. if (!rtl.hasString(module_name)) rtl.error('invalid module name "'+module_name+'"');
  73. if (!rtl.isArray(intfuseslist)) rtl.error('invalid interface useslist of "'+module_name+'"');
  74. if (!rtl.isFunction(intfcode)) rtl.error('invalid interface code of "'+module_name+'"');
  75. if (!(impluseslist==undefined) && !rtl.isArray(impluseslist)) rtl.error('invalid implementation useslist of "'+module_name+'"');
  76. if (!(implcode==undefined) && !rtl.isFunction(implcode)) rtl.error('invalid implementation code of "'+module_name+'"');
  77. if (pas[module_name])
  78. rtl.error('module "'+module_name+'" is already registered');
  79. var module = pas[module_name] = {
  80. $name: module_name,
  81. $intfuseslist: intfuseslist,
  82. $impluseslist: impluseslist,
  83. $state: rtl.m_loading,
  84. $intfcode: intfcode,
  85. $implcode: implcode,
  86. $impl: null,
  87. $rtti: Object.create(rtl.tSectionRTTI)
  88. };
  89. module.$rtti.$module = module;
  90. if (implcode) module.$impl = {
  91. $module: module,
  92. $rtti: module.$rtti
  93. };
  94. },
  95. exitcode: 0,
  96. run: function(module_name){
  97. function doRun(){
  98. if (!rtl.hasString(module_name)) module_name='program';
  99. if (rtl.debug_load_units) rtl.debug('rtl.run module="'+module_name+'"');
  100. rtl.initRTTI();
  101. var module = pas[module_name];
  102. if (!module) rtl.error('rtl.run module "'+module_name+'" missing');
  103. rtl.loadintf(module);
  104. rtl.loadimpl(module);
  105. if (module_name=='program'){
  106. if (rtl.debug_load_units) rtl.debug('running $main');
  107. var r = pas.program.$main();
  108. if (rtl.isNumber(r)) rtl.exitcode = r;
  109. }
  110. }
  111. if (rtl.showUncaughtExceptions) {
  112. try{
  113. doRun();
  114. } catch(re) {
  115. var errMsg = re.hasOwnProperty('$class') ? re.$class.$classname : '';
  116. errMsg += ((errMsg) ? ': ' : '') + (re.hasOwnProperty('fMessage') ? re.fMessage : re);
  117. alert('Uncaught Exception : '+errMsg);
  118. rtl.exitCode = 216;
  119. }
  120. } else {
  121. doRun();
  122. }
  123. return rtl.exitcode;
  124. },
  125. loadintf: function(module){
  126. if (module.$state>rtl.m_loading_intf) return; // already finished
  127. if (rtl.debug_load_units) rtl.debug('loadintf: "'+module.$name+'"');
  128. if (module.$state===rtl.m_loading_intf)
  129. rtl.error('unit cycle detected "'+module.$name+'"');
  130. module.$state=rtl.m_loading_intf;
  131. // load interfaces of interface useslist
  132. rtl.loaduseslist(module,module.$intfuseslist,rtl.loadintf);
  133. // run interface
  134. if (rtl.debug_load_units) rtl.debug('loadintf: run intf of "'+module.$name+'"');
  135. module.$intfcode(module.$intfuseslist);
  136. // success
  137. module.$state=rtl.m_intf_loaded;
  138. // Note: units only used in implementations are not yet loaded (not even their interfaces)
  139. },
  140. loaduseslist: function(module,useslist,f){
  141. if (useslist==undefined) return;
  142. for (var i in useslist){
  143. var unitname=useslist[i];
  144. if (rtl.debug_load_units) rtl.debug('loaduseslist of "'+module.$name+'" uses="'+unitname+'"');
  145. if (pas[unitname]==undefined)
  146. rtl.error('module "'+module.$name+'" misses "'+unitname+'"');
  147. f(pas[unitname]);
  148. }
  149. },
  150. loadimpl: function(module){
  151. if (module.$state>=rtl.m_loading_impl) return; // already processing
  152. if (module.$state<rtl.m_intf_loaded) rtl.error('loadimpl: interface not loaded of "'+module.$name+'"');
  153. if (rtl.debug_load_units) rtl.debug('loadimpl: load uses of "'+module.$name+'"');
  154. module.$state=rtl.m_loading_impl;
  155. // load interfaces of implementation useslist
  156. rtl.loaduseslist(module,module.$impluseslist,rtl.loadintf);
  157. // load implementation of interfaces useslist
  158. rtl.loaduseslist(module,module.$intfuseslist,rtl.loadimpl);
  159. // load implementation of implementation useslist
  160. rtl.loaduseslist(module,module.$impluseslist,rtl.loadimpl);
  161. // Note: At this point all interfaces used by this unit are loaded. If
  162. // there are implementation uses cycles some used units might not yet be
  163. // initialized. This is by design.
  164. // run implementation
  165. if (rtl.debug_load_units) rtl.debug('loadimpl: run impl of "'+module.$name+'"');
  166. if (rtl.isFunction(module.$implcode)) module.$implcode(module.$impluseslist);
  167. // run initialization
  168. if (rtl.debug_load_units) rtl.debug('loadimpl: run init of "'+module.$name+'"');
  169. module.$state=rtl.m_initializing;
  170. if (rtl.isFunction(module.$init)) module.$init();
  171. // unit initialized
  172. module.$state=rtl.m_initialized;
  173. },
  174. createCallback: function(scope, fn){
  175. var cb;
  176. if (typeof(fn)==='string'){
  177. cb = function(){
  178. return scope[fn].apply(scope,arguments);
  179. };
  180. } else {
  181. cb = function(){
  182. return fn.apply(scope,arguments);
  183. };
  184. };
  185. cb.scope = scope;
  186. cb.fn = fn;
  187. return cb;
  188. },
  189. cloneCallback: function(cb){
  190. return rtl.createCallback(cb.scope,cb.fn);
  191. },
  192. eqCallback: function(a,b){
  193. // can be a function or a function wrapper
  194. if (a==b){
  195. return true;
  196. } else {
  197. return (a!=null) && (b!=null) && (a.fn) && (a.scope===b.scope) && (a.fn==b.fn);
  198. }
  199. },
  200. initClass: function(c,parent,name,initfn){
  201. parent[name] = c;
  202. c.$class = c; // Note: o.$class === Object.getPrototypeOf(o)
  203. c.$classname = name;
  204. if ((parent.$module) && (parent.$module.$impl===parent)) parent=parent.$module;
  205. c.$parent = parent;
  206. c.$fullname = parent.$name+'.'+name;
  207. if (rtl.isModule(parent)){
  208. c.$module = parent;
  209. c.$name = name;
  210. } else {
  211. c.$module = parent.$module;
  212. c.$name = parent.name+'.'+name;
  213. };
  214. // rtti
  215. if (rtl.debug_rtti) rtl.debug('initClass '+c.$fullname);
  216. var t = c.$module.$rtti.$Class(c.$name,{ "class": c, module: parent });
  217. c.$rtti = t;
  218. if (rtl.isObject(c.$ancestor)) t.ancestor = c.$ancestor.$rtti;
  219. if (!t.ancestor) t.ancestor = null;
  220. // init members
  221. initfn.call(c);
  222. },
  223. createClass: function(parent,name,ancestor,initfn){
  224. // create a normal class,
  225. // ancestor must be null or a normal class,
  226. // the root ancestor can be an external class
  227. var c = null;
  228. if (ancestor != null){
  229. c = Object.create(ancestor);
  230. c.$ancestor = ancestor;
  231. // Note:
  232. // if root is an "object" then c.$ancestor === Object.getPrototypeOf(c)
  233. // if root is a "function" then c.$ancestor === c.__proto__, Object.getPrototypeOf(c) returns the root
  234. } else {
  235. c = {};
  236. c.$create = function(fnname,args){
  237. if (args == undefined) args = [];
  238. var o = Object.create(this);
  239. o.$init();
  240. try{
  241. o[fnname].apply(o,args);
  242. o.AfterConstruction();
  243. } catch($e){
  244. // do not call BeforeDestruction
  245. if (o.Destroy) o.Destroy();
  246. o.$final();
  247. throw $e;
  248. }
  249. return o;
  250. };
  251. c.$destroy = function(fnname){
  252. this.BeforeDestruction();
  253. if (this[fnname]) this[fnname]();
  254. this.$final();
  255. };
  256. };
  257. rtl.initClass(c,parent,name,initfn);
  258. },
  259. createClassExt: function(parent,name,ancestor,newinstancefnname,initfn){
  260. // Create a class using an external ancestor.
  261. // If newinstancefnname is given, use that function to create the new object.
  262. // If exist call BeforeDestruction and AfterConstruction.
  263. var c = null;
  264. c = Object.create(ancestor);
  265. c.$create = function(fnname,args){
  266. if (args == undefined) args = [];
  267. var o = null;
  268. if (newinstancefnname.length>0){
  269. o = this[newinstancefnname](fnname,args);
  270. } else {
  271. o = Object.create(this);
  272. }
  273. if (o.$init) o.$init();
  274. try{
  275. o[fnname].apply(o,args);
  276. if (o.AfterConstruction) o.AfterConstruction();
  277. } catch($e){
  278. // do not call BeforeDestruction
  279. if (o.Destroy) o.Destroy();
  280. if (o.$final) this.$final();
  281. throw $e;
  282. }
  283. return o;
  284. };
  285. c.$destroy = function(fnname){
  286. if (this.BeforeDestruction) this.BeforeDestruction();
  287. if (this[fnname]) this[fnname]();
  288. if (this.$final) this.$final();
  289. };
  290. rtl.initClass(c,parent,name,initfn);
  291. },
  292. tObjectDestroy: "Destroy",
  293. free: function(obj,name){
  294. if (obj[name]==null) return;
  295. obj[name].$destroy(rtl.tObjectDestroy);
  296. obj[name]=null;
  297. },
  298. freeLoc: function(obj){
  299. if (obj==null) return;
  300. obj.$destroy(rtl.tObjectDestroy);
  301. return null;
  302. },
  303. is: function(instance,type){
  304. return type.isPrototypeOf(instance) || (instance===type);
  305. },
  306. isExt: function(instance,type,mode){
  307. // mode===1 means instance must be a Pascal class instance
  308. // mode===2 means instance must be a Pascal class
  309. // Notes:
  310. // isPrototypeOf and instanceof return false on equal
  311. // isPrototypeOf does not work for Date.isPrototypeOf(new Date())
  312. // so if isPrototypeOf is false test with instanceof
  313. // instanceof needs a function on right side
  314. if (instance == null) return false; // Note: ==null checks for undefined too
  315. if ((typeof(type) !== 'object') && (typeof(type) !== 'function')) return false;
  316. if (instance === type){
  317. if (mode===1) return false;
  318. if (mode===2) return rtl.isPasClass(instance);
  319. return true;
  320. }
  321. if (type.isPrototypeOf && type.isPrototypeOf(instance)){
  322. if (mode===1) return rtl.isPasClassInstance(instance);
  323. if (mode===2) return rtl.isPasClass(instance);
  324. return true;
  325. }
  326. if ((typeof type == 'function') && (instance instanceof type)) return true;
  327. return false;
  328. },
  329. Exception: null,
  330. EInvalidCast: null,
  331. EAbstractError: null,
  332. ERangeError: null,
  333. raiseE: function(typename){
  334. var t = rtl[typename];
  335. if (t==null){
  336. var mod = pas.SysUtils;
  337. if (!mod) mod = pas.sysutils;
  338. if (mod){
  339. t = mod[typename];
  340. if (!t) t = mod[typename.toLowerCase()];
  341. if (!t) t = mod['Exception'];
  342. if (!t) t = mod['exception'];
  343. }
  344. }
  345. if (t){
  346. if (t.Create){
  347. throw t.$create("Create");
  348. } else if (t.create){
  349. throw t.$create("create");
  350. }
  351. }
  352. if (typename === "EInvalidCast") throw "invalid type cast";
  353. if (typename === "EAbstractError") throw "Abstract method called";
  354. if (typename === "ERangeError") throw "range error";
  355. throw typename;
  356. },
  357. as: function(instance,type){
  358. if((instance === null) || rtl.is(instance,type)) return instance;
  359. rtl.raiseE("EInvalidCast");
  360. },
  361. asExt: function(instance,type,mode){
  362. if((instance === null) || rtl.isExt(instance,type,mode)) return instance;
  363. rtl.raiseE("EInvalidCast");
  364. },
  365. createInterface: function(module, name, guid, fnnames, ancestor, initfn){
  366. //console.log('createInterface name="'+name+'" guid="'+guid+'" names='+fnnames);
  367. var i = ancestor?Object.create(ancestor):{};
  368. module[name] = i;
  369. i.$module = module;
  370. i.$name = name;
  371. i.$fullname = module.$name+'.'+name;
  372. i.$guid = guid;
  373. i.$guidr = null;
  374. i.$names = fnnames?fnnames:[];
  375. if (rtl.isFunction(initfn)){
  376. // rtti
  377. if (rtl.debug_rtti) rtl.debug('createInterface '+i.$fullname);
  378. var t = i.$module.$rtti.$Interface(name,{ "interface": i, module: module });
  379. i.$rtti = t;
  380. if (ancestor) t.ancestor = ancestor.$rtti;
  381. if (!t.ancestor) t.ancestor = null;
  382. initfn.call(i);
  383. }
  384. return i;
  385. },
  386. strToGUIDR: function(s,g){
  387. var p = 0;
  388. function n(l){
  389. var h = s.substr(p,l);
  390. p+=l;
  391. return parseInt(h,16);
  392. }
  393. p+=1; // skip {
  394. g.D1 = n(8);
  395. p+=1; // skip -
  396. g.D2 = n(4);
  397. p+=1; // skip -
  398. g.D3 = n(4);
  399. p+=1; // skip -
  400. if (!g.D4) g.D4=[];
  401. g.D4[0] = n(2);
  402. g.D4[1] = n(2);
  403. p+=1; // skip -
  404. for(var i=2; i<8; i++) g.D4[i] = n(2);
  405. return g;
  406. },
  407. guidrToStr: function(g){
  408. if (g.$intf) return g.$intf.$guid;
  409. var h = rtl.hexStr;
  410. var s='{'+h(g.D1,8)+'-'+h(g.D2,4)+'-'+h(g.D3,4)+'-'+h(g.D4[0],2)+h(g.D4[1],2)+'-';
  411. for (var i=2; i<8; i++) s+=h(g.D4[i],2);
  412. s+='}';
  413. return s;
  414. },
  415. createTGUID: function(guid){
  416. var TGuid = (pas.System)?pas.System.TGuid:pas.system.tguid;
  417. var g = rtl.strToGUIDR(guid,new TGuid());
  418. return g;
  419. },
  420. getIntfGUIDR: function(intfTypeOrVar){
  421. if (!intfTypeOrVar) return null;
  422. if (!intfTypeOrVar.$guidr){
  423. var g = rtl.createTGUID(intfTypeOrVar.$guid);
  424. if (!intfTypeOrVar.hasOwnProperty('$guid')) intfTypeOrVar = Object.getPrototypeOf(intfTypeOrVar);
  425. g.$intf = intfTypeOrVar;
  426. intfTypeOrVar.$guidr = g;
  427. }
  428. return intfTypeOrVar.$guidr;
  429. },
  430. addIntf: function (aclass, intf, map){
  431. function jmp(fn){
  432. if (typeof(fn)==="function"){
  433. return function(){ return fn.apply(this.$o,arguments); };
  434. } else {
  435. return function(){ rtl.raiseE('EAbstractError'); };
  436. }
  437. }
  438. if(!map) map = {};
  439. var t = intf;
  440. var item = Object.create(t);
  441. if (!aclass.hasOwnProperty('$intfmaps')) aclass.$intfmaps = {};
  442. aclass.$intfmaps[intf.$guid] = item;
  443. do{
  444. var names = t.$names;
  445. if (!names) break;
  446. for (var i=0; i<names.length; i++){
  447. var intfname = names[i];
  448. var fnname = map[intfname];
  449. if (!fnname) fnname = intfname;
  450. //console.log('addIntf: intftype='+t.$name+' index='+i+' intfname="'+intfname+'" fnname="'+fnname+'" old='+typeof(item[intfname]));
  451. item[intfname] = jmp(aclass[fnname]);
  452. }
  453. t = Object.getPrototypeOf(t);
  454. }while(t!=null);
  455. },
  456. getIntfG: function (obj, guid, query){
  457. if (!obj) return null;
  458. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' query='+query);
  459. // search
  460. var maps = obj.$intfmaps;
  461. if (!maps) return null;
  462. var item = maps[guid];
  463. if (!item) return null;
  464. // check delegation
  465. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' query='+query+' item='+typeof(item));
  466. if (typeof item === 'function') return item.call(obj); // delegate. Note: COM contains _AddRef
  467. // check cache
  468. var intf = null;
  469. if (obj.$interfaces){
  470. intf = obj.$interfaces[guid];
  471. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' cache='+typeof(intf));
  472. }
  473. if (!intf){ // intf can be undefined!
  474. intf = Object.create(item);
  475. intf.$o = obj;
  476. if (!obj.$interfaces) obj.$interfaces = {};
  477. obj.$interfaces[guid] = intf;
  478. }
  479. if (typeof(query)==='object'){
  480. // called by queryIntfT
  481. var o = null;
  482. if (intf.QueryInterface(rtl.getIntfGUIDR(query),
  483. {get:function(){ return o; }, set:function(v){ o=v; }}) === 0){
  484. return o;
  485. } else {
  486. return null;
  487. }
  488. } else if(query===2){
  489. // called by TObject.GetInterfaceByStr
  490. if (intf.$kind === 'com') intf._AddRef();
  491. }
  492. return intf;
  493. },
  494. getIntfT: function(obj,intftype){
  495. return rtl.getIntfG(obj,intftype.$guid);
  496. },
  497. queryIntfT: function(obj,intftype){
  498. return rtl.getIntfG(obj,intftype.$guid,intftype);
  499. },
  500. queryIntfIsT: function(obj,intftype){
  501. var i = rtl.queryIntfG(obj,intftype.$guid);
  502. if (!i) return false;
  503. if (i.$kind === 'com') i._Release();
  504. return true;
  505. },
  506. asIntfT: function (obj,intftype){
  507. var i = rtl.getIntfG(obj,intftype.$guid);
  508. if (i!==null) return i;
  509. rtl.raiseEInvalidCast();
  510. },
  511. intfIsClass: function(intf,classtype){
  512. return (intf!=null) && (rtl.is(intf.$o,classtype));
  513. },
  514. intfAsClass: function(intf,classtype){
  515. if (intf==null) return null;
  516. return rtl.as(intf.$o,classtype);
  517. },
  518. intfToClass: function(intf,classtype){
  519. if ((intf!==null) && rtl.is(intf.$o,classtype)) return intf.$o;
  520. return null;
  521. },
  522. // interface reference counting
  523. intfRefs: { // base object for temporary interface variables
  524. ref: function(id,intf){
  525. // called for temporary interface references needing delayed release
  526. var old = this[id];
  527. //console.log('rtl.intfRefs.ref: id='+id+' old="'+(old?old.$name:'null')+'" intf="'+(intf?intf.$name:'null')+' $o='+(intf?intf.$o:'null'));
  528. if (old){
  529. // called again, e.g. in a loop
  530. delete this[id];
  531. old._Release(); // may fail
  532. }
  533. this[id]=intf;
  534. return intf;
  535. },
  536. free: function(){
  537. //console.log('rtl.intfRefs.free...');
  538. for (var id in this){
  539. if (this.hasOwnProperty(id)){
  540. //console.log('rtl.intfRefs.free: id='+id+' '+this[id].$name+' $o='+this[id].$o.$classname);
  541. this[id]._Release();
  542. }
  543. }
  544. }
  545. },
  546. createIntfRefs: function(){
  547. //console.log('rtl.createIntfRefs');
  548. return Object.create(rtl.intfRefs);
  549. },
  550. setIntfP: function(path,name,value,skipAddRef){
  551. var old = path[name];
  552. //console.log('rtl.setIntfP path='+path+' name='+name+' old="'+(old?old.$name:'null')+'" value="'+(value?value.$name:'null')+'"');
  553. if (old === value) return;
  554. if (old !== null){
  555. path[name]=null;
  556. old._Release();
  557. }
  558. if (value !== null){
  559. if (!skipAddRef) value._AddRef();
  560. path[name]=value;
  561. }
  562. },
  563. setIntfL: function(old,value,skipAddRef){
  564. //console.log('rtl.setIntfL old="'+(old?old.$name:'null')+'" value="'+(value?value.$name:'null')+'"');
  565. if (old !== value){
  566. if (value!==null){
  567. if (!skipAddRef) value._AddRef();
  568. }
  569. if (old!==null){
  570. old._Release(); // Release after AddRef, to avoid double Release if Release creates an exception
  571. }
  572. } else if (skipAddRef){
  573. if (old!==null){
  574. old._Release(); // value has an AddRef
  575. }
  576. }
  577. return value;
  578. },
  579. _AddRef: function(intf){
  580. //if (intf) console.log('rtl._AddRef intf="'+(intf?intf.$name:'null')+'"');
  581. if (intf) intf._AddRef();
  582. return intf;
  583. },
  584. _Release: function(intf){
  585. //if (intf) console.log('rtl._Release intf="'+(intf?intf.$name:'null')+'"');
  586. if (intf) intf._Release();
  587. return intf;
  588. },
  589. checkMethodCall: function(obj,type){
  590. if (rtl.isObject(obj) && rtl.is(obj,type)) return;
  591. rtl.raiseE("EInvalidCast");
  592. },
  593. rc: function(i,minval,maxval){
  594. // range check integer
  595. if ((Math.floor(i)===i) && (i>=minval) && (i<=maxval)) return i;
  596. rtl.raiseE('ERangeError');
  597. },
  598. rcc: function(c,minval,maxval){
  599. // range check char
  600. if ((typeof(c)==='string') && (c.length===1)){
  601. var i = c.charCodeAt(0);
  602. if ((i>=minval) && (i<=maxval)) return c;
  603. }
  604. rtl.raiseE('ERangeError');
  605. },
  606. rcSetCharAt: function(s,index,c){
  607. // range check setCharAt
  608. if ((typeof(s)!=='string') || (index<0) || (index>=s.length)) rtl.raiseE('ERangeError');
  609. return rtl.setCharAt(s,index,c);
  610. },
  611. rcCharAt: function(s,index){
  612. // range check charAt
  613. if ((typeof(s)!=='string') || (index<0) || (index>=s.length)) rtl.raiseE('ERangeError');
  614. return s.charAt(index);
  615. },
  616. rcArrR: function(arr,index){
  617. // range check read array
  618. if (Array.isArray(arr) && (typeof(index)==='number') && (index>=0) && (index<arr.length)){
  619. if (arguments.length>2){
  620. // arr,index1,index2,...
  621. arr=arr[index];
  622. for (var i=2; i<arguments.length; i++) arr=rtl.rcArrR(arr,arguments[i]);
  623. return arr;
  624. }
  625. return arr[index];
  626. }
  627. rtl.raiseE('ERangeError');
  628. },
  629. rcArrW: function(arr,index,value){
  630. // range check write array
  631. // arr,index1,index2,...,value
  632. for (var i=3; i<arguments.length; i++){
  633. arr=rtl.rcArrR(arr,index);
  634. index=arguments[i-1];
  635. value=arguments[i];
  636. }
  637. if (Array.isArray(arr) && (typeof(index)==='number') && (index>=0) && (index<arr.length)){
  638. return arr[index]=value;
  639. }
  640. rtl.raiseE('ERangeError');
  641. },
  642. length: function(arr){
  643. return (arr == null) ? 0 : arr.length;
  644. },
  645. arraySetLength: function(arr,defaultvalue,newlength){
  646. // multi dim: (arr,defaultvalue,dim1,dim2,...)
  647. if (arr == null) arr = [];
  648. var p = arguments;
  649. function setLength(a,argNo){
  650. var oldlen = a.length;
  651. var newlen = p[argNo];
  652. if (oldlen!==newlength){
  653. a.length = newlength;
  654. if (argNo === p.length-1){
  655. if (rtl.isArray(defaultvalue)){
  656. for (var i=oldlen; i<newlen; i++) a[i]=[]; // nested array
  657. } else if (rtl.isFunction(defaultvalue)){
  658. for (var i=oldlen; i<newlen; i++) a[i]=new defaultvalue(); // e.g. record
  659. } else if (rtl.isObject(defaultvalue)) {
  660. for (var i=oldlen; i<newlen; i++) a[i]={}; // e.g. set
  661. } else {
  662. for (var i=oldlen; i<newlen; i++) a[i]=defaultvalue;
  663. }
  664. } else {
  665. for (var i=oldlen; i<newlen; i++) a[i]=[]; // nested array
  666. }
  667. }
  668. if (argNo < p.length-1){
  669. // multi argNo
  670. for (var i=0; i<newlen; i++) a[i]=setLength(a[i],argNo+1);
  671. }
  672. return a;
  673. }
  674. return setLength(arr,2);
  675. },
  676. arrayEq: function(a,b){
  677. if (a===null) return b===null;
  678. if (b===null) return false;
  679. if (a.length!==b.length) return false;
  680. for (var i=0; i<a.length; i++) if (a[i]!==b[i]) return false;
  681. return true;
  682. },
  683. arrayClone: function(type,src,srcpos,endpos,dst,dstpos){
  684. // type: 0 for references, "refset" for calling refSet(), a function for new type()
  685. // src must not be null
  686. // This function does not range check.
  687. if (rtl.isFunction(type)){
  688. for (; srcpos<endpos; srcpos++) dst[dstpos++] = new type(src[srcpos]); // clone record
  689. } else if(type === 'refSet') {
  690. for (; srcpos<endpos; srcpos++) dst[dstpos++] = rtl.refSet(src[srcpos]); // ref set
  691. } else {
  692. for (; srcpos<endpos; srcpos++) dst[dstpos++] = src[srcpos]; // reference
  693. };
  694. },
  695. arrayConcat: function(type){
  696. // type: see rtl.arrayClone
  697. var a = [];
  698. var l = 0;
  699. for (var i=1; i<arguments.length; i++){
  700. var src = arguments[i];
  701. if (src !== null) l+=src.length;
  702. };
  703. a.length = l;
  704. l=0;
  705. for (var i=1; i<arguments.length; i++){
  706. var src = arguments[i];
  707. if (src === null) continue;
  708. rtl.arrayClone(type,src,0,src.length,a,l);
  709. l+=src.length;
  710. };
  711. return a;
  712. },
  713. arrayConcatN: function(){
  714. var a = null;
  715. for (var i=1; i<arguments.length; i++){
  716. var src = arguments[i];
  717. if (src === null) continue;
  718. if (a===null){
  719. a=src; // Note: concat(a) does not clone
  720. } else {
  721. a=a.concat(src);
  722. }
  723. };
  724. return a;
  725. },
  726. arrayCopy: function(type, srcarray, index, count){
  727. // type: see rtl.arrayClone
  728. // if count is missing, use srcarray.length
  729. if (srcarray === null) return [];
  730. if (index < 0) index = 0;
  731. if (count === undefined) count=srcarray.length;
  732. var end = index+count;
  733. if (end>srcarray.length) end = srcarray.length;
  734. if (index>=end) return [];
  735. if (type===0){
  736. return srcarray.slice(index,end);
  737. } else {
  738. var a = [];
  739. a.length = end-index;
  740. rtl.arrayClone(type,srcarray,index,end,a,0);
  741. return a;
  742. }
  743. },
  744. setCharAt: function(s,index,c){
  745. return s.substr(0,index)+c+s.substr(index+1);
  746. },
  747. getResStr: function(mod,name){
  748. var rs = mod.$resourcestrings[name];
  749. return rs.current?rs.current:rs.org;
  750. },
  751. createSet: function(){
  752. var s = {};
  753. for (var i=0; i<arguments.length; i++){
  754. if (arguments[i]!=null){
  755. s[arguments[i]]=true;
  756. } else {
  757. var first=arguments[i+=1];
  758. var last=arguments[i+=1];
  759. for(var j=first; j<=last; j++) s[j]=true;
  760. }
  761. }
  762. return s;
  763. },
  764. cloneSet: function(s){
  765. var r = {};
  766. for (var key in s) r[key]=true;
  767. return r;
  768. },
  769. refSet: function(s){
  770. Object.defineProperty(s, '$shared', {
  771. enumerable: false,
  772. configurable: true,
  773. writable: true,
  774. value: true
  775. });
  776. return s;
  777. },
  778. includeSet: function(s,enumvalue){
  779. if (s.$shared) s = rtl.cloneSet(s);
  780. s[enumvalue] = true;
  781. return s;
  782. },
  783. excludeSet: function(s,enumvalue){
  784. if (s.$shared) s = rtl.cloneSet(s);
  785. delete s[enumvalue];
  786. return s;
  787. },
  788. diffSet: function(s,t){
  789. var r = {};
  790. for (var key in s) if (!t[key]) r[key]=true;
  791. delete r.$shared;
  792. return r;
  793. },
  794. unionSet: function(s,t){
  795. var r = {};
  796. for (var key in s) r[key]=true;
  797. for (var key in t) r[key]=true;
  798. delete r.$shared;
  799. return r;
  800. },
  801. intersectSet: function(s,t){
  802. var r = {};
  803. for (var key in s) if (t[key]) r[key]=true;
  804. delete r.$shared;
  805. return r;
  806. },
  807. symDiffSet: function(s,t){
  808. var r = {};
  809. for (var key in s) if (!t[key]) r[key]=true;
  810. for (var key in t) if (!s[key]) r[key]=true;
  811. delete r.$shared;
  812. return r;
  813. },
  814. eqSet: function(s,t){
  815. for (var key in s) if (!t[key] && (key!='$shared')) return false;
  816. for (var key in t) if (!s[key] && (key!='$shared')) return false;
  817. return true;
  818. },
  819. neSet: function(s,t){
  820. return !rtl.eqSet(s,t);
  821. },
  822. leSet: function(s,t){
  823. for (var key in s) if (!t[key] && (key!='$shared')) return false;
  824. return true;
  825. },
  826. geSet: function(s,t){
  827. for (var key in t) if (!s[key] && (key!='$shared')) return false;
  828. return true;
  829. },
  830. strSetLength: function(s,newlen){
  831. var oldlen = s.length;
  832. if (oldlen > newlen){
  833. return s.substring(0,newlen);
  834. } else if (s.repeat){
  835. // Note: repeat needs ECMAScript6!
  836. return s+' '.repeat(newlen-oldlen);
  837. } else {
  838. while (oldlen<newlen){
  839. s+=' ';
  840. oldlen++;
  841. };
  842. return s;
  843. }
  844. },
  845. spaceLeft: function(s,width){
  846. var l=s.length;
  847. if (l>=width) return s;
  848. if (s.repeat){
  849. // Note: repeat needs ECMAScript6!
  850. return ' '.repeat(width-l) + s;
  851. } else {
  852. while (l<width){
  853. s=' '+s;
  854. l++;
  855. };
  856. };
  857. },
  858. floatToStr : function(d,w,p){
  859. // input 1-3 arguments: double, width, precision
  860. if (arguments.length>2){
  861. return rtl.spaceLeft(d.toFixed(p),w);
  862. } else {
  863. // exponent width
  864. var pad = "";
  865. var ad = Math.abs(d);
  866. if (ad<1.0e+10) {
  867. pad='00';
  868. } else if (ad<1.0e+100) {
  869. pad='0';
  870. }
  871. if (arguments.length<2) {
  872. w=9;
  873. } else if (w<9) {
  874. w=9;
  875. }
  876. var p = w-8;
  877. var s=(d>0 ? " " : "" ) + d.toExponential(p);
  878. s=s.replace(/e(.)/,'E$1'+pad);
  879. return rtl.spaceLeft(s,w);
  880. }
  881. },
  882. initRTTI: function(){
  883. if (rtl.debug_rtti) rtl.debug('initRTTI');
  884. // base types
  885. rtl.tTypeInfo = { name: "tTypeInfo" };
  886. function newBaseTI(name,kind,ancestor){
  887. if (!ancestor) ancestor = rtl.tTypeInfo;
  888. if (rtl.debug_rtti) rtl.debug('initRTTI.newBaseTI "'+name+'" '+kind+' ("'+ancestor.name+'")');
  889. var t = Object.create(ancestor);
  890. t.name = name;
  891. t.kind = kind;
  892. rtl[name] = t;
  893. return t;
  894. };
  895. function newBaseInt(name,minvalue,maxvalue,ordtype){
  896. var t = newBaseTI(name,1 /* tkInteger */,rtl.tTypeInfoInteger);
  897. t.minvalue = minvalue;
  898. t.maxvalue = maxvalue;
  899. t.ordtype = ordtype;
  900. return t;
  901. };
  902. newBaseTI("tTypeInfoInteger",1 /* tkInteger */);
  903. newBaseInt("shortint",-0x80,0x7f,0);
  904. newBaseInt("byte",0,0xff,1);
  905. newBaseInt("smallint",-0x8000,0x7fff,2);
  906. newBaseInt("word",0,0xffff,3);
  907. newBaseInt("longint",-0x80000000,0x7fffffff,4);
  908. newBaseInt("longword",0,0xffffffff,5);
  909. newBaseInt("nativeint",-0x10000000000000,0xfffffffffffff,6);
  910. newBaseInt("nativeuint",0,0xfffffffffffff,7);
  911. newBaseTI("char",2 /* tkChar */);
  912. newBaseTI("string",3 /* tkString */);
  913. newBaseTI("tTypeInfoEnum",4 /* tkEnumeration */,rtl.tTypeInfoInteger);
  914. newBaseTI("tTypeInfoSet",5 /* tkSet */);
  915. newBaseTI("double",6 /* tkDouble */);
  916. newBaseTI("boolean",7 /* tkBool */);
  917. newBaseTI("tTypeInfoProcVar",8 /* tkProcVar */);
  918. newBaseTI("tTypeInfoMethodVar",9 /* tkMethod */,rtl.tTypeInfoProcVar);
  919. newBaseTI("tTypeInfoArray",10 /* tkArray */);
  920. newBaseTI("tTypeInfoDynArray",11 /* tkDynArray */);
  921. newBaseTI("tTypeInfoPointer",15 /* tkPointer */);
  922. var t = newBaseTI("pointer",15 /* tkPointer */,rtl.tTypeInfoPointer);
  923. t.reftype = null;
  924. newBaseTI("jsvalue",16 /* tkJSValue */);
  925. newBaseTI("tTypeInfoRefToProcVar",17 /* tkRefToProcVar */,rtl.tTypeInfoProcVar);
  926. // member kinds
  927. rtl.tTypeMember = {};
  928. function newMember(name,kind){
  929. var m = Object.create(rtl.tTypeMember);
  930. m.name = name;
  931. m.kind = kind;
  932. rtl[name] = m;
  933. };
  934. newMember("tTypeMemberField",1); // tmkField
  935. newMember("tTypeMemberMethod",2); // tmkMethod
  936. newMember("tTypeMemberProperty",3); // tmkProperty
  937. // base object for storing members: a simple object
  938. rtl.tTypeMembers = {};
  939. // tTypeInfoStruct - base object for tTypeInfoClass, tTypeInfoRecord, tTypeInfoInterface
  940. var tis = newBaseTI("tTypeInfoStruct",0);
  941. tis.$addMember = function(name,ancestor,options){
  942. if (rtl.debug_rtti){
  943. if (!rtl.hasString(name) || (name.charAt()==='$')) throw 'invalid member "'+name+'", this="'+this.name+'"';
  944. if (!rtl.is(ancestor,rtl.tTypeMember)) throw 'invalid ancestor "'+ancestor+':'+ancestor.name+'", "'+this.name+'.'+name+'"';
  945. if ((options!=undefined) && (typeof(options)!='object')) throw 'invalid options "'+options+'", "'+this.name+'.'+name+'"';
  946. };
  947. var t = Object.create(ancestor);
  948. t.name = name;
  949. this.members[name] = t;
  950. this.names.push(name);
  951. if (rtl.isObject(options)){
  952. for (var key in options) if (options.hasOwnProperty(key)) t[key] = options[key];
  953. };
  954. return t;
  955. };
  956. tis.addField = function(name,type,options){
  957. var t = this.$addMember(name,rtl.tTypeMemberField,options);
  958. if (rtl.debug_rtti){
  959. if (!rtl.is(type,rtl.tTypeInfo)) throw 'invalid type "'+type+'", "'+this.name+'.'+name+'"';
  960. };
  961. t.typeinfo = type;
  962. this.fields.push(name);
  963. return t;
  964. };
  965. tis.addFields = function(){
  966. var i=0;
  967. while(i<arguments.length){
  968. var name = arguments[i++];
  969. var type = arguments[i++];
  970. if ((i<arguments.length) && (typeof(arguments[i])==='object')){
  971. this.addField(name,type,arguments[i++]);
  972. } else {
  973. this.addField(name,type);
  974. };
  975. };
  976. };
  977. tis.addMethod = function(name,methodkind,params,result,options){
  978. var t = this.$addMember(name,rtl.tTypeMemberMethod,options);
  979. t.methodkind = methodkind;
  980. t.procsig = rtl.newTIProcSig(params);
  981. t.procsig.resulttype = result?result:null;
  982. this.methods.push(name);
  983. return t;
  984. };
  985. tis.addProperty = function(name,flags,result,getter,setter,options){
  986. var t = this.$addMember(name,rtl.tTypeMemberProperty,options);
  987. t.flags = flags;
  988. t.typeinfo = result;
  989. t.getter = getter;
  990. t.setter = setter;
  991. // Note: in options: params, stored, defaultvalue
  992. if (rtl.isArray(t.params)) t.params = rtl.newTIParams(t.params);
  993. this.properties.push(name);
  994. if (!rtl.isString(t.stored)) t.stored = "";
  995. return t;
  996. };
  997. tis.getField = function(index){
  998. return this.members[this.fields[index]];
  999. };
  1000. tis.getMethod = function(index){
  1001. return this.members[this.methods[index]];
  1002. };
  1003. tis.getProperty = function(index){
  1004. return this.members[this.properties[index]];
  1005. };
  1006. newBaseTI("tTypeInfoRecord",12 /* tkRecord */,rtl.tTypeInfoStruct);
  1007. newBaseTI("tTypeInfoClass",13 /* tkClass */,rtl.tTypeInfoStruct);
  1008. newBaseTI("tTypeInfoClassRef",14 /* tkClassRef */);
  1009. newBaseTI("tTypeInfoInterface",15 /* tkInterface */,rtl.tTypeInfoStruct);
  1010. },
  1011. tSectionRTTI: {
  1012. $module: null,
  1013. $inherited: function(name,ancestor,o){
  1014. if (rtl.debug_rtti){
  1015. rtl.debug('tSectionRTTI.newTI "'+(this.$module?this.$module.$name:"(no module)")
  1016. +'"."'+name+'" ('+ancestor.name+') '+(o?'init':'forward'));
  1017. };
  1018. var t = this[name];
  1019. if (t){
  1020. if (!t.$forward) throw 'duplicate type "'+name+'"';
  1021. if (!ancestor.isPrototypeOf(t)) throw 'typeinfo ancestor mismatch "'+name+'" ancestor="'+ancestor.name+'" t.name="'+t.name+'"';
  1022. } else {
  1023. t = Object.create(ancestor);
  1024. t.name = name;
  1025. t.$module = this.$module;
  1026. this[name] = t;
  1027. }
  1028. if (o){
  1029. delete t.$forward;
  1030. for (var key in o) if (o.hasOwnProperty(key)) t[key]=o[key];
  1031. } else {
  1032. t.$forward = true;
  1033. }
  1034. return t;
  1035. },
  1036. $Scope: function(name,ancestor,o){
  1037. var t=this.$inherited(name,ancestor,o);
  1038. t.members = {};
  1039. t.names = [];
  1040. t.fields = [];
  1041. t.methods = [];
  1042. t.properties = [];
  1043. return t;
  1044. },
  1045. $TI: function(name,kind,o){ var t=this.$inherited(name,rtl.tTypeInfo,o); t.kind = kind; return t; },
  1046. $Int: function(name,o){ return this.$inherited(name,rtl.tTypeInfoInteger,o); },
  1047. $Enum: function(name,o){ return this.$inherited(name,rtl.tTypeInfoEnum,o); },
  1048. $Set: function(name,o){ return this.$inherited(name,rtl.tTypeInfoSet,o); },
  1049. $StaticArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoArray,o); },
  1050. $DynArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoDynArray,o); },
  1051. $ProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoProcVar,o); },
  1052. $RefToProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoRefToProcVar,o); },
  1053. $MethodVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoMethodVar,o); },
  1054. $Record: function(name,o){ return this.$Scope(name,rtl.tTypeInfoRecord,o); },
  1055. $Class: function(name,o){ return this.$Scope(name,rtl.tTypeInfoClass,o); },
  1056. $ClassRef: function(name,o){ return this.$inherited(name,rtl.tTypeInfoClassRef,o); },
  1057. $Pointer: function(name,o){ return this.$inherited(name,rtl.tTypeInfoPointer,o); },
  1058. $Interface: function(name,o){ return this.$Scope(name,rtl.tTypeInfoInterface,o); }
  1059. },
  1060. newTIParam: function(param){
  1061. // param is an array, 0=name, 1=type, 2=optional flags
  1062. var t = {
  1063. name: param[0],
  1064. typeinfo: param[1],
  1065. flags: (rtl.isNumber(param[2]) ? param[2] : 0)
  1066. };
  1067. return t;
  1068. },
  1069. newTIParams: function(list){
  1070. // list: optional array of [paramname,typeinfo,optional flags]
  1071. var params = [];
  1072. if (rtl.isArray(list)){
  1073. for (var i=0; i<list.length; i++) params.push(rtl.newTIParam(list[i]));
  1074. };
  1075. return params;
  1076. },
  1077. newTIProcSig: function(params,result,flags){
  1078. var s = {
  1079. params: rtl.newTIParams(params),
  1080. resulttype: result,
  1081. flags: flags
  1082. };
  1083. return s;
  1084. }
  1085. }