forked from TarsPHP/tars-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtars2php.php
2892 lines (2565 loc) · 106 KB
/
tars2php.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 说明:
* 1. } 要单独放在一行,如}后面有;号,要跟}放在一行
* 2. 每行只能字义一个字段
* 3. struct不能嵌套定义,如用到别的struct, 把对应的struct 拿出来定义即可.
**/
$configFile = $argv[1];
$config = require_once $configFile;
$fileConverter = new FileConverter($config);
$fileConverter->moduleScan();
$fileConverter->moduleParse();
class Utils
{
public static $preEnums;
public static $preStructs;
public static $wholeTypeMap = array(
'bool' => '\TARS::BOOL',
'boolean' => '\TARS::BOOL',
'byte' => '\TARS::CHAR',
'char' => '\TARS::CHAR',
'unsigned byte' => '\TARS::UINT8',
'unsigned char' => '\TARS::UINT8',
'short' => '\TARS::SHORT',
'unsigned short' => '\TARS::UINT16',
'int' => '\TARS::INT32',
'unsigned int' => '\TARS::UINT32',
'long' => '\TARS::INT64',
'float' => '\TARS::FLOAT',
'double' => '\TARS::DOUBLE',
'string' => '\TARS::STRING',
'vector' => 'new \TARS_Vector',
'map' => 'new \TARS_Map',
);
public static $typeMap = array(
'bool' => '\TARS::BOOL',
'boolean' => '\TARS::BOOL',
'byte' => '\TARS::CHAR',
'char' => '\TARS::CHAR',
'unsigned byte' => '\TARS::UINT8',
'unsigned char' => '\TARS::UINT8',
'short' => '\TARS::SHORT',
'unsigned short' => '\TARS::UINT16',
'int' => '\TARS::INT32',
'unsigned int' => '\TARS::UINT32',
'long' => '\TARS::INT64',
'float' => '\TARS::FLOAT',
'double' => '\TARS::DOUBLE',
'string' => '\TARS::STRING',
'vector' => '\TARS::VECTOR',
'map' => '\TARS::MAP',
'enum' => '\TARS::UINT8', // 应该不会出现
'struct' => '\TARS::STRUCT', // 应该不会出现
);
public static function getPackMethods($type)
{
$packMethods = [
'bool' => 'putBool',
'boolean' => 'putBool',
'byte' => 'putChar',
'char' => 'putChar',
'unsigned byte' => 'putUInt8',
'unsigned char' => 'putUInt8',
'short' => 'putShort',
'unsigned short' => 'putUInt16',
'int' => 'putInt32',
'unsigned int' => 'putUInt32',
'long' => 'putInt64',
'float' => 'putFloat',
'double' => 'putDouble',
'string' => 'putString',
'enum' => 'putUInt8',
'map' => 'putMap',
'vector' => 'putVector',
'Bool' => 'putBool',
'Boolean' => 'putBool',
'Byte' => 'putChar',
'Char' => 'putChar',
'Unsigned byte' => 'putUInt8',
'Unsigned char' => 'putUInt8',
'Short' => 'putShort',
'Unsigned short' => 'putUInt16',
'Int' => 'putInt32',
'Unsigned int' => 'putUInt32',
'Long' => 'putInt64',
'Float' => 'putFloat',
'Double' => 'putDouble',
'String' => 'putString',
'Enum' => 'putUInt8',
'Map' => 'putMap',
'Vector' => 'putVector',
];
if (isset($packMethods[$type])) {
return $packMethods[$type];
} else {
return 'putStruct';
}
}
public static function getUnpackMethods($type)
{
$unpackMethods = [
'bool' => 'getBool',
'boolean' => 'getBool',
'byte' => 'getChar',
'char' => 'getChar',
'unsigned byte' => 'getUInt8',
'unsigned char' => 'getUInt8',
'short' => 'getShort',
'unsigned short' => 'getUInt16',
'int' => 'getInt32',
'unsigned int' => 'getUInt32',
'long' => 'getInt64',
'float' => 'getFloat',
'double' => 'getDouble',
'string' => 'getString',
'enum' => 'getUInt8',
'map' => 'getMap',
'vector' => 'getVector',
'Bool' => 'getBool',
'Boolean' => 'getBool',
'Byte' => 'getChar',
'Char' => 'getChar',
'Unsigned byte' => 'getUInt8',
'Unsigned char' => 'getUInt8',
'Short' => 'getShort',
'Unsigned short' => 'getUInt16',
'Int' => 'getInt32',
'Unsigned int' => 'getUInt32',
'Long' => 'getInt64',
'Float' => 'getFloat',
'Double' => 'getDouble',
'String' => 'getString',
'Enum' => 'getUInt8',
'Map' => 'getMap',
'Vector' => 'getVector',
];
if (isset($unpackMethods[strtolower($type)])) {
return $unpackMethods[strtolower($type)];
} else {
return 'getStruct';
}
}
/**
* @param $char
*
* @return int
* 判断是不是tag
*/
public static function isTag($word)
{
if (!is_numeric($word)) {
return false;
} else {
return true;
}
}
/**
* @param $word
*
* @return bool
* 判断收集到的word是不是
*/
public static function isRequireType($word)
{
return in_array(strtolower($word), ['require', 'optional']);
}
public static function isBasicType($word)
{
$basicTypes = [
'bool', 'boolean', 'byte', 'char', 'unsigned byte', 'unsigned char', 'short', 'unsigned short',
'int', 'unsigned int', 'long', 'float', 'double', 'string', 'void',
];
return in_array(strtolower($word), $basicTypes);
}
public static function isEnum($word, $preEnums)
{
return in_array($word, $preEnums);
}
public static function isMap($word)
{
return strtolower($word) == 'map';
}
public static function isStruct($word, $preStructs)
{
return in_array($word, $preStructs);
}
public static function isVector($word)
{
return strtolower($word) == 'vector';
}
public static function isSpace($char)
{
if ($char == ' ' || $char == "\t") {
return true;
} else {
return false;
}
}
public static function paramTypeMap($paramType)
{
if (self::isBasicType($paramType) || self::isMap($paramType) || self::isVector($paramType)) {
return '';
} else {
return $paramType;
}
}
public static function getRealType($type)
{
if (isset(self::$typeMap[strtolower($type)])) {
return self::$typeMap[strtolower($type)];
} else {
return '\TARS::STRUCT';
}
}
public static function inIdentifier($char)
{
return ($char >= 'a' & $char <= 'z') |
($char >= 'A' & $char <= 'Z') |
($char >= '0' & $char <= '9') |
($char == '_');
}
public static function abnormalExit($level, $msg)
{
echo "[$level]$msg"."\n";
exit;
}
public static function pregMatchByName($name, $line)
{
// 处理第一行,正则匹配出classname
$Tokens = preg_split("/$name/", $line);
$mathName = $Tokens[1];
$mathName = trim($mathName, " \r\0\x0B\t\n{");
preg_match('/[a-zA-Z][0-9a-zA-Z]/', $mathName, $matches);
if (empty($matches)) {
//Utils::abnormalExit('error',$name.'名称有误'.$line);
}
return $mathName;
}
public static function isReturn($char)
{
if ($char == "\n" || $char == '\r' || bin2hex($char) == '0a' || bin2hex($char) == '0b' ||
bin2hex($char) == '0c' || bin2hex($char) == '0d') {
return true;
} else {
return false;
}
}
}
class FileConverter
{
public $moduleName;
public $uniqueName;
public $interfaceName;
public $fromFile;
public $outputDir;
public $appName;
public $serverName;
public $objName;
public $servantName;
public $namespaceName;
public $namespacePrefix;
public $preStructs = [];
public $preEnums = [];
public $preConsts = [];
public $preNamespaceStructs = [];
public $preNamespaceEnums = [];
public function __construct($config)
{
$this->fromFile = $config['tarsFiles'][0];
if (empty($config['appName']) || empty($config['serverName']) || empty($config['objName'])) {
Utils::abnormalExit('error', 'appName or serverName or objName empty!');
}
$this->servantName = $config['appName'].'.'.$config['serverName'].'.'.$config['objName'];
$this->appName = $config['appName'];
$this->serverName = $config['serverName'];
$this->objName = $config['objName'];
$this->outputDir = empty($config['dstPath']) ? './' : $config['dstPath'].'/';
$pos = strrpos($this->fromFile, '/', -1);
$inputDir = substr($this->fromFile, 0, $pos);
$this->inputDir = $inputDir;
$this->namespacePrefix = $config['namespacePrefix'];
$this->withServant = $config['withServant'];
$this->initDir();
}
/**
* 首先需要初始化一些文件目录.
*
* @return [type] [description]
*/
public function initDir()
{
if (strtolower(substr(php_uname('a'), 0, 3)) === 'win') {
exec('mkdir '.$this->outputDir.$this->appName);
exec('mkdir '.$this->outputDir.$this->appName.'\\'.$this->serverName);
exec('DEL '.$this->outputDir.$this->appName.'\\'.$this->serverName.'\\'.$this->objName.'\\*.*');
exec('mkdir '.$this->outputDir.$this->appName.'\\'.$this->serverName.'\\'.$this->objName);
$this->moduleName = $this->appName.'\\'.$this->serverName.'\\'.$this->objName;
exec('mkdir '.$this->outputDir.$this->moduleName.'\\classes');
exec('mkdir '.$this->outputDir.$this->moduleName.'\\tars');
exec('copy '.$this->fromFile.' '.$this->outputDir.$this->moduleName.'\\tars');
} else {
exec('mkdir '.$this->outputDir.$this->appName);
exec('mkdir '.$this->outputDir.$this->appName.'/'.$this->serverName);
exec('rm -rf '.$this->outputDir.$this->appName.'/'.$this->serverName.'/'.$this->objName);
exec('mkdir '.$this->outputDir.$this->appName.'/'.$this->serverName.'/'.$this->objName);
$this->moduleName = $this->appName.'/'.$this->serverName.'/'.$this->objName;
exec('mkdir '.$this->outputDir.$this->moduleName.'/classes');
exec('mkdir '.$this->outputDir.$this->moduleName.'/tars');
exec('cp '.$this->fromFile.' '.$this->outputDir.$this->moduleName.'/tars');
}
$this->namespaceName = empty($this->namespacePrefix) ? $this->appName.'\\'.$this->serverName.'\\'.$this->objName
: $this->namespacePrefix.'\\'.$this->appName.'\\'.$this->serverName.'\\'.$this->objName;
$this->uniqueName = $this->appName.'_'.$this->serverName.'_'.$this->objName;
}
public function usage()
{
echo 'php tars2php.php tars.proto.php';
}
public function moduleScan()
{
$fp = fopen($this->fromFile, 'r');
if (!$fp) {
$this->usage();
exit;
}
while (($line = fgets($fp, 1024)) !== false) {
// 判断是否有module
$moduleFlag = strpos($line, 'module');
if ($moduleFlag !== false) {
$name = Utils::pregMatchByName('module', $line);
$currentModule = $name;
}
// 判断是否有include
$includeFlag = strpos($line, '#include');
if ($includeFlag !== false) {
// 找出tars对应的文件名
$tokens = preg_split('/#include/', $line);
$includeFile = trim($tokens[1], "\" \r\n");
if (strtolower(substr(php_uname('a'), 0, 3)) === 'win') {
exec('copy '.$includeFile.' '.$this->moduleName.'\\tars');
} else {
exec('cp '.$includeFile.' '.$this->moduleName.'/tars');
}
$includeParser = new IncludeParser();
$includeParser->includeScan($includeFile, $this->preEnums, $this->preStructs,
$this->preNamespaceEnums, $this->preNamespaceStructs);
}
// 如果空行,或者是注释,就直接略过
if (!$line || trim($line) == '' || trim($line)[0] === '/' || trim($line)[0] === '*' || trim($line) === '{') {
continue;
}
// 正则匹配,发现是在enum中
$enumFlag = strpos($line, 'enum');
if ($enumFlag !== false) {
$name = Utils::pregMatchByName('enum', $line);
if (!empty($name)) {
$this->preEnums[] = $name;
// 增加命名空间以备不时之需
if (!empty($currentModule)) {
$this->preNamespaceEnums[] = $currentModule.'::'.$name;
}
while (($lastChar = fgetc($fp)) != '}') {
continue;
}
}
}
// 正则匹配,发现是在结构体中
$structFlag = strpos($line, 'struct');
// 一旦发现了struct,那么持续读到结束为止
if ($structFlag !== false) {
$name = Utils::pregMatchByName('struct', $line);
if (!empty($name)) {
$this->preStructs[] = $name;
// 增加命名空间以备不时之需
if (!empty($currentModule)) {
$this->preNamespaceStructs[] = $currentModule.'::'.$name;
}
}
}
}
fclose($fp);
}
public function moduleParse()
{
$fp = fopen($this->fromFile, 'r');
if (!$fp) {
$this->usage();
exit;
}
while (($line = fgets($fp, 1024)) !== false) {
// 判断是否有include
$includeFlag = strpos($line, '#include');
if ($includeFlag !== false) {
// 找出tars对应的文件名
$tokens = preg_split('/#include/', $line);
$includeFile = trim($tokens[1], "\" \r\n");
$includeParser = new IncludeParser();
$includeParser->includeParse($includeFile, $this->preEnums, $this->preStructs, $this->uniqueName,
$this->moduleName, $this->namespaceName, $this->servantName, $this->preNamespaceEnums, $this->preNamespaceStructs,
$this->outputDir);
}
// 如果空行,或者是注释,就直接略过
if (!$line || trim($line) == '' || trim($line)[0] === '/' || trim($line)[0] === '*') {
continue;
}
// 正则匹配,发现是在enum中
$enumFlag = strpos($line, 'enum');
if ($enumFlag !== false) {
// 处理第一行,正则匹配出classname
$enumTokens = preg_split('/enum/', $line);
$enumName = $enumTokens[1];
$enumName = trim($enumName, " \r\0\x0B\t\n{");
// 判断是否是合法的structName
preg_match('/[a-zA-Z][0-9a-zA-Z]/', $enumName, $matches);
if (empty($matches)) {
Utils::abnormalExit('error', 'Enum名称有误');
}
$this->preEnums[] = $enumName;
while (($lastChar = fgetc($fp)) != '}') {
continue;
}
}
// 正则匹配,发现是在consts中
$constFlag = strpos($line, 'const');
if ($constFlag !== false) {
// 直接进行正则匹配
Utils::abnormalExit('warning', 'const is not supported, please make sure you deal with them yourself in this version!');
}
// 正则匹配,发现是在结构体中
$structFlag = strpos($line, 'struct');
// 一旦发现了struct,那么持续读到结束为止
if ($structFlag !== false) {
$name = Utils::pregMatchByName('struct', $line);
$structParser = new StructParser($fp, $line, $this->uniqueName, $this->moduleName, $name, $this->preStructs,
$this->preEnums, $this->namespaceName, $this->preNamespaceEnums, $this->preNamespaceStructs);
$structClassStr = $structParser->parse();
file_put_contents($this->outputDir.$this->moduleName.'/classes/'.$name.'.php', $structClassStr);
}
// 正则匹配,发现是在interface中
$interfaceFlag = strpos(strtolower($line), 'interface');
// 一旦发现了struct,那么持续读到结束为止
if ($interfaceFlag !== false) {
$name = Utils::pregMatchByName('interface', $line);
$interfaceName = $name.'Servant';
// 需要区分一下生成server还是client的代码
if ($this->withServant) {
$servantParser = new ServantParser($fp, $line, $this->namespaceName, $this->moduleName,
$interfaceName, $this->preStructs,
$this->preEnums, $this->servantName, $this->preNamespaceEnums, $this->preNamespaceStructs);
$servant = $servantParser->parse();
file_put_contents($this->outputDir.$this->moduleName.'/'.$interfaceName.'.php', $servant);
} else {
$interfaceParser = new InterfaceParser($fp, $line, $this->namespaceName, $this->moduleName,
$interfaceName, $this->preStructs,
$this->preEnums, $this->servantName, $this->preNamespaceEnums, $this->preNamespaceStructs);
$interfaces = $interfaceParser->parse();
// 需要区分同步和异步的两种方式
file_put_contents($this->outputDir.$this->moduleName.'/'.$interfaceName.'.php', $interfaces['syn']);
}
}
}
}
}
class IncludeParser
{
public function includeScan($includeFile, &$preEnums, &$preStructs,
&$preNamespaceEnums, &$preNamespaceStructs)
{
$fp = fopen($includeFile, 'r');
if (!$fp) {
echo 'Include file not exit, please check';
exit;
}
while (($line = fgets($fp, 1024)) !== false) {
// 如果空行,或者是注释,就直接略过
if (!$line || trim($line) == '' || trim($line)[0] === '/' || trim($line)[0] === '*') {
continue;
}
// 判断是否有module
$moduleFlag = strpos($line, 'module');
if ($moduleFlag !== false) {
$name = Utils::pregMatchByName('module', $line);
$currentModule = $name;
}
// 正则匹配,发现是在enum中
$enumFlag = strpos($line, 'enum');
if ($enumFlag !== false) {
$name = Utils::pregMatchByName('enum', $line);
$preEnums[] = $name;
if (!empty($currentModule)) {
$preNamespaceEnums[] = $currentModule.'::'.$name;
}
while (($lastChar = fgetc($fp)) != '}') {
continue;
}
}
// 正则匹配,发现是在结构体中
$structFlag = strpos($line, 'struct');
// 一旦发现了struct,那么持续读到结束为止
if ($structFlag !== false) {
$name = Utils::pregMatchByName('struct', $line);
$preStructs[] = $name;
if (!empty($currentModule)) {
$preNamespaceStructs[] = $currentModule.'::'.$name;
}
}
}
}
public function includeParse($includeFile, &$preEnums, &$preStructs, $uniqueName, $moduleName, $namespaceName, $servantName,
&$preNamespaceEnums, &$preNamespaceStructs, $outputDir)
{
$fp = fopen($includeFile, 'r');
if (!$fp) {
echo 'Include file not exit, please check';
exit;
}
while (($line = fgets($fp, 1024)) !== false) {
// 如果空行,或者是注释,就直接略过
if (!$line || trim($line) == '' || trim($line)[0] === '/' || trim($line)[0] === '*') {
continue;
}
// 正则匹配,发现是在consts中
$constFlag = strpos($line, 'const');
if ($constFlag !== false) {
// 直接进行正则匹配
echo 'CONST is not supported, please make sure you deal with them yourself in this version!';
}
// 正则匹配,发现是在结构体中
$structFlag = strpos($line, 'struct');
// 一旦发现了struct,那么持续读到结束为止
if ($structFlag !== false) {
$name = Utils::pregMatchByName('struct', $line);
$structParser = new StructParser($fp, $line, $uniqueName, $moduleName, $name, $preStructs,
$preEnums, $namespaceName, $preNamespaceEnums, $preNamespaceStructs);
$structClassStr = $structParser->parse();
file_put_contents($outputDir.$moduleName.'/classes/'.$name.'.php', $structClassStr);
}
// 正则匹配,发现是在interface中
$interfaceFlag = strpos(strtolower($line), 'interface');
// 一旦发现了struct,那么持续读到结束为止
if ($interfaceFlag !== false) {
$name = Utils::pregMatchByName('interface', $line);
if (in_array($name, $preStructs)) {
$name .= 'Servant';
}
$interfaceParser = new InterfaceParser($fp, $line, $namespaceName, $moduleName,
$name, $preStructs,
$preEnums, $servantName, $preNamespaceEnums, $preNamespaceStructs);
$interfaces = $interfaceParser->parse();
// 需要区分同步和异步的两种方式
file_put_contents($outputDir.$moduleName.'/'.$name.'.php', $interfaces['syn']);
}
}
}
}
class InterfaceParser
{
public $namespaceName;
public $moduleName;
public $interfaceName;
public $asInterfaceName;
public $state;
// 这个结构体,可能会引用的部分,包括其他的结构体、枚举类型、常量
public $useStructs = [];
public $extraUse;
public $preStructs;
public $preEnums;
public $preNamespaceStructs;
public $preNamespaceEnums;
public $returnSymbol = "\n";
public $doubleReturn = "\n\n";
public $tabSymbol = "\t";
public $doubleTab = "\t\t";
public $tripleTab = "\t\t\t";
public $quardupleTab = "\t\t\t\t";
public $extraContructs = '';
public $extraExtInit = '';
public $consts = '';
public $variables = '';
public $fields = '';
public $funcSet = '';
public $servantName;
public function __construct($fp, $line, $namespaceName, $moduleName,
$interfaceName, $preStructs,
$preEnums, $servantName, $preNamespaceEnums, $preNamespaceStructs)
{
$this->fp = $fp;
$this->namespaceName = $namespaceName;
$this->moduleName = $moduleName;
$this->preStructs = $preStructs;
$this->preEnums = $preEnums;
$this->interfaceName = $interfaceName;
$this->servantName = $servantName;
$this->extraUse = '';
$this->useStructs = [];
$this->preNamespaceEnums = $preNamespaceEnums;
$this->preNamespaceStructs = $preNamespaceStructs;
}
public function copyAnnotation()
{
// 再读入一个字符
$nextChar = fgetc($this->fp);
// 第一种
if ($nextChar == '/') {
while (1) {
$tmpChar = fgetc($this->fp);
if ($tmpChar == "\n") {
$this->state = 'lineEnd';
break;
}
}
return;
} elseif ($nextChar == '*') {
while (1) {
$tmpChar = fgetc($this->fp);
if ($tmpChar === false) {
Utils::abnormalExit('error', '注释换行错误,请检查'.$tmpChar);
} elseif ($tmpChar === "\n") {
} elseif (($tmpChar) === '*') {
$nextnextChar = fgetc($this->fp);
if ($nextnextChar == '/') {
return;
} else {
$pos = ftell($this->fp);
fseek($this->fp, $pos - 1);
}
}
}
}
// 注释不正常
else {
Utils::abnormalExit('error', '注释换行错误,请检查'.$nextChar);
}
}
public function getFileHeader($prefix = '')
{
return "<?php\n\nnamespace ".$this->namespaceName.$prefix.';'.$this->doubleReturn.
'use Tars\\client\\CommunicatorConfig;'.$this->returnSymbol.
'use Tars\\client\\Communicator;'.$this->returnSymbol.
'use Tars\\client\\RequestPacket;'.$this->returnSymbol.
'use Tars\\client\\TUPAPIWrapper;'.$this->returnSymbol.
$this->returnSymbol;
}
public function getInterfaceBasic()
{
return $this->tabSymbol.'protected $_communicator;'.$this->returnSymbol.
$this->tabSymbol.'protected $_iVersion;'.$this->returnSymbol.
$this->tabSymbol.'protected $_iTimeout;'.$this->returnSymbol.
$this->tabSymbol."public \$_servantName = \"$this->servantName\";".$this->doubleReturn.
$this->tabSymbol.'public function __construct(CommunicatorConfig $config) {'.$this->returnSymbol.
$this->doubleTab.'try {'.$this->returnSymbol.
$this->tripleTab.'$config->setServantName($this->_servantName);'.$this->returnSymbol.
$this->tripleTab.'$this->_communicator = new Communicator($config);'.$this->returnSymbol.
$this->tripleTab.'$this->_iVersion = $config->getIVersion();'.$this->returnSymbol.
$this->tripleTab.'$this->_iTimeout = empty($config->getAsyncInvokeTimeout())?2:$config->getAsyncInvokeTimeout();'.$this->returnSymbol.
$this->doubleTab.'} catch (\\Exception $e) {'.$this->returnSymbol.
$this->tripleTab.'throw $e;'.$this->returnSymbol.
$this->doubleTab.'}'.$this->returnSymbol.
$this->tabSymbol.'}'.$this->doubleReturn;
}
public function parse()
{
while ($this->state != 'end') {
$this->state = 'init';
$this->InterfaceFuncParseLine();
}
$interfaceClass = $this->getFileHeader('').$this->extraUse.'class '.$this->interfaceName.' {'.$this->returnSymbol;
$interfaceClass .= $this->getInterfaceBasic();
$interfaceClass .= $this->funcSet;
$interfaceClass .= '}'.$this->doubleReturn;
return [
'syn' => $interfaceClass,
];
}
/**
* @param $fp
* @param $line
* 这里必须要引入状态机了
*/
public function InterfaceFuncParseLine()
{
$line = '';
$this->state = 'init';
while (1) {
if ($this->state == 'init') {
$char = fgetc($this->fp);
// 有可能是换行
if ($char == '{' || Utils::isReturn($char)) {
continue;
}
// 遇到了注释会用贪婪算法全部处理完,同时填充到struct的类里面去
elseif ($char == '/') {
$this->copyAnnotation();
break;
} elseif (Utils::inIdentifier($char)) {
$this->state = 'identifier';
$line .= $char;
}
// 终止条件之1,宣告struct结束
elseif ($char == '}') {
// 需要贪心的读到"\n"为止
while (($lastChar = fgetc($this->fp)) != "\n") {
continue;
}
$this->state = 'end';
break;
}
} elseif ($this->state == 'identifier') {
$char = fgetc($this->fp);
if ($char == '/') {
$this->copyAnnotation();
} elseif ($char == ';') {
$line .= $char;
break;
}
// 终止条件之2,同样宣告interface结束
elseif ($char == '}') {
// 需要贪心的读到"\n"为止
while (($lastChar = fgetc($this->fp)) != "\n") {
continue;
}
$this->state = 'end';
} elseif (Utils::isReturn($char)) {
continue;
} elseif ($char == ')') {
$line .= $char;
// 需要贪心的读到"\n"为止
while (($lastChar = fgetc($this->fp)) != "\n") {
continue;
}
$this->state = 'lineEnd';
} else {
$line .= $char;
}
} elseif ($this->state == 'lineEnd') {
$char = fgetc($this->fp);
if ($char == '}') {
// 需要贪心的读到"\n"为止
while (($lastChar = fgetc($this->fp)) != "\n") {
continue;
}
$this->state = 'end';
}
break;
} elseif ($this->state == 'end') {
break;
}
}
if (empty($line)) {
return;
}
$line = trim($line);
// 如果空行,或者是注释,或者是大括号就直接略过
if (!$line || $line[0] === '/' || $line[0] === '*' || $line === '{') {
return;
}
$endFlag = strpos($line, '};');
if ($endFlag !== false) {
$this->state = 'end';
return;
}
$endFlag = strpos($line, '}');
if ($endFlag !== false) {
$this->state = 'end';
return;
}
// 有必要先分成三个部分,返回类型、接口名、参数列表
$tokens = preg_split('/\(/', $line, 2);
$mix = trim($tokens[0]);
$rest = $tokens[1];
$pices = preg_split('/\s+/', $mix);
$funcName = $pices[count($pices) - 1];
$returnType = implode('', array_slice($pices, 0, count($pices) - 1));
$state = 'init';
$word = '';
$params = [];
for ($i = 0; $i < strlen($rest); ++$i) {
$char = $rest[$i];
if ($state == 'init') {
// 有可能是换行
if ($char == '(' || Utils::isSpace($char)) {
continue;
} elseif ($char == "\n") {
break;
} elseif (Utils::inIdentifier($char)) {
$state = 'identifier';
$word .= $char;
}
// 终止条件之1,宣告interface结束
elseif ($char == ')') {
break;
} else {
Utils::abnormalExit('error', 'Interface:'.$this->interfaceName.'内格式错误,请更正tars');
}
} elseif ($state == 'identifier') {
if ($char == ',') {
$params[] = $word;
$state = 'init';
$word = '';
continue;
}
// 标志着map和vector的开始,不等到'>'的结束不罢休
// 这时候需要使用栈来push,然后一个个对应的pop,从而达到type的遍历
elseif ($char == '<') {
$mapVectorStack = [];
$word .= $char;
array_push($mapVectorStack, '<');
while (!empty($mapVectorStack)) {
$moreChar = $rest[$i + 1];
$word .= $moreChar;
if ($moreChar == '<') {
array_push($mapVectorStack, '<');
} elseif ($moreChar == '>') {
array_pop($mapVectorStack);
}
++$i;
}
continue;
} elseif ($char == ')') {
$params[] = $word;
break;
} elseif ($char == ';') {
continue;
}
// 终止条件之2,同样宣告struct结束
elseif ($char == '}') {
$state = 'end';
} elseif ($char == "\n") {
break;
} else {
$word .= $char;
}
} elseif ($state == 'lineEnd') {
break;
} elseif ($state == 'end') {
break;
}
}
$this->writeInterfaceLine($returnType, $funcName, $params);
}
/**
* @param $wholeType
* 通过完整的类型获取vector的扩展类型
* vector<CateObj> => new \TARS_VECTOR(new CateObj())
* vector<string> => new \TARS_VECTOR(\TARS::STRING)
* vector<map<string,CateObj>> => new \TARS_VECTOR(new \TARS_MAP(\TARS_MAP,new CateObj()))
*/
public function getExtType($wholeType, $valueName)
{
$state = 'init';
$word = '';
$extType = '';
for ($i = 0; $i < strlen($wholeType); ++$i) {
$char = $wholeType[$i];
if ($state == 'init') {
// 如果遇到了空格
if (Utils::isSpace($char)) {
continue;
}
// 回车是停止符号
elseif (Utils::inIdentifier($char)) {
$state = 'indentifier';
$word .= $char;
} elseif (Utils::isReturn($char)) {
break;
} elseif ($char == '>') {
$extType .= ')';
continue;
}
} elseif ($state == 'indentifier') {
if ($char == '<') {
// 替换word,替换< 恢复初始状态
$tmp = $this->VecMapReplace($word);