-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcppsp_compiler.cpp
More file actions
1856 lines (1554 loc) · 80 KB
/
cppsp_compiler.cpp
File metadata and controls
1856 lines (1554 loc) · 80 KB
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
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <string.h>
#include <vector>
#include <filesystem>
#include <cstdlib>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <functional>
bool isWindows=false;bool isMac=false;bool isLinux =false;
#if defined(_WIN32) || defined(_WIN64)
#define isWindows 1
typedef unsigned int UINT;
typedef int BOOL;
extern "C" BOOL __stdcall SetConsoleOutputCP(UINT wCodePageID);
extern "C" BOOL __stdcall SetConsoleCP(UINT wCodePageID);
#elif defined(__APPLE__) && defined(__MACH__)
#define isMac 1
#elif defined(__linux__)
#define isLinux 1
#endif
//檢查dll依賴:objdump -p cppsp_compiler.exe | findstr ".dll"
//備忘錄:設計匿名函數lamda(x,=y,&z,type g,{...}),x是變數名無須也不能提前宣告,type ...是參數,=/& ...是傳值,{...}是內容
namespace fs = std::filesystem;
bool Ifiostream=0;bool commentInReg=false;bool shouldInjectFuction=true;
// ====== 新增:萬用語法指令註冊器 ======
std::unordered_map<std::string, std::function<std::string(const std::string&)>> cpsCommands;
std::unordered_map<std::string, std::string>func_head_end ;
void registerCommand(const std::string& name,const std::string& start,const std::string& end,
std::function<std::string(const std::string&)> handler) {
cpsCommands[name] = handler;
func_head_end[start]=end;
}
// ======token區域=======
enum class TokenType {
ROOT, //0 container 根節點,不算實際 token
BEGIN, //1 ( 、 {
END, //2 ) 、 }
IDENTIFIER, //3 變數名稱
NUMBER, //4 數字
STRING, //5 字串
CHAR, //6 字元
OPERATOR, //7 運算子+ - = += * /
TYPE, //8 資料型態int float bool string
SEPARATOR, //9 分隔符號: , ;
KEYWORD, //10 關鍵字: print println input @inject @function
COMMENT, //11 註解
INJECT, //12 <<...>> 內嵌程式碼
funcKEYWORD, //13 函數關鍵字:
funcIDENTIFIER, //14 函數名稱:
NAMESPACELIKE, //15 C++中使用 n::child呼叫
STRUCTLIKE, //16 C++中使用 n.child呼叫
UNKNOWN //17 未知
};
struct Token {
TokenType type;
std::string value;
size_t line_number;
std::vector<Token> children; // 用於括號、{}、<<>> 等內部 token
bool operator==(const Token& other) const {
return type == other.type && value == other.value;
}
};
struct TokenizeState {
int depth = 0;
bool inString = false;
bool inBlockComment = false;
};
TokenizeState state={0,false,false};
std::unordered_set<std::string> typeKeywords= {
"int", "float", "bool", "char", "string","struct"
};
bool isTypeKeyword(const std::string& s) {
return typeKeywords.find(s) != typeKeywords.end();
}
static const std::vector<std::string> operators = {
">>=", "<<=",
"==", "!=", "<=", ">=",
"&&", "||",
"<<", ">>",
"+=", "-=", "*=", "/=", "%=",
"&=", "|=", "^=",
"++", "--",
"=", "+", "-", "*", "/", "%",
"&", "|", "^", "!", "<", ">","::",":"
};
std::vector<Token> tokenstream;
using tokencallback = std::function<std::string(const Token&)>;
std::unordered_map<std::string, tokencallback> tokenHandlers;
void registerToken(const std::string& name, tokencallback handler) {
tokenHandlers[name] = handler;
}
std::unordered_map<std::string, tokencallback> funcHandlers;std::unordered_set<std::string> what_is_funcname;
std::unordered_set<std::string> what_is_namespace_like;
std::unordered_set<std::string> what_is_struct_like;
std::unordered_set<std::string> custom_command;std::unordered_map<std::string,std::vector<Token>> custom_command_arg;
void registerfunc(const std::string& name, tokencallback handler) {
funcHandlers[name] = handler;
}
Token tokenizeFile(std::istream& funcfile,size_t lineno = 1) {
// 一次把整個檔案讀進來(不用 get / peek)
std::string src(
(std::istreambuf_iterator<char>(funcfile)),
std::istreambuf_iterator<char>()
);
Token root{TokenType::ROOT, "", 0, {}};
size_t i = 0;
TokenizeState state{};
auto skipWhitespace = [&](size_t& idx) {
while (idx < src.size()) {
if (src[idx] == ' ' || src[idx] == '\t') {
idx++;
} else if (src[idx] == '\n') { root.children.push_back({TokenType::SEPARATOR,";",lineno,{}});
lineno++;
idx++;
} else {
break;
}
}
};
auto parseIdentifierOrKeyword = [&](size_t& idx) -> Token {
std::string id;
while (idx < src.size() &&
((src[idx] >= 'a' && src[idx] <= 'z') ||
(src[idx] >= 'A' && src[idx] <= 'Z') ||
(src[idx] >= '0' && src[idx] <= '9') ||
src[idx] == '_' || src[idx] == '@' || src[idx] == '#'||src[idx]==':'||src[i]=='.')) {
if(src[idx]==':'&&src[idx+1]==':'){id+="::";idx+=2;continue;}
if(src[idx]=='.'){idx++;break;;}
id += src[idx++];
}
TokenType ttype = TokenType::IDENTIFIER;
if (isTypeKeyword(id))
ttype = TokenType::TYPE;
if (tokenHandlers.find(id) != tokenHandlers.end())
ttype = TokenType::KEYWORD;
if (funcHandlers.find(id) != funcHandlers.end())
ttype = TokenType::funcKEYWORD;
return {ttype, id, lineno, {}};
};
auto justconnectidentifier = [&](size_t& idx) -> Token {
std::string id;
while (idx < src.size() &&
((src[idx] >= 'a' && src[idx] <= 'z') ||
(src[idx] >= 'A' && src[idx] <= 'Z') ||
(src[idx] >= '0' && src[idx] <= '9') ||
src[idx] == '_' || src[idx] == '@' || src[idx] == '#'||src[idx]==':'||src[i]=='.')) {
if(src[idx]==':'&&src[idx+1]==':'){id+="::";idx+=2;continue;}
id += src[idx++];
}
TokenType ttype = TokenType::IDENTIFIER;
if (isTypeKeyword(id))
ttype = TokenType::TYPE;
if (tokenHandlers.find(id) != tokenHandlers.end())
ttype = TokenType::KEYWORD;
if (funcHandlers.find(id) != funcHandlers.end())
ttype = TokenType::funcKEYWORD;
return {ttype, id, lineno, {}};
};
auto parseNumber = [&](size_t& idx) -> Token {
std::string num;
while (idx < src.size() &&
((src[idx] >= '0' && src[idx] <= '9') || src[idx] == '.')) {
num += src[idx++];
}
return {TokenType::NUMBER, num, lineno, {}};
};
while (i < src.size()) {
skipWhitespace(i);
if (i >= src.size()) break;
//單行判斷的關鍵字類似import a,b,c...
std::vector<std::string> regkw={"import","from ","use","package"};
for(auto regk:regkw){
if ( i + 1 < src.size()&&src.compare(i,regk.size(),regk)==0) {
std::string Inimport;Token node{TokenType::funcKEYWORD, regk, lineno, {}};
i+=regk.size();
while (i < src.size() && src[i] != '\n') {
Inimport += src[i++];
}
node.children.push_back({TokenType::COMMENT, Inimport, lineno, {}});
root.children.push_back(node);
continue;
}
}
// 單行註解
if (src[i] == '/' && i + 1 < src.size() && src[i + 1] == '/') {
std::string comment;
while (i < src.size() && src[i] != '\n') {
comment += src[i++];
}
root.children.push_back({TokenType::COMMENT, comment+"\n", lineno, {}});
continue;
}
// 字串
bool ifwstr =(src[i]=='L'&& i+1<src.size() &&src[i+1] == '"');
if (ifwstr||(src[i] == '"') ){
std::string str;
if(ifwstr){ str="L\"";i+=2;} else{str="\"";i++; }
while (i < src.size()) {
if(src[i] == '\\'&&src[i+1]=='\"') { str+='"';i+=2; continue; }
if (src[i] == '\\' && i + 1 < src.size()) {
str += src[i];
str += src[i + 1];
i += 2;
continue;
}
bool ifstrend;if(src[i+1]==')'||src[i+1]==','||src[i+1]==' '||src[i+1]=='\n') ifstrend=true; else ifstrend=false;
if (src[i] == '"'&&ifstrend) {
str += '"';
i++;
break;
}
if (src[i] == '\n') lineno++;
str += src[i++] ;
}
root.children.push_back({TokenType::STRING, str, lineno, {}});
continue;
}
// 字元char
if(src[i]=='\''){
std::string charstr;
charstr+="'";
i++;
while(i<src.size()){
if(src[i]=='\\'&& i+1<src.size()){
charstr+=src[i];
charstr+=src[i+1];
i+=2;
continue;
}
bool ifstrend;if(src[i+1]==')'||src[i+1]==',') ifstrend=true; else ifstrend=false;
if(src[i]=='\''&&ifstrend){
charstr+="'";
i++;
break;
}
if(src[i]=='\n') lineno++;
charstr+=src[i++];
}
root.children.push_back({TokenType::CHAR,charstr,lineno,{}});
continue;
}
// () {}
int inner_lineno = lineno;
if (src[i] == '(' || src[i] == '{'||src[i]=='[') {
char startChar = src[i];
char endChar = (startChar == '(') ? ')' :(startChar == '[') ?']': '}';
Token node{TokenType::BEGIN, std::string(1, startChar), lineno, {}};
int depth = 1;
i++;
std::string inner;
while (i < src.size() && depth > 0) {
if (src[i] == startChar){ depth++;}
if (src[i] == endChar) {depth--;}
if (depth > 0) {
if (src[i] == '\n') lineno++;
inner += src[i];
}
i++;
}
if (!root.children.empty() && (root.children.back().type == TokenType::KEYWORD
||root.children.back().type==TokenType::funcIDENTIFIER||root.children.back().type==TokenType::funcKEYWORD
||root.children.back().type==TokenType::NAMESPACELIKE||root.children.back().type==TokenType::STRUCTLIKE) ){
if (!inner.empty()) { //變成關鍵字子節點
std::istringstream ss(inner);Token iner=tokenizeFile(ss,inner_lineno);
for(auto& child : iner.children){ node.children.push_back(child); // 不再使用 reinterpret_cast
if(startChar=='['&&root.children.back().type==TokenType::funcKEYWORD){
if(child.value!="]"&&child.value!=",") what_is_funcname.insert(child.value);
}
}
}
node.children.push_back({TokenType::END, std::string(1, endChar), lineno, {}});
if(!root.children.empty() && !root.children.back().children.empty()&& custom_command.find(root.children.back().children.back().value)!=custom_command.end()){
if(!root.children.back().children.back().children.empty()){ root.children.back().children.push_back(node); continue;}
else {root.children.back().children.back().children.push_back(node);continue;}
}else{
// 把 BEGIN 作為前一個 KEYWORD 的 child
root.children.back().children.push_back(node);}
}else if(startChar =='['&&!root.children.empty() && root.children.back().type == TokenType::IDENTIFIER){
if (!inner.empty()){ //把[]變成變數值(和原來變數合併)
root.children.back().value += std::string(1,startChar)+inner+std::string(1, endChar);
}
}
else {
if (!inner.empty()) { // 單獨()或{},與關鍵字
std::istringstream ss(inner);Token iner=tokenizeFile(ss,inner_lineno);
for(auto& child : iner.children) node.children.push_back(child); // 不再使用 reinterpret_cast
}
node.children.push_back({TokenType::END, std::string(1, endChar), lineno, {}});
root.children.push_back(node);
}
continue;
}
// <{ }>
if (i + 1 < src.size() &&( src[i] == '<' && src[i + 1] == '{')||(src[i]=='<'&&src[i+1]=='<') ){
std::string startStr,endStr;
if(src[i]=='<'&&src[i+1]=='<'){
if(!root.children.empty() && (root.children.back().value=="@function")){ startStr = "<<";
endStr = ">>";
Token node{TokenType::BEGIN, startStr, lineno, {}};
int depth = 1;
i += 2;
std::string inner;
size_t inner_lineno = lineno;
while (i + 1 < src.size() && depth > 0) {
if (src.compare(i, 2, startStr) == 0) {
inner +="<<";
i += 2;
continue;
}
if (src.compare(i, 2, endStr) == 0&&(src[i+2]=='\n'||!src[i+2])) {
depth--;
i += 3;
continue;
}
if (src[i] == '\n') lineno++;
inner += src[i++];
}
if (!inner.empty()) {
node.children.push_back({TokenType::INJECT, inner, inner_lineno, {}});
node.children.push_back({TokenType::END, endStr, lineno, {}});
root.children.back().children.push_back(node);
}
}
}else{
startStr = "<{";
endStr = "}>";
Token node{TokenType::BEGIN, startStr, lineno, {}};
int depth = 1;
i += 2;
std::string inner;
size_t inner_lineno = lineno;
while (i + 1 < src.size() && depth > 0) {
if (src.compare(i, 2, startStr) == 0) {
depth++;
i += 2;
continue;
}
if (src.compare(i, 2, endStr) == 0) {
depth--;
i += 2;
continue;
}
if (src[i] == '\n') lineno++;
inner += src[i++];
}
if (!inner.empty()) {
root.children.push_back(node);
root.children.push_back({TokenType::INJECT, inner, inner_lineno, {}});
root.children.push_back({TokenType::END, endStr, lineno, {}});
}
}
continue;
}
//var 變數系統
auto var_nodes = [](const Token& node){
Token result =node;
while(!result.children.empty()) result=result.children.back();
return result;
};
int var_inner_lineno = lineno;
if (src[i] == 'v' && src[i+1] == 'a' && src[i+2] == 'r' ) {
Token node{TokenType::KEYWORD, "var", lineno, {}};Token invar;
i += 3;bool varend=true;
std::string inner;
while (i < src.size()&&varend) {if(!src[i+1]){inner+=src[i];}
std::istringstream ss(inner);
if (src[i] == '\n'||!src[i+1]){Token tmp=tokenizeFile(ss,var_inner_lineno);
while((tmp.children.back().value==";"))tmp.children.pop_back();
invar=tmp;
for(auto& child : invar.children){
if( child.type != TokenType::TYPE) node.children.push_back(child);
}
if(invar.children.back().type==TokenType::TYPE){varend=false;
node.children.push_back(invar.children.back());}
else {inner="";}
lineno++;
}
inner += src[i];i++;
}
/* if(what_is_struct_like.find(invar.children.back().value) != what_is_struct_like.end()){
for(Token& p:invar.children){
if(p.type==TokenType::IDENTIFIER){ p.type==TokenType::STRUCTLIKE;
what_is_struct_like.insert(p.value);}
}
}*/
root.children.push_back(node);
continue;
}
// 運算子 + = > ...
bool matched = false;
for (const auto& op : operators) {
if (i + op.size() <= src.size() &&
src.compare(i, op.size(), op) == 0) {
if(op=="::"){ i+=op.size(); continue; }
root.children.push_back({TokenType::OPERATOR, op, lineno, {}} );
if(!root.children.empty() && (root.children.back().value=="@function")){i+=op.size(); continue; }
i += op.size(); matched = true;
break;
}
}
if (matched) continue;
if(src[i] == ',' || src[i] == ';') {
root.children.push_back({TokenType::SEPARATOR, std::string(1, src[i]), lineno, {}});
i++;
continue;
}
// 數字
if (src[i] >= '0' && src[i] <= '9') {
root.children.push_back(parseNumber(i));
continue;
}
// 識別字
if ((src[i] >= 'a' && src[i] <= 'z') ||
(src[i] >= 'A' && src[i] <= 'Z') ||
src[i] == '_' || src[i] == '@' || src[i] == '#'||src[i]==':'||src[i]=='.') {int depth=0;
Token whole=justconnectidentifier(i),node;std::stringstream ss(whole.value);std::string nod;i-=whole.value.size();
while(getline(ss,nod,'.')){ depth++;
Token v=parseIdentifierOrKeyword(i);std::string end;bool hasfuncname=false;
if(!root.children.empty() &&root.children.back().type == TokenType::funcKEYWORD
&& v.type != TokenType::KEYWORD && v.type != TokenType::funcKEYWORD ){
if(root.children.back().value=="@function"){if (what_is_funcname.find(v.value) != what_is_funcname.end()&&v.type != TokenType::TYPE) v.type = TokenType::funcIDENTIFIER;
root.children.push_back(v);continue;}
if(root.children.back().value=="function"){
if(whole.value.find(".")!=std::string::npos){
if (what_is_namespace_like.find(v.value) != what_is_namespace_like.end()&&v.type != TokenType::TYPE
) v.type = TokenType::NAMESPACELIKE;
Token* cur = &node;//指向node地址
if(depth==1){node=v;cur=&node;continue;}
if(depth>1){
while(!cur->children.empty()){cur = &cur->children.back();} //指向還沒有子節點的a.b.c的最後面一個節點
v.value="."+v.value;if(v.type != TokenType::TYPE){ cur->children.push_back(v); //把a.b.c逐漸從a變a.b變a.b.c
continue;}else{cur->children.push_back(v);root.children.back().children.push_back(node);continue;}
}
}
if(v.type != TokenType::TYPE) v.type = TokenType::funcIDENTIFIER;
what_is_funcname.insert(v.value);
}else{
if(root.children.back().value=="namespace"){what_is_namespace_like.insert(v.value); if(v.type != TokenType::TYPE) v.type = TokenType::NAMESPACELIKE;}
if(root.children.back().value=="struct"){what_is_struct_like.insert(v.value); typeKeywords.insert(v.value); if(v.type != TokenType::TYPE) v.type = TokenType::STRUCTLIKE;}
if(root.children.back().value=="@custom"){custom_command.insert(v.value);what_is_funcname.insert(v.value); v.type = TokenType::funcIDENTIFIER;}
}
if(!root.children.back().children.empty()&&!root.children.back().children.back().children.empty()
&& (root.children.back().children.back().children.back().value== "}"||root.children.back().children.back().children.back().value=="]")&&v.type != TokenType::TYPE) {v.type = TokenType::IDENTIFIER; root.children.push_back(v);continue;}
//上面那段用來避免全域呼叫被丟到function底下
for(auto &child:root.children.back().children){ if (what_is_funcname.find(child.value) != what_is_funcname.end())hasfuncname=true;}
if(hasfuncname&&v.type!=TokenType::TYPE&&!(what_is_struct_like.find(root.children.back().value) != what_is_struct_like.end())
){v.type = TokenType::IDENTIFIER;root.children.push_back(v);continue;}
root.children.back().children.push_back(v);
}
else{
if (what_is_funcname.find(v.value) != what_is_funcname.end()&&v.type != TokenType::TYPE
) v.type = TokenType::funcIDENTIFIER;
if (what_is_namespace_like.find(v.value) != what_is_namespace_like.end()&&v.type != TokenType::TYPE
) v.type = TokenType::NAMESPACELIKE;
if (what_is_struct_like.find(v.value) != what_is_struct_like.end()&&v.type != TokenType::TYPE
) v.type = TokenType::STRUCTLIKE;
if(!root.children.empty()&& root.children.back().type == TokenType::TYPE&&what_is_struct_like.find(root.children.back().value) != what_is_struct_like.end()) {
what_is_struct_like.insert(v.value);v.type=TokenType::STRUCTLIKE;root.children.push_back(v);continue;}
if(!root.children.empty()&& root.children.back().type == TokenType::NAMESPACELIKE&&v.value.find(".")==std::string::npos) {
what_is_struct_like.insert(v.value);v.type=TokenType::NAMESPACELIKE;root.children.push_back(v);continue;}
if(!root.children.empty()&&custom_command.find(v.value)!=custom_command.end()&&root.children.back().type!=TokenType::SEPARATOR
&&root.children.back().value!="var"){
v.type = TokenType::funcIDENTIFIER;
root.children.back().children.push_back(v);continue;
}
if(whole.value==v.value){root.children.push_back(v);} //沒有a.b.c只有一層
else{Token* cur = &node;//指向node地址
if(depth==1){node=v;cur=&node;}
if(depth>1){
while(!cur->children.empty()){cur = &cur->children.back();} //指向還沒有子節點的a.b.c的最後面一個節點
if(custom_command.find(v.value)!=custom_command.end()){ ;node.value=whole.value;node.type=TokenType::funcIDENTIFIER;node.children={};}
else{v.value="."+v.value; cur->children.push_back(v);}//把a.b.c逐漸從a變a.b變a.b.c
}
}
}
}
if(depth>1&&!root.children.empty()&&root.children.back().value=="function")continue;
if(depth>1){ root.children.push_back(node); }
continue;
}
if (src[i] == '\n'){lineno++;}
i++; // 防止死循環
}
return root;
}
// ====== token 執行接口 ======
// runTokenFunc 對應原 funcfile while,執行 token handler
Token singletoken(const Token& node, const std::string& afterSeper);
std::string sumLeftparen(const Token& node) {
std::string rt=node.value,result;
for(auto& p:node.children){rt+=sumLeftparen(p);}
return rt;
}
std::string AdotBdotC(const Token& node,std::string spepar="") {
std::string result=node.value,callb,sp,cur;
if(node.type==TokenType::NAMESPACELIKE) sp="::";else if(node.type==TokenType::STRUCTLIKE) sp="."; else sp=spepar;
if(node.value.find(".")!=std::string::npos){
if(node.children.empty()){ cur=node.value.substr(node.value.find(".")+1,node.value.size()-1);return spepar+cur; }
else { cur=node.value.substr(node.value.find(".")+1,node.value.size()-1);cur+=AdotBdotC(node.children[0],sp);return spepar+cur; }
}
for(auto& p:node.children){
if(p.value=="(") callb+=sumLeftparen(p);
else result+=AdotBdotC(p,sp);}
return result+" "+callb;
}
std::string sumLeftbrackets(const Token& node) {
std::string result=node.value;
if(node.type==TokenType::NAMESPACELIKE||node.type==TokenType::STRUCTLIKE){result= AdotBdotC(node);return result;}
if(node.type == TokenType::KEYWORD&& !node.children.empty()){ auto it = tokenHandlers.find(node.value);Token k;k.type=TokenType::UNKNOWN;if (it != tokenHandlers.end()){
k.value=it->second(node);
}return k.value; }
if(node.type == TokenType::funcKEYWORD& !node.children.empty()){ auto it = funcHandlers.find(node.value);Token k;k.type=TokenType::UNKNOWN;if (it != funcHandlers.end()){
k.value=it->second(node);
}return k.value; }
if(node.type==TokenType::funcIDENTIFIER&&!node.children.empty()){
auto cusit =custom_command_arg.find(node.value);
if(cusit!=custom_command_arg.end()){
std::vector<Token> templa=cusit->second;std::vector<size_t> args;Token out;bool hasback=false;std::string tmp;
for(size_t pos=0;pos<templa.size();pos++){if(templa[pos].type==TokenType::INJECT)args.push_back(pos);}
for(size_t i=0,j=0;i<node.children[0].children.size();i++){ Token cur=node.children[0].children[i];cur.value=singletoken(cur,",").value;
if(cur.value!="<{"&&cur.value!="}>"){
if(cur.value=="{"){ for(auto& inside:cur.children)cur.value+=singletoken(inside,";").value;}
if(cur.value==","||cur.value==")"){j++;tmp="";continue;}else{tmp+=" "+cur.value;}
if(j>=args.size()){j=0;hasback=true; }
if(!hasback){templa[args[j]].value=tmp;} else{templa[args[j]].value+=tmp;}
}
}
for(auto& p:templa){out.value+=p.value;}
out.type=TokenType::INJECT;
return out.value;
}
}
for(auto& p:node.children){
result+=sumLeftbrackets(p);}
return result;
}
Token mergetoken(const Token& node, const std::string& afterSeper) {
if(node.type == TokenType::STRING){return node;}
if(node.type == TokenType::NUMBER){return node;}
if(node.type == TokenType::IDENTIFIER&&node.children.empty()){ return node;}
if(node.type == TokenType::IDENTIFIER&& !node.children.empty()){ }
if (node.type == TokenType::KEYWORD&&(node.value=="true"||node.value=="false")) {Token tfbool;tfbool.type==TokenType::STRING;tfbool.value="\""+node.value+"\""; return tfbool;}
if (node.type == TokenType::SEPARATOR) {Token aftp;aftp.type==TokenType::SEPARATOR;aftp.value=afterSeper; return aftp;}
Token result; result.type = TokenType::STRING;
for (const auto& child : node.children) {
result.value += mergetoken(child,afterSeper).value;
}
return result; }
Token singletoken(const Token& node, const std::string& afterSeper) {
Token result; bool boolkey =(node.value=="true"||node.value=="false")?true:false;
if(node.type == TokenType::STRING){result.type = TokenType::STRING;return node;}
if(node.type == TokenType::CHAR){result.type = TokenType::CHAR;return node;}
if(node.type == TokenType::NUMBER){result.type = TokenType::NUMBER; return node;}
if(node.type == TokenType::OPERATOR){result.type = TokenType::NUMBER; return node;}
if(node.type == TokenType::INJECT){result.type = TokenType::INJECT; return node;}
if(node.value=="<{"||node.value=="}>" ){return result;}
if(node.value=="{"){result.value+=sumLeftbrackets(node);return result;}
if(node.type==TokenType::funcIDENTIFIER&&!node.children.empty()){
auto cusit =custom_command_arg.find(node.value);
if(cusit!=custom_command_arg.end()){
std::vector<Token> templa=cusit->second;std::vector<size_t> args;Token out;bool hasback=false;std::string tmp;
for(size_t pos=0;pos<templa.size();pos++){if(templa[pos].type==TokenType::INJECT)args.push_back(pos);}
for(size_t i=0,j=0;i<node.children[0].children.size();i++){ Token cur=node.children[0].children[i];cur.value=singletoken(cur,",").value;
if(cur.value!="<{"&&cur.value!="}>"){
if(cur.value=="{"){ for(auto& inside:cur.children)cur.value+=singletoken(inside,";").value;}
if(cur.value==","||cur.value==")"){j++;tmp="";continue;}else{tmp+=" "+cur.value;}
if(j>=args.size()){j=0;hasback=true; }
if(!hasback){templa[args[j]].value=tmp;} else{templa[args[j]].value+=tmp;}
}
}
for(auto& p:templa){out.value+=p.value;}
out.type=TokenType::INJECT;
return out;
}
bool iftemplate=false; for(auto& child:node.children){ if(child.value!="(")iftemplate=true;}
if(!iftemplate)result.value=node.value+"(" ;else result.value=node.value;
for(auto& child:node.children){
if(child.value!="("){result.value+=singletoken(child,",").value+"(";continue;}
for(auto& p:child.children){
if(p.value=="("){result.value+=sumLeftparen(p);continue;}
result.value+=singletoken(p,",").value;
}
}
return result;
}
if(node.type == TokenType::TYPE){
if(node.value=="float"){result.value="double";result.type = TokenType::TYPE;return result;}
if(node.value=="string"){result.value="std::string";result.type = TokenType::TYPE;return result;}
if(what_is_struct_like.find(node.value)!=what_is_struct_like.end()){result=node;result.value+=" ";return result;}
}
if(node.type == TokenType::IDENTIFIER&&node.children.empty()){
if(node.value=="true"||node.value=="false"){Token tfbool;tfbool.type=TokenType::STRING;
result.type = TokenType::KEYWORD;//tfbool.value="\""+node.value+"\"";
tfbool.value=node.value; return tfbool;}else{
result.type = TokenType::IDENTIFIER; return node;} }
if(node.type==TokenType::NAMESPACELIKE||node.type==TokenType::STRUCTLIKE){Token n=node;n.value=AdotBdotC(node);return n;}
if(node.type == TokenType::KEYWORD ){ auto it = tokenHandlers.find(node.value);Token k;k.type=TokenType::UNKNOWN;if (it != tokenHandlers.end()){
k.value=it->second(node);
}return k; }
if(node.type == TokenType::funcKEYWORD ){ auto it = funcHandlers.find(node.value);Token k;k.type=TokenType::UNKNOWN;if (it != funcHandlers.end()){
k.value=it->second(node);
}return k; }
if (node.type == TokenType::SEPARATOR) {Token aftp;aftp.type=TokenType::SEPARATOR;result.type = TokenType::SEPARATOR;aftp.value=afterSeper; return aftp;}
return node; }
Token injecttoken(const Token& node) {
if(node.type !=TokenType::ROOT) return node;
Token result; result.type = TokenType::STRING;
for (const auto& child : node.children) {
result.value += injecttoken(child).value;
}
return result; }
std::string runTokenFunc(const Token& node) {
std::string result;
auto it = funcHandlers.find(node.value);
if (it != funcHandlers.end()) {
return it->second(node); // 傳入整個 KEYWORD 節點
}
auto itk = tokenHandlers.find(node.value);
if (itk != tokenHandlers.end()) {
return ""; // 傳入整個 KEYWORD 節點
}
auto cusit =custom_command_arg.find(node.value);
if(node.type==TokenType::funcIDENTIFIER&&!node.children.empty()){
if(cusit!=custom_command_arg.end()){
std::vector<Token> templa=cusit->second;
std::vector<size_t> args;std::string out,tmp;bool hasback=false;
for(size_t pos=0;pos<templa.size();pos++){if(templa[pos].type==TokenType::INJECT)args.push_back(pos);}
for(size_t i=0,j=0;i<node.children[0].children.size();i++){ Token cur=node.children[0].children[i];cur.value=singletoken(cur,",").value;
if(cur.value!="<{"&&cur.value!="}>"){
if(cur.value==","||cur.value==")"){j++;tmp="";continue;}else{tmp+=" "+cur.value;}
if(j>=args.size()){j=0;hasback=true; }
if(cur.value=="{"){ for(auto& inside:cur.children)cur.value+=singletoken(inside,";").value;}
if(!hasback){templa[args[j]].value=tmp;} else{templa[args[j]].value+=tmp;}
}
}
for(auto& p:templa){out+=p.value;}
return out;
}else{return "";}
}
// 遞迴子 token
for (const auto& child : node.children) {
result += runTokenFunc(child);
}
return result;
}
// runToken 對應普通程式行
std::string runToken(const Token& node) {
std::string result;
auto it = tokenHandlers.find(node.value);
if (it != tokenHandlers.end()) {
return it->second(node); // 傳入整個 KEYWORD 節點
}
auto itf = funcHandlers.find(node.value);//防止重複輸出runTokenFunc裡面{...}的關鍵字
if (itf != funcHandlers.end()) {
return ""; // 傳入整個 KEYWORD 節點
}
if(node.type==TokenType::funcIDENTIFIER&&!node.children.empty()){
auto cusit =custom_command_arg.find(node.value);
if( cusit!=custom_command_arg.end()){
return "";
}
bool iftemplate=false; for(auto& child:node.children){ if(child.value!="(")iftemplate=true;}
if(!iftemplate)result=node.value+"(" ;else result=node.value;
for(auto& child:node.children){
if(child.value!="("){result+=singletoken(child,",").value+"(";continue;}
for(auto& p:child.children){
if(p.value=="("){result+=sumLeftparen(p);continue;}
result+=singletoken(p,",").value;
}
}
return result+";";
}
if(node.type==TokenType::IDENTIFIER||node.type==TokenType::STRING||node.type==TokenType::NUMBER
||node.type==TokenType::CHAR||node.type==TokenType::OPERATOR||node.type==TokenType::SEPARATOR){
if(((node.value.find('.') != std::string::npos&&node.type!=TokenType::NUMBER) || (!node.children.empty() &&
node.children.back().value.find('.') != std::string::npos) )) return "";//a.b.c節點跳過,另外處理
result+=node.value;
}
if(node.type==TokenType::NAMESPACELIKE||node.type==TokenType::STRUCTLIKE){return AdotBdotC(node);}
if(node.value=="{"){result+=sumLeftbrackets(node);return result;}
if(what_is_struct_like.find(node.value)!=what_is_struct_like.end()){return node.value+" ";}
// 遞迴子 token
for (const auto& child : node.children) {
result += runToken(child);
}
return result;
}
std::string escapeUtf8(const std::string& s) {
std::string out;
for(unsigned char c : s){
if(c >= 32 && c <= 126) out += c; // 可打印 ASCII
else { char buf[5];snprintf(buf, sizeof(buf), "\\x%02X", c); out += buf; }}
return out;
}
void printToken(const Token& node, int indent=0) {
std::string pad(indent*2, '-');
std::string value=((int)node.type==0)?"root---":escapeUtf8(node.value);
std::cout << pad << "Token(type=" << (int)node.type
<< ", value=\""<< value
<< "\", line=" << node.line_number << ")\n";
for(auto& child: node.children){
printToken(child, indent+1);
}
}
std::unordered_map<std::string, std::string> namespace_parent;
std::string namespace_tree(std::string name){
std::string result;
if(namespace_parent.find(name)!=namespace_parent.end()) {result+= namespace_tree(namespace_parent[name])+"."+name;}
else result+=name;
return result;
}
void registcondition(){
registerToken("if", [](const Token& node) {
std::string argcond,argcont,cur,cr,ed;
for(auto& root: node.children){
if(root.value=="("){ argcond="if(";
for(auto& cond: root.children){
if(cond.type==TokenType::KEYWORD){
argcond="";argcond+=singletoken(cond,"").value;argcond+="if(";argcond+=cond.children[0].children[0].value;
}else{ cur= singletoken(cond,"").value;
if(cur=="("){for(auto& p:cond.children){cur+= singletoken(p,"").value;}}
argcond+=cur;}
}
}
if(root.value=="{"){ argcont="{";
for( size_t i=0; i<root.children.size(); i++){
auto& cont=root.children[i];
cr= singletoken(cont,";").value;
if(cont.value=="<{"||cont.value=="}>"||cont.type==TokenType::COMMENT){continue;}
if(cr=="("){for(auto& p:cont.children){cr+= singletoken(p,"").value;}}
argcont+=cr;
if(cont.type==TokenType::IDENTIFIER||cont.type==TokenType::STRING||cont.type==TokenType::NUMBER
||cont.type==TokenType::CHAR||cont.type==TokenType::INJECT||cont.type==TokenType::OPERATOR||cont.value=="("
||cont.type==TokenType::funcIDENTIFIER||cont.type==TokenType::NAMESPACELIKE||cont.type==TokenType::STRUCTLIKE
){ if( root.children[i+1].value=="}"||root.children[i+1].line_number==cont.line_number+1){ argcont+=";\n";}
}
} }
}
return argcond+argcont+"\n";
});
registerToken("else", [](const Token& node) {
std::string argcont,cur;
for(auto& root: node.children){
if(node.children.empty()){ argcont= "";}
if(root.value=="{"){ argcont="{";
for( size_t i=0; i<root.children.size(); i++){
auto& cont=root.children[i];
cur= singletoken(cont,";").value;
if(cont.value=="<{"||cont.value=="}>"||cont.type==TokenType::COMMENT){continue;}
if(cur=="("){for(auto& p:cont.children){cur+= singletoken(p,"").value;}}
argcont+=cur;
if(cont.type==TokenType::IDENTIFIER||cont.type==TokenType::STRING||cont.type==TokenType::NUMBER
||cont.type==TokenType::CHAR||cont.type==TokenType::INJECT||cont.type==TokenType::OPERATOR||cont.value=="("
||cont.type==TokenType::funcIDENTIFIER||cont.type==TokenType::NAMESPACELIKE||cont.type==TokenType::STRUCTLIKE
){ if( root.children[i+1].value=="}"||root.children[i+1].line_number==cont.line_number+1){ argcont+=";\n";}
}
} }
}
return "else " + argcont + "\n";
});
registerToken("for", [](const Token& node) {
std::string argcond,argcont,cur,cr,ed;std::vector<char> sepg;int sep=0;
for(auto& root: node.children){
if(root.value=="("){ argcond="for(";
for(auto& cond: root.children){
if(cond.value==";"||cond.value==","){sepg.push_back(cond.value[0]);if(cond.value==";")sep++;}
cur= singletoken(cond,";").value;
if(cur=="("||cur=="{"){for(auto& p:cond.children){cur+= singletoken(p,",").value;}}
if(cond.type==TokenType::IDENTIFIER){cur=" "+cur;}
argcond+=cur;
}
if(sep==2){
for(size_t i=0,j=0; i<argcond.size(); i++){ if(argcond[i]==';'){ if(sepg[j]==','){argcond[i]=',';} j++; }}
}
}
if(root.value=="{"){ argcont="{";
for( size_t i=0; i<root.children.size(); i++){
auto& cont=root.children[i];
cr= singletoken(cont,";").value;
if(cont.value=="<{"||cont.value=="}>"||cont.type==TokenType::COMMENT){continue;}
if(cr=="("){for(auto& p:cont.children){cr+= singletoken(p,"").value;}}
argcont+=cr;
if(cont.type==TokenType::IDENTIFIER||cont.type==TokenType::STRING||cont.type==TokenType::NUMBER
||cont.type==TokenType::CHAR||cont.type==TokenType::INJECT||cont.type==TokenType::OPERATOR||cont.value=="("
||cont.type==TokenType::funcIDENTIFIER||cont.type==TokenType::NAMESPACELIKE||cont.type==TokenType::STRUCTLIKE
){ if( root.children[i+1].value=="}"||root.children[i+1].line_number==cont.line_number+1){ argcont+=";\n";}
}
} }
}
return argcond+argcont+"\n";
});
registerToken("while", [](const Token& node) {
std::string argcond,argcont,cur,cr,ed;std::vector<char> sepg;int sep=0;
for(auto& root: node.children){
if(root.value=="("){ argcond="while(";
for(auto& cond: root.children){
if(cond.value==";"||cond.value==","){sepg.push_back(cond.value[0]);if(cond.value==";")sep++;}
cur= singletoken(cond,";").value;
if(cur=="("||cur=="{"){for(auto& p:cond.children){cur+= singletoken(p,",").value;}}
if(cond.type==TokenType::IDENTIFIER){cur=" "+cur;}
argcond+=cur;
}
if(sep==2){
for(size_t i=0,j=0; i<argcond.size(); i++){ if(argcond[i]==';'){ if(sepg[j]==','){argcond[i]=',';} j++; }}
}
}
if(root.value=="{"){ argcont="{";
for( size_t i=0; i<root.children.size(); i++){
auto& cont=root.children[i];
cr= singletoken(cont,";").value;
if(cont.value=="<{"||cont.value=="}>"||cont.type==TokenType::COMMENT){continue;}
if(cr=="("){for(auto& p:cont.children){cr+= singletoken(p,"").value;}}
argcont+=cr;
if(cont.type==TokenType::IDENTIFIER||cont.type==TokenType::STRING||cont.type==TokenType::NUMBER
||cont.type==TokenType::CHAR||cont.type==TokenType::INJECT||cont.type==TokenType::OPERATOR||cont.value=="("
||cont.type==TokenType::funcIDENTIFIER||cont.type==TokenType::NAMESPACELIKE||cont.type==TokenType::STRUCTLIKE
){ if( root.children[i+1].value=="}"||root.children[i+1].line_number==cont.line_number+1){ argcont+=";\n";}
}
} }
}
return argcond+argcont+"\n";
});
}
void registfunckeyword(){
registerfunc("function",[](const Token& node){
std::string parag,type,funcname,cont,cr;bool declared=false,guesstype=false,hasparen=false;
for(auto& p:node.children){
if(p.type==TokenType::TYPE){type=p.value;type=(type=="float")?"double":(type=="string")?"std::string":type;}