Boot.hx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package php;
  23. import haxe.PosInfos;
  24. import haxe.extern.EitherType;
  25. using php.Global;
  26. /**
  27. Various Haxe->PHP compatibility utilities.
  28. You should not use this class directly.
  29. **/
  30. @:keep
  31. @:dox(hide)
  32. class Boot {
  33. /** List of Haxe classes registered by their PHP class names */
  34. @:protected static var aliases = new NativeAssocArray<String>();
  35. /** Cache of HxClass instances */
  36. @:protected static var classes = new NativeAssocArray<HxClass>();
  37. /** List of getters (for Reflect) */
  38. @:protected static var getters = new NativeAssocArray<NativeAssocArray<Bool>>();
  39. /** List of setters (for Reflect) */
  40. @:protected static var setters = new NativeAssocArray<NativeAssocArray<Bool>>();
  41. /** Metadata storage */
  42. @:protected static var meta = new NativeAssocArray<{}>();
  43. /** Cache for closures created of static methods */
  44. @:protected static var staticClosures = new NativeAssocArray<NativeAssocArray<HxClosure>>();
  45. /**
  46. Initialization stuff.
  47. This method is called once before invoking any Haxe-generated user code.
  48. **/
  49. static function __init__() {
  50. Global.mb_internal_encoding('UTF-8');
  51. if (!Global.defined('HAXE_CUSTOM_ERROR_HANDLER') || !Const.HAXE_CUSTOM_ERROR_HANDLER) {
  52. var previousLevel = Global.error_reporting(Const.E_ALL);
  53. var previousHandler = Global.set_error_handler(function(errno:Int, errstr:String, errfile:String, errline:Int) {
  54. if (Global.error_reporting() & errno == 0) {
  55. return false;
  56. }
  57. /*
  58. * Division by zero should not throw
  59. * @see https://github.com/HaxeFoundation/haxe/issues/7034#issuecomment-394264544
  60. */
  61. if (errno == Const.E_WARNING && errstr == 'Division by zero') {
  62. return true;
  63. }
  64. throw new ErrorException(errstr, 0, errno, errfile, errline);
  65. });
  66. // Already had user-defined handler. Return it.
  67. if (previousHandler != null) {
  68. Global.error_reporting(previousLevel);
  69. Global.set_error_handler(previousHandler);
  70. }
  71. }
  72. }
  73. /**
  74. Returns root namespace based on a value of `-D php-prefix=value` compiler flag.
  75. Returns empty string if no `-D php-prefix=value` provided.
  76. **/
  77. public static function getPrefix():String {
  78. return Syntax.code('self::PHP_PREFIX');
  79. }
  80. /**
  81. Register list of getters to be able to call getters using reflection
  82. **/
  83. public static function registerGetters(phpClassName:String, list:NativeAssocArray<Bool>):Void {
  84. getters[phpClassName] = list;
  85. }
  86. /**
  87. Register list of setters to be able to call getters using reflection
  88. **/
  89. public static function registerSetters(phpClassName:String, list:NativeAssocArray<Bool>):Void {
  90. setters[phpClassName] = list;
  91. }
  92. /**
  93. Check if specified property has getter
  94. **/
  95. public static function hasGetter(phpClassName:String, property:String):Bool {
  96. ensureLoaded(phpClassName);
  97. var has = false;
  98. var phpClassName:haxe.extern.EitherType<Bool, String> = phpClassName;
  99. do {
  100. has = Global.isset(getters[phpClassName][property]);
  101. phpClassName = Global.get_parent_class(phpClassName);
  102. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  103. return has;
  104. }
  105. /**
  106. Check if specified property has setter
  107. **/
  108. public static function hasSetter(phpClassName:String, property:String):Bool {
  109. ensureLoaded(phpClassName);
  110. var has = false;
  111. var phpClassName:haxe.extern.EitherType<Bool, String> = phpClassName;
  112. do {
  113. has = Global.isset(setters[phpClassName][property]);
  114. phpClassName = Global.get_parent_class(phpClassName);
  115. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  116. return has;
  117. }
  118. /**
  119. Save metadata for specified class
  120. **/
  121. public static function registerMeta(phpClassName:String, data:Dynamic):Void {
  122. meta[phpClassName] = data;
  123. }
  124. /**
  125. Retrieve metadata for specified class
  126. **/
  127. public static function getMeta(phpClassName:String):Null<Dynamic> {
  128. ensureLoaded(phpClassName);
  129. return Global.isset(meta[phpClassName]) ? meta[phpClassName] : null;
  130. }
  131. /**
  132. Associate PHP class name with Haxe class name
  133. **/
  134. public static function registerClass(phpClassName:String, haxeClassName:String):Void {
  135. aliases[phpClassName] = haxeClassName;
  136. }
  137. /**
  138. Returns a list of currently loaded haxe-generated classes.
  139. **/
  140. public static function getRegisteredClasses():Array<Class<Dynamic>> {
  141. var result = [];
  142. Syntax.foreach(aliases, function(phpName, haxeName) {
  143. result.push(cast getClass(phpName));
  144. });
  145. return result;
  146. }
  147. /**
  148. Returns a list of phpName=>haxeName for currently loaded haxe-generated classes.
  149. **/
  150. public static function getRegisteredAliases():NativeAssocArray<String> {
  151. return aliases;
  152. }
  153. /**
  154. Get Class<T> instance for PHP fully qualified class name (E.g. '\some\pack\MyClass')
  155. It's always the same instance for the same `phpClassName`
  156. **/
  157. public static function getClass(phpClassName:String):HxClass {
  158. if (phpClassName.charAt(0) == '\\') {
  159. phpClassName = phpClassName.substr(1);
  160. }
  161. if (!Global.isset(classes[phpClassName])) {
  162. classes[phpClassName] = new HxClass(phpClassName);
  163. }
  164. return classes[phpClassName];
  165. }
  166. /**
  167. Returns Class<HxAnon>
  168. **/
  169. public static inline function getHxAnon():HxClass {
  170. return cast HxAnon;
  171. }
  172. /**
  173. Check if provided value is an anonymous object
  174. **/
  175. public static inline function isAnon(v:Any):Bool {
  176. return Std.is(v, HxAnon);
  177. }
  178. /**
  179. Returns Class<HxClass>
  180. **/
  181. public static inline function getHxClass():HxClass {
  182. return cast HxClass;
  183. }
  184. /**
  185. Returns either Haxe class name for specified `phpClassName` or (if no such Haxe class registered) `phpClassName`.
  186. **/
  187. public static function getClassName(phpClassName:String):String {
  188. var hxClass = getClass(phpClassName);
  189. var name = getHaxeName(hxClass);
  190. return (name == null ? hxClass.phpClassName : name);
  191. }
  192. /**
  193. Returns original Haxe fully qualified class name for this type (if exists)
  194. **/
  195. public static function getHaxeName(hxClass:HxClass):Null<String> {
  196. switch (hxClass.phpClassName) {
  197. case 'Int':
  198. return 'Int';
  199. case 'String':
  200. return 'String';
  201. case 'Bool':
  202. return 'Bool';
  203. case 'Float':
  204. return 'Float';
  205. case 'Class':
  206. return 'Class';
  207. case 'Enum':
  208. return 'Enum';
  209. case 'Dynamic':
  210. return 'Dynamic';
  211. case _:
  212. }
  213. inline function exists()
  214. return Global.isset(aliases[hxClass.phpClassName]);
  215. if (exists()) {
  216. return aliases[hxClass.phpClassName];
  217. } else if (Global.class_exists(hxClass.phpClassName) && exists()) {
  218. return aliases[hxClass.phpClassName];
  219. } else if (Global.interface_exists(hxClass.phpClassName) && exists()) {
  220. return aliases[hxClass.phpClassName];
  221. }
  222. return null;
  223. }
  224. /**
  225. Find corresponding PHP class name.
  226. Returns `null` if specified class does not exist.
  227. **/
  228. public static function getPhpName(haxeName:String):Null<String> {
  229. var prefix = getPrefix();
  230. var phpParts = (Global.strlen(prefix) == 0 ? [] : [prefix]);
  231. var haxeParts = haxeName.split('.');
  232. for (part in haxeParts) {
  233. if (isPhpKeyword(part)) {
  234. part += '_hx';
  235. }
  236. phpParts.push(part);
  237. }
  238. return phpParts.join('\\');
  239. }
  240. /**
  241. Check if the value of `str` is a reserved keyword in PHP
  242. @see https://www.php.net/manual/en/reserved.keywords.php
  243. **/
  244. @:pure(false)
  245. static public function isPhpKeyword(str:String):Bool {
  246. //The body of this method is generated by the compiler
  247. return false;
  248. }
  249. /**
  250. Unsafe cast to HxClosure
  251. **/
  252. public static inline function castClosure(value:Dynamic):HxClosure {
  253. return value;
  254. }
  255. /**
  256. Unsafe cast to HxClass
  257. **/
  258. public static inline function castClass(cls:Class<Dynamic>):HxClass {
  259. return cast cls;
  260. }
  261. /**
  262. Unsafe cast to HxEnum
  263. **/
  264. public static inline function castEnumValue(enm:EnumValue):HxEnum {
  265. return cast enm;
  266. }
  267. /**
  268. Returns `Class<T>` for `HxClosure`
  269. **/
  270. public static inline function closureHxClass():HxClass {
  271. return cast HxClosure;
  272. }
  273. /**
  274. Implementation for `cast(value, Class<Dynamic>)`
  275. @throws HxException if `value` cannot be casted to this type
  276. **/
  277. public static function typedCast(hxClass:HxClass, value:Dynamic):Dynamic {
  278. if (value == null)
  279. return null;
  280. switch (hxClass.phpClassName) {
  281. case 'Int':
  282. if (Boot.isNumber(value)) {
  283. return Global.intval(value);
  284. }
  285. case 'Float':
  286. if (Boot.isNumber(value)) {
  287. return value.floatval();
  288. }
  289. case 'Bool':
  290. if (value.is_bool()) {
  291. return value;
  292. }
  293. case 'String':
  294. if (value.is_string()) {
  295. return value;
  296. }
  297. case 'php\\NativeArray':
  298. if (value.is_array()) {
  299. return value;
  300. }
  301. case _:
  302. if (value.is_object() && Std.is(value, cast hxClass)) {
  303. return value;
  304. }
  305. }
  306. throw 'Cannot cast ' + Std.string(value) + ' to ' + getClassName(hxClass.phpClassName);
  307. }
  308. /**
  309. Returns string representation of `value`
  310. **/
  311. public static function stringify(value:Dynamic, maxRecursion:Int = 10):String {
  312. if (maxRecursion <= 0) {
  313. return '<...>';
  314. }
  315. if (value == null) {
  316. return 'null';
  317. }
  318. if (value.is_string()) {
  319. return value;
  320. }
  321. if (value.is_int() || value.is_float()) {
  322. return Syntax.string(value);
  323. }
  324. if (value.is_bool()) {
  325. return value ? 'true' : 'false';
  326. }
  327. if (value.is_array()) {
  328. var strings = Syntax.arrayDecl();
  329. Syntax.foreach(value, function(key:Dynamic, item:Dynamic) {
  330. strings.push(Syntax.string(key) + ' => ' + stringify(item, maxRecursion - 1));
  331. });
  332. return '[' + Global.implode(', ', strings) + ']';
  333. }
  334. if (value.is_object()) {
  335. if (Std.is(value, Array)) {
  336. return inline stringifyNativeIndexedArray(value.arr, maxRecursion - 1);
  337. }
  338. if (Std.is(value, HxEnum)) {
  339. var e:HxEnum = value;
  340. var result = e.tag;
  341. if (Global.count(e.params) > 0) {
  342. var strings = Global.array_map(function(item) return Boot.stringify(item, maxRecursion - 1), e.params);
  343. result += '(' + Global.implode(',', strings) + ')';
  344. }
  345. return result;
  346. }
  347. if (value.method_exists('toString')) {
  348. return value.toString();
  349. }
  350. if (value.method_exists('__toString')) {
  351. return value.__toString();
  352. }
  353. if (Std.is(value, StdClass)) {
  354. if (Global.isset(Syntax.field(value, 'toString')) && value.toString.is_callable()) {
  355. return value.toString();
  356. }
  357. var result = new NativeIndexedArray<String>();
  358. var data = Global.get_object_vars(value);
  359. for (key in data.array_keys()) {
  360. result.array_push('$key : ' + stringify(data[key], maxRecursion - 1));
  361. }
  362. return '{ ' + Global.implode(', ', result) + ' }';
  363. }
  364. if (isFunction(value)) {
  365. return '<function>';
  366. }
  367. if (Std.is(value, HxClass)) {
  368. return '[class ' + getClassName((value : HxClass).phpClassName) + ']';
  369. } else {
  370. return '[object ' + getClassName(Global.get_class(value)) + ']';
  371. }
  372. }
  373. throw "Unable to stringify value";
  374. }
  375. static public function stringifyNativeIndexedArray<T>(arr:NativeIndexedArray<T>, maxRecursion:Int = 10):String {
  376. var strings = Syntax.arrayDecl();
  377. Syntax.foreach(arr, function(index:Int, value:T) {
  378. strings[index] = Boot.stringify(value, maxRecursion - 1);
  379. });
  380. return '[' + Global.implode(',', strings) + ']';
  381. }
  382. static public inline function isNumber(value:Dynamic) {
  383. return value.is_int() || value.is_float();
  384. }
  385. /**
  386. Check if specified values are equal
  387. **/
  388. public static function equal(left:Dynamic, right:Dynamic):Bool {
  389. if (isNumber(left) && isNumber(right)) {
  390. return Syntax.equal(left, right);
  391. }
  392. if (Std.is(left, HxClosure) && Std.is(right, HxClosure)) {
  393. return (left : HxClosure).equals(right);
  394. }
  395. return Syntax.strictEqual(left, right);
  396. }
  397. /**
  398. Concat `left` and `right` if both are strings or string and null.
  399. Otherwise return sum of `left` and `right`.
  400. **/
  401. public static function addOrConcat(left:Dynamic, right:Dynamic):Dynamic {
  402. if (left.is_string() || right.is_string()) {
  403. return (left : String) + (right : String);
  404. }
  405. return Syntax.add(left, right);
  406. }
  407. /**
  408. `Std.is()` implementation
  409. **/
  410. public static function is(value:Dynamic, type:HxClass):Bool {
  411. if (type == null)
  412. return false;
  413. var phpType = type.phpClassName;
  414. #if php_prefix
  415. var prefix = getPrefix();
  416. if (Global.substr(phpType, 0, Global.strlen(prefix) + 1) == '$prefix\\') {
  417. phpType = Global.substr(phpType, Global.strlen(prefix) + 1);
  418. }
  419. #end
  420. switch (phpType) {
  421. case 'Dynamic':
  422. return value != null;
  423. case 'Int':
  424. return (value.is_int() || (value.is_float() && Syntax.equal(Syntax.int(value), value) && !Global.is_nan(value)))
  425. && Global.abs(value) <= 2147483648;
  426. case 'Float':
  427. return value.is_float() || value.is_int();
  428. case 'Bool':
  429. return value.is_bool();
  430. case 'String':
  431. return value.is_string();
  432. case 'php\\NativeArray', 'php\\_NativeArray\\NativeArray_Impl_':
  433. return value.is_array();
  434. case 'Enum' | 'Class':
  435. if (Std.is(value, HxClass)) {
  436. var valuePhpClass = (cast value : HxClass).phpClassName;
  437. var enumPhpClass = (cast HxEnum : HxClass).phpClassName;
  438. var isEnumType = Global.is_subclass_of(valuePhpClass, enumPhpClass);
  439. return (phpType == 'Enum' ? isEnumType : !isEnumType);
  440. }
  441. case _:
  442. if (value.is_object()) {
  443. var type:Class<Dynamic> = cast type;
  444. return Syntax.instanceof(value, type);
  445. }
  446. }
  447. return false;
  448. }
  449. /**
  450. Check if `value` is a `Class<T>`
  451. **/
  452. public static inline function isClass(value:Dynamic):Bool {
  453. return Std.is(value, HxClass);
  454. }
  455. /**
  456. Check if `value` is an enum constructor instance
  457. **/
  458. public static inline function isEnumValue(value:Dynamic):Bool {
  459. return Std.is(value, HxEnum);
  460. }
  461. /**
  462. Check if `value` is a function
  463. **/
  464. public static inline function isFunction(value:Dynamic):Bool {
  465. return Std.is(value, Closure) || Std.is(value, HxClosure);
  466. }
  467. /**
  468. Check if `value` is an instance of `HxClosure`
  469. **/
  470. public static inline function isHxClosure(value:Dynamic):Bool {
  471. return Std.is(value, HxClosure);
  472. }
  473. /**
  474. Performs `left >>> right` operation
  475. **/
  476. public static function shiftRightUnsigned(left:Int, right:Int):Int {
  477. if (right == 0) {
  478. return left;
  479. } else if (left >= 0) {
  480. return (left >> right) & ~((1 << (8 * Const.PHP_INT_SIZE - 1)) >> (right - 1));
  481. } else {
  482. return (left >> right) & (0x7fffffff >> (right - 1));
  483. }
  484. }
  485. /**
  486. Helper method to avoid "Cannot use temporary expression in write context" error for expressions like this:
  487. ```haxe
  488. (new MyClass()).fieldName = 'value';
  489. ```
  490. **/
  491. static public function deref(value:Dynamic):Dynamic {
  492. return value;
  493. }
  494. /**
  495. Create Haxe-compatible anonymous structure of `data` associative array
  496. **/
  497. static public inline function createAnon(data:NativeArray):Dynamic {
  498. return new HxAnon(data);
  499. }
  500. /**
  501. Make sure specified class is loaded
  502. **/
  503. static public inline function ensureLoaded(phpClassName:String):Bool {
  504. return Global.class_exists(phpClassName) || Global.interface_exists(phpClassName);
  505. }
  506. /**
  507. Get `field` of a dynamic `value` in a safe manner (avoid exceptions on trying to get a method)
  508. **/
  509. static public function dynamicField(value:Dynamic, field:String):Dynamic {
  510. if (Global.method_exists(value, field)) {
  511. return closure(value, field);
  512. }
  513. if (Global.is_string(value)) {
  514. value = @:privateAccess new HxDynamicStr(value);
  515. }
  516. return Syntax.field(value, field);
  517. }
  518. public static function dynamicString(str:String):HxDynamicStr {
  519. return @:privateAccess new HxDynamicStr(str);
  520. }
  521. /**
  522. Creates Haxe-compatible closure of an instance method.
  523. @param obj - any object
  524. **/
  525. public static function getInstanceClosure(obj:{?__hx_closureCache:NativeAssocArray<HxClosure>}, methodName:String) {
  526. var result = Syntax.coalesce(obj.__hx_closureCache[methodName], null);
  527. if (result != null) {
  528. return result;
  529. }
  530. result = new HxClosure(obj, methodName);
  531. if (!Global.property_exists(obj, '__hx_closureCache')) {
  532. obj.__hx_closureCache = new NativeAssocArray();
  533. }
  534. obj.__hx_closureCache[methodName] = result;
  535. return result;
  536. }
  537. /**
  538. Creates Haxe-compatible closure of a static method.
  539. **/
  540. public static function getStaticClosure(phpClassName:String, methodName:String) {
  541. var result = Syntax.coalesce(staticClosures[phpClassName][methodName], null);
  542. if (result != null) {
  543. return result;
  544. }
  545. result = new HxClosure(phpClassName, methodName);
  546. if (!Global.array_key_exists(phpClassName, staticClosures)) {
  547. staticClosures[phpClassName] = new NativeAssocArray();
  548. }
  549. staticClosures[phpClassName][methodName] = result;
  550. return result;
  551. }
  552. /**
  553. Creates Haxe-compatible closure.
  554. @param type `this` for instance methods; full php class name for static methods
  555. @param func Method name
  556. **/
  557. public static inline function closure(target:Dynamic, func:String):HxClosure {
  558. return target.is_string() ? getStaticClosure(target, func) : getInstanceClosure(target, func);
  559. }
  560. /**
  561. Get UTF-8 code of the first character in `s` without any checks
  562. **/
  563. static public inline function unsafeOrd(s:NativeString):Int {
  564. var code = Global.ord(s[0]);
  565. if (code < 0xC0) {
  566. return code;
  567. } else if (code < 0xE0) {
  568. return ((code - 0xC0) << 6) + Global.ord(s[1]) - 0x80;
  569. } else if (code < 0xF0) {
  570. return ((code - 0xE0) << 12) + ((Global.ord(s[1]) - 0x80) << 6) + Global.ord(s[2]) - 0x80;
  571. } else {
  572. return ((code - 0xF0) << 18) + ((Global.ord(s[1]) - 0x80) << 12) + ((Global.ord(s[2]) - 0x80) << 6) + Global.ord(s[3]) - 0x80;
  573. }
  574. }
  575. }
  576. /**
  577. Class<T> implementation for Haxe->PHP internals.
  578. **/
  579. @:keep
  580. @:dox(hide)
  581. private class HxClass {
  582. public var phpClassName(default, null):String;
  583. public function new(phpClassName:String):Void {
  584. this.phpClassName = phpClassName;
  585. }
  586. /**
  587. Magic method to call static methods of this class, when `HxClass` instance is in a `Dynamic` variable.
  588. **/
  589. @:phpMagic
  590. function __call(method:String, args:NativeArray):Dynamic {
  591. var callback = (phpClassName == 'String' ? Syntax.nativeClassName(HxString) : phpClassName) + '::' + method;
  592. return Global.call_user_func_array(callback, args);
  593. }
  594. /**
  595. Magic method to get static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  596. **/
  597. @:phpMagic
  598. function __get(property:String):Dynamic {
  599. if (Global.defined('$phpClassName::$property')) {
  600. return Global.constant('$phpClassName::$property');
  601. } else if (Boot.hasGetter(phpClassName, property)) {
  602. return Syntax.staticCall(phpClassName, 'get_$property');
  603. } else if (phpClassName.method_exists(property)) {
  604. return new HxClosure(phpClassName, property);
  605. } else {
  606. return Syntax.getStaticField(phpClassName, property);
  607. }
  608. }
  609. /**
  610. Magic method to set static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  611. **/
  612. @:phpMagic
  613. function __set(property:String, value:Dynamic):Void {
  614. if (Boot.hasSetter(phpClassName, property)) {
  615. Syntax.staticCall(phpClassName, 'set_$property', value);
  616. } else {
  617. Syntax.setStaticField(phpClassName, property, value);
  618. }
  619. }
  620. }
  621. /**
  622. Base class for enum types
  623. **/
  624. @:keep
  625. @:dox(hide)
  626. @:allow(php.Boot.stringify)
  627. @:allow(Type)
  628. private class HxEnum {
  629. final tag:String;
  630. final index:Int;
  631. final params:NativeArray;
  632. public function new(tag:String, index:Int, arguments:NativeArray = null):Void {
  633. this.tag = tag;
  634. this.index = index;
  635. params = (arguments == null ? new NativeArray() : arguments);
  636. }
  637. /**
  638. Get string representation of this `Class`
  639. **/
  640. public function toString():String {
  641. return __toString();
  642. }
  643. /**
  644. PHP magic method to get string representation of this `Class`
  645. **/
  646. @:phpMagic
  647. public function __toString():String {
  648. return Boot.stringify(this);
  649. }
  650. extern public static function __hx__list():Array<String>;
  651. }
  652. /**
  653. `String` implementation
  654. **/
  655. @:keep
  656. @:dox(hide)
  657. private class HxString {
  658. public static function toUpperCase(str:String):String {
  659. return Global.mb_strtoupper(str);
  660. }
  661. public static function toLowerCase(str:String):String {
  662. return Global.mb_strtolower(str);
  663. }
  664. public static function charAt(str:String, index:Int):String {
  665. return index < 0 ? '' : Global.mb_substr(str, index, 1);
  666. }
  667. public static function charCodeAt(str:String, index:Int):Null<Int> {
  668. if (index < 0 || str == '') {
  669. return null;
  670. }
  671. if (index == 0) {
  672. return Boot.unsafeOrd(str);
  673. }
  674. var char = Global.mb_substr(str, index, 1);
  675. return char == '' ? null : Boot.unsafeOrd(char);
  676. }
  677. public static function indexOf(str:String, search:String, startIndex:Int = null):Int {
  678. if (startIndex == null) {
  679. startIndex = 0;
  680. } else {
  681. var length = str.length;
  682. if (startIndex < 0) {
  683. startIndex += length;
  684. if (startIndex < 0) {
  685. startIndex = 0;
  686. }
  687. }
  688. if (startIndex >= length && search != '') {
  689. return -1;
  690. }
  691. }
  692. var index:EitherType<Int, Bool> = if (search == '') {
  693. var length = str.length;
  694. startIndex > length ? length : startIndex;
  695. } else {
  696. Global.mb_strpos(str, search, startIndex);
  697. }
  698. return (index == false ? -1 : index);
  699. }
  700. public static function lastIndexOf(str:String, search:String, startIndex:Int = null):Int {
  701. var start = startIndex;
  702. if (start == null) {
  703. start = 0;
  704. } else {
  705. var length = str.length;
  706. if (start >= 0) {
  707. start = start - length;
  708. if (start > 0) {
  709. start = 0;
  710. }
  711. } else if (start < -length) {
  712. start = -length;
  713. }
  714. }
  715. var index:EitherType<Int, Bool> = if (search == '') {
  716. var length = str.length;
  717. startIndex == null || startIndex > length ? length : startIndex;
  718. } else {
  719. Global.mb_strrpos(str, search, start);
  720. }
  721. if (index == false) {
  722. return -1;
  723. } else {
  724. return index;
  725. }
  726. }
  727. public static function split(str:String, delimiter:String):Array<String> {
  728. var arr:NativeArray = if (delimiter == '') {
  729. Global.preg_split('//u', str, -1, Const.PREG_SPLIT_NO_EMPTY);
  730. } else {
  731. delimiter = Global.preg_quote(delimiter, '/');
  732. Global.preg_split('/$delimiter/', str);
  733. }
  734. return @:privateAccess Array.wrap(arr);
  735. }
  736. public static function substr(str:String, pos:Int, ?len:Int):String {
  737. return Global.mb_substr(str, pos, len);
  738. }
  739. public static function substring(str:String, startIndex:Int, ?endIndex:Int):String {
  740. if (endIndex == null) {
  741. if (startIndex < 0) {
  742. startIndex = 0;
  743. }
  744. return Global.mb_substr(str, startIndex);
  745. }
  746. if (endIndex < 0) {
  747. endIndex = 0;
  748. }
  749. if (startIndex < 0) {
  750. startIndex = 0;
  751. }
  752. if (startIndex > endIndex) {
  753. var tmp = endIndex;
  754. endIndex = startIndex;
  755. startIndex = tmp;
  756. }
  757. return Global.mb_substr(str, startIndex, endIndex - startIndex);
  758. }
  759. public static function toString(str:String):String {
  760. return str;
  761. }
  762. public static function fromCharCode(code:Int):String {
  763. return Global.mb_chr(code);
  764. }
  765. }
  766. /**
  767. For Dynamic access which looks like String.
  768. Instances of this class should not be saved anywhere.
  769. Instead it should be used to immediately invoke a String field right after instance creation one time only.
  770. **/
  771. @:dox(hide)
  772. @:keep
  773. private class HxDynamicStr extends HxClosure {
  774. static var hxString:String = (cast HxString : HxClass).phpClassName;
  775. /**
  776. Returns HxDynamicStr instance if `value` is a string.
  777. Otherwise returns `value` as-is.
  778. **/
  779. static function wrap(value:Dynamic):Dynamic {
  780. if (value.is_string()) {
  781. return new HxDynamicStr(value);
  782. } else {
  783. return value;
  784. }
  785. }
  786. static inline function invoke(str:String, method:String, args:NativeArray):Dynamic {
  787. Global.array_unshift(args, str);
  788. return Global.call_user_func_array(hxString + '::' + method, args);
  789. }
  790. function new(str:String) {
  791. super(str, null);
  792. }
  793. @:phpMagic
  794. function __get(field:String):Dynamic {
  795. switch (field) {
  796. case 'length':
  797. return (target : String).length;
  798. case _:
  799. func = field;
  800. return this;
  801. }
  802. }
  803. @:phpMagic
  804. function __call(method:String, args:NativeArray):Dynamic {
  805. return invoke(target, method, args);
  806. }
  807. /**
  808. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  809. **/
  810. @:phpMagic
  811. override public function __invoke() {
  812. return invoke(target, func, Global.func_get_args());
  813. }
  814. /**
  815. Generates callable value for PHP
  816. **/
  817. override public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  818. if (eThis == null) {
  819. return Syntax.arrayDecl((this : Dynamic), func);
  820. }
  821. return Syntax.arrayDecl((new HxDynamicStr(eThis) : Dynamic), func);
  822. }
  823. /**
  824. Invoke this closure with `newThis` instead of `this`
  825. **/
  826. override public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  827. if (newThis == null) {
  828. newThis = target;
  829. }
  830. return invoke(newThis, func, args);
  831. }
  832. }
  833. /**
  834. Anonymous objects implementation
  835. **/
  836. @:keep
  837. @:dox(hide)
  838. private class HxAnon extends StdClass {
  839. public function new(fields:NativeArray = null) {
  840. super();
  841. if (fields != null) {
  842. Syntax.foreach(fields, function(name, value) Syntax.setField(this, name, value));
  843. }
  844. }
  845. @:phpMagic
  846. function __get(name:String) {
  847. return null;
  848. }
  849. @:phpMagic
  850. function __call(name:String, args:NativeArray):Dynamic {
  851. return Syntax.code("($this->{0})(...{1})", name, args);
  852. }
  853. }
  854. /**
  855. Closures implementation
  856. **/
  857. @:keep
  858. @:dox(hide)
  859. private class HxClosure {
  860. /** `this` for instance methods; php class name for static methods */
  861. var target:Dynamic;
  862. /** Method name for methods */
  863. var func:String;
  864. /** A callable value, which can be invoked by PHP */
  865. var callable:Any;
  866. public function new(target:Dynamic, func:String):Void {
  867. this.target = target;
  868. this.func = func;
  869. // Force runtime error if trying to create a closure of an instance which happen to be `null`
  870. if (target.is_null()) {
  871. throw "Unable to create closure on `null`";
  872. }
  873. callable = Std.is(target, HxAnon) ? Syntax.field(target, func) : Syntax.arrayDecl(target, func);
  874. }
  875. /**
  876. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  877. **/
  878. @:phpMagic
  879. public function __invoke() {
  880. return Global.call_user_func_array(callable, Global.func_get_args());
  881. }
  882. /**
  883. Generates callable value for PHP
  884. **/
  885. public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  886. if (eThis == null) {
  887. eThis = target;
  888. }
  889. if (Std.is(eThis, HxAnon)) {
  890. return Syntax.field(eThis, func);
  891. }
  892. return Syntax.arrayDecl(eThis, func);
  893. }
  894. /**
  895. Check if this is the same closure
  896. **/
  897. public function equals(closure:HxClosure):Bool {
  898. return (target == closure.target && func == closure.func);
  899. }
  900. /**
  901. Invoke this closure with `newThis` instead of `this`
  902. **/
  903. public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  904. return Global.call_user_func_array(getCallback(newThis), args);
  905. }
  906. }
  907. /**
  908. Special exception which is used to wrap non-throwable values
  909. **/
  910. @:keep
  911. @:dox(hide)
  912. private class HxException extends Exception {
  913. var e:Dynamic;
  914. public function new(e:Dynamic):Void {
  915. this.e = e;
  916. super(Boot.stringify(e));
  917. }
  918. }