rtl.js 35 KB

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