rtl.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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. return r;
  792. },
  793. unionSet: function(s,t){
  794. var r = {};
  795. for (var key in s) r[key]=true;
  796. for (var key in t) r[key]=true;
  797. return r;
  798. },
  799. intersectSet: function(s,t){
  800. var r = {};
  801. for (var key in s) if (t[key]) r[key]=true;
  802. return r;
  803. },
  804. symDiffSet: function(s,t){
  805. var r = {};
  806. for (var key in s) if (!t[key]) r[key]=true;
  807. for (var key in t) if (!s[key]) r[key]=true;
  808. return r;
  809. },
  810. eqSet: function(s,t){
  811. for (var key in s) if (!t[key]) return false;
  812. for (var key in t) if (!s[key]) return false;
  813. return true;
  814. },
  815. neSet: function(s,t){
  816. return !rtl.eqSet(s,t);
  817. },
  818. leSet: function(s,t){
  819. for (var key in s) if (!t[key]) return false;
  820. return true;
  821. },
  822. geSet: function(s,t){
  823. for (var key in t) if (!s[key]) return false;
  824. return true;
  825. },
  826. strSetLength: function(s,newlen){
  827. var oldlen = s.length;
  828. if (oldlen > newlen){
  829. return s.substring(0,newlen);
  830. } else if (s.repeat){
  831. // Note: repeat needs ECMAScript6!
  832. return s+' '.repeat(newlen-oldlen);
  833. } else {
  834. while (oldlen<newlen){
  835. s+=' ';
  836. oldlen++;
  837. };
  838. return s;
  839. }
  840. },
  841. spaceLeft: function(s,width){
  842. var l=s.length;
  843. if (l>=width) return s;
  844. if (s.repeat){
  845. // Note: repeat needs ECMAScript6!
  846. return ' '.repeat(width-l) + s;
  847. } else {
  848. while (l<width){
  849. s=' '+s;
  850. l++;
  851. };
  852. };
  853. },
  854. floatToStr : function(d,w,p){
  855. // input 1-3 arguments: double, width, precision
  856. if (arguments.length>2){
  857. return rtl.spaceLeft(d.toFixed(p),w);
  858. } else {
  859. // exponent width
  860. var pad = "";
  861. var ad = Math.abs(d);
  862. if (ad<1.0e+10) {
  863. pad='00';
  864. } else if (ad<1.0e+100) {
  865. pad='0';
  866. }
  867. if (arguments.length<2) {
  868. w=9;
  869. } else if (w<9) {
  870. w=9;
  871. }
  872. var p = w-8;
  873. var s=(d>0 ? " " : "" ) + d.toExponential(p);
  874. s=s.replace(/e(.)/,'E$1'+pad);
  875. return rtl.spaceLeft(s,w);
  876. }
  877. },
  878. initRTTI: function(){
  879. if (rtl.debug_rtti) rtl.debug('initRTTI');
  880. // base types
  881. rtl.tTypeInfo = { name: "tTypeInfo" };
  882. function newBaseTI(name,kind,ancestor){
  883. if (!ancestor) ancestor = rtl.tTypeInfo;
  884. if (rtl.debug_rtti) rtl.debug('initRTTI.newBaseTI "'+name+'" '+kind+' ("'+ancestor.name+'")');
  885. var t = Object.create(ancestor);
  886. t.name = name;
  887. t.kind = kind;
  888. rtl[name] = t;
  889. return t;
  890. };
  891. function newBaseInt(name,minvalue,maxvalue,ordtype){
  892. var t = newBaseTI(name,1 /* tkInteger */,rtl.tTypeInfoInteger);
  893. t.minvalue = minvalue;
  894. t.maxvalue = maxvalue;
  895. t.ordtype = ordtype;
  896. return t;
  897. };
  898. newBaseTI("tTypeInfoInteger",1 /* tkInteger */);
  899. newBaseInt("shortint",-0x80,0x7f,0);
  900. newBaseInt("byte",0,0xff,1);
  901. newBaseInt("smallint",-0x8000,0x7fff,2);
  902. newBaseInt("word",0,0xffff,3);
  903. newBaseInt("longint",-0x80000000,0x7fffffff,4);
  904. newBaseInt("longword",0,0xffffffff,5);
  905. newBaseInt("nativeint",-0x10000000000000,0xfffffffffffff,6);
  906. newBaseInt("nativeuint",0,0xfffffffffffff,7);
  907. newBaseTI("char",2 /* tkChar */);
  908. newBaseTI("string",3 /* tkString */);
  909. newBaseTI("tTypeInfoEnum",4 /* tkEnumeration */,rtl.tTypeInfoInteger);
  910. newBaseTI("tTypeInfoSet",5 /* tkSet */);
  911. newBaseTI("double",6 /* tkDouble */);
  912. newBaseTI("boolean",7 /* tkBool */);
  913. newBaseTI("tTypeInfoProcVar",8 /* tkProcVar */);
  914. newBaseTI("tTypeInfoMethodVar",9 /* tkMethod */,rtl.tTypeInfoProcVar);
  915. newBaseTI("tTypeInfoArray",10 /* tkArray */);
  916. newBaseTI("tTypeInfoDynArray",11 /* tkDynArray */);
  917. newBaseTI("tTypeInfoPointer",15 /* tkPointer */);
  918. var t = newBaseTI("pointer",15 /* tkPointer */,rtl.tTypeInfoPointer);
  919. t.reftype = null;
  920. newBaseTI("jsvalue",16 /* tkJSValue */);
  921. newBaseTI("tTypeInfoRefToProcVar",17 /* tkRefToProcVar */,rtl.tTypeInfoProcVar);
  922. // member kinds
  923. rtl.tTypeMember = {};
  924. function newMember(name,kind){
  925. var m = Object.create(rtl.tTypeMember);
  926. m.name = name;
  927. m.kind = kind;
  928. rtl[name] = m;
  929. };
  930. newMember("tTypeMemberField",1); // tmkField
  931. newMember("tTypeMemberMethod",2); // tmkMethod
  932. newMember("tTypeMemberProperty",3); // tmkProperty
  933. // base object for storing members: a simple object
  934. rtl.tTypeMembers = {};
  935. // tTypeInfoStruct - base object for tTypeInfoClass, tTypeInfoRecord, tTypeInfoInterface
  936. var tis = newBaseTI("tTypeInfoStruct",0);
  937. tis.$addMember = function(name,ancestor,options){
  938. if (rtl.debug_rtti){
  939. if (!rtl.hasString(name) || (name.charAt()==='$')) throw 'invalid member "'+name+'", this="'+this.name+'"';
  940. if (!rtl.is(ancestor,rtl.tTypeMember)) throw 'invalid ancestor "'+ancestor+':'+ancestor.name+'", "'+this.name+'.'+name+'"';
  941. if ((options!=undefined) && (typeof(options)!='object')) throw 'invalid options "'+options+'", "'+this.name+'.'+name+'"';
  942. };
  943. var t = Object.create(ancestor);
  944. t.name = name;
  945. this.members[name] = t;
  946. this.names.push(name);
  947. if (rtl.isObject(options)){
  948. for (var key in options) if (options.hasOwnProperty(key)) t[key] = options[key];
  949. };
  950. return t;
  951. };
  952. tis.addField = function(name,type,options){
  953. var t = this.$addMember(name,rtl.tTypeMemberField,options);
  954. if (rtl.debug_rtti){
  955. if (!rtl.is(type,rtl.tTypeInfo)) throw 'invalid type "'+type+'", "'+this.name+'.'+name+'"';
  956. };
  957. t.typeinfo = type;
  958. this.fields.push(name);
  959. return t;
  960. };
  961. tis.addFields = function(){
  962. var i=0;
  963. while(i<arguments.length){
  964. var name = arguments[i++];
  965. var type = arguments[i++];
  966. if ((i<arguments.length) && (typeof(arguments[i])==='object')){
  967. this.addField(name,type,arguments[i++]);
  968. } else {
  969. this.addField(name,type);
  970. };
  971. };
  972. };
  973. tis.addMethod = function(name,methodkind,params,result,options){
  974. var t = this.$addMember(name,rtl.tTypeMemberMethod,options);
  975. t.methodkind = methodkind;
  976. t.procsig = rtl.newTIProcSig(params);
  977. t.procsig.resulttype = result?result:null;
  978. this.methods.push(name);
  979. return t;
  980. };
  981. tis.addProperty = function(name,flags,result,getter,setter,options){
  982. var t = this.$addMember(name,rtl.tTypeMemberProperty,options);
  983. t.flags = flags;
  984. t.typeinfo = result;
  985. t.getter = getter;
  986. t.setter = setter;
  987. // Note: in options: params, stored, defaultvalue
  988. if (rtl.isArray(t.params)) t.params = rtl.newTIParams(t.params);
  989. this.properties.push(name);
  990. if (!rtl.isString(t.stored)) t.stored = "";
  991. return t;
  992. };
  993. tis.getField = function(index){
  994. return this.members[this.fields[index]];
  995. };
  996. tis.getMethod = function(index){
  997. return this.members[this.methods[index]];
  998. };
  999. tis.getProperty = function(index){
  1000. return this.members[this.properties[index]];
  1001. };
  1002. newBaseTI("tTypeInfoRecord",12 /* tkRecord */,rtl.tTypeInfoStruct);
  1003. newBaseTI("tTypeInfoClass",13 /* tkClass */,rtl.tTypeInfoStruct);
  1004. newBaseTI("tTypeInfoClassRef",14 /* tkClassRef */);
  1005. newBaseTI("tTypeInfoInterface",15 /* tkInterface */,rtl.tTypeInfoStruct);
  1006. },
  1007. tSectionRTTI: {
  1008. $module: null,
  1009. $inherited: function(name,ancestor,o){
  1010. if (rtl.debug_rtti){
  1011. rtl.debug('tSectionRTTI.newTI "'+(this.$module?this.$module.$name:"(no module)")
  1012. +'"."'+name+'" ('+ancestor.name+') '+(o?'init':'forward'));
  1013. };
  1014. var t = this[name];
  1015. if (t){
  1016. if (!t.$forward) throw 'duplicate type "'+name+'"';
  1017. if (!ancestor.isPrototypeOf(t)) throw 'typeinfo ancestor mismatch "'+name+'" ancestor="'+ancestor.name+'" t.name="'+t.name+'"';
  1018. } else {
  1019. t = Object.create(ancestor);
  1020. t.name = name;
  1021. t.$module = this.$module;
  1022. this[name] = t;
  1023. }
  1024. if (o){
  1025. delete t.$forward;
  1026. for (var key in o) if (o.hasOwnProperty(key)) t[key]=o[key];
  1027. } else {
  1028. t.$forward = true;
  1029. }
  1030. return t;
  1031. },
  1032. $Scope: function(name,ancestor,o){
  1033. var t=this.$inherited(name,ancestor,o);
  1034. t.members = {};
  1035. t.names = [];
  1036. t.fields = [];
  1037. t.methods = [];
  1038. t.properties = [];
  1039. return t;
  1040. },
  1041. $TI: function(name,kind,o){ var t=this.$inherited(name,rtl.tTypeInfo,o); t.kind = kind; return t; },
  1042. $Int: function(name,o){ return this.$inherited(name,rtl.tTypeInfoInteger,o); },
  1043. $Enum: function(name,o){ return this.$inherited(name,rtl.tTypeInfoEnum,o); },
  1044. $Set: function(name,o){ return this.$inherited(name,rtl.tTypeInfoSet,o); },
  1045. $StaticArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoArray,o); },
  1046. $DynArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoDynArray,o); },
  1047. $ProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoProcVar,o); },
  1048. $RefToProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoRefToProcVar,o); },
  1049. $MethodVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoMethodVar,o); },
  1050. $Record: function(name,o){ return this.$Scope(name,rtl.tTypeInfoRecord,o); },
  1051. $Class: function(name,o){ return this.$Scope(name,rtl.tTypeInfoClass,o); },
  1052. $ClassRef: function(name,o){ return this.$inherited(name,rtl.tTypeInfoClassRef,o); },
  1053. $Pointer: function(name,o){ return this.$inherited(name,rtl.tTypeInfoPointer,o); },
  1054. $Interface: function(name,o){ return this.$Scope(name,rtl.tTypeInfoInterface,o); }
  1055. },
  1056. newTIParam: function(param){
  1057. // param is an array, 0=name, 1=type, 2=optional flags
  1058. var t = {
  1059. name: param[0],
  1060. typeinfo: param[1],
  1061. flags: (rtl.isNumber(param[2]) ? param[2] : 0)
  1062. };
  1063. return t;
  1064. },
  1065. newTIParams: function(list){
  1066. // list: optional array of [paramname,typeinfo,optional flags]
  1067. var params = [];
  1068. if (rtl.isArray(list)){
  1069. for (var i=0; i<list.length; i++) params.push(rtl.newTIParam(list[i]));
  1070. };
  1071. return params;
  1072. },
  1073. newTIProcSig: function(params,result,flags){
  1074. var s = {
  1075. params: rtl.newTIParams(params),
  1076. resulttype: result,
  1077. flags: flags
  1078. };
  1079. return s;
  1080. }
  1081. }