Boot.hx 27 KB

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