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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
|
#include "scriptbuilder.h"
#include <vector>
#include <assert.h>
using namespace std;
#include <stdio.h>
#if defined(_MSC_VER) && !defined(_WIN32_WCE) && !defined(__S3E__)
#include <direct.h>
#endif
#ifdef _WIN32_WCE
#include <windows.h> // For GetModuleFileName()
#endif
#if defined(__S3E__) || defined(__APPLE__) || defined(__GNUC__)
#include <unistd.h> // For getcwd()
#endif
BEGIN_AS_NAMESPACE
// Helper functions
static string GetCurrentDir();
static string GetAbsolutePath(const string &path);
CScriptBuilder::CScriptBuilder()
{
engine = 0;
module = 0;
includeCallback = 0;
callbackParam = 0;
}
void CScriptBuilder::SetIncludeCallback(INCLUDECALLBACK_t callback, void *userParam)
{
includeCallback = callback;
callbackParam = userParam;
}
int CScriptBuilder::StartNewModule(asIScriptEngine *inEngine, const char *moduleName)
{
if(inEngine == 0 ) return -1;
engine = inEngine;
module = inEngine->GetModule(moduleName, asGM_ALWAYS_CREATE);
if( module == 0 )
return -1;
ClearAll();
return 0;
}
asIScriptModule *CScriptBuilder::GetModule()
{
return module;
}
unsigned int CScriptBuilder::GetSectionCount() const
{
return (unsigned int)(includedScripts.size());
}
string CScriptBuilder::GetSectionName(unsigned int idx) const
{
if( idx >= includedScripts.size() ) return "";
#ifdef _WIN32
set<string, ci_less>::const_iterator it = includedScripts.begin();
#else
set<string>::const_iterator it = includedScripts.begin();
#endif
while( idx-- > 0 ) it++;
return *it;
}
// Returns 1 if the section was included
// Returns 0 if the section was not included because it had already been included before
// Returns <0 if there was an error
int CScriptBuilder::AddSectionFromFile(const char *filename)
{
// The file name stored in the set should be the fully resolved name because
// it is possible to name the same file in multiple ways using relative paths.
string fullpath = GetAbsolutePath(filename);
if( IncludeIfNotAlreadyIncluded(fullpath.c_str()) )
{
int r = LoadScriptSection(fullpath.c_str());
if( r < 0 )
return r;
else
return 1;
}
return 0;
}
// Returns 1 if the section was included
// Returns 0 if the section was not included because it had already been included before
// Returns <0 if there was an error
int CScriptBuilder::AddSectionFromMemory(const char *sectionName, const char *scriptCode, unsigned int scriptLength, int lineOffset)
{
if( IncludeIfNotAlreadyIncluded(sectionName) )
{
int r = ProcessScriptSection(scriptCode, scriptLength, sectionName, lineOffset);
if( r < 0 )
return r;
else
return 1;
}
return 0;
}
int CScriptBuilder::BuildModule()
{
return Build();
}
void CScriptBuilder::DefineWord(const char *word)
{
string sword = word;
if( definedWords.find(sword) == definedWords.end() )
{
definedWords.insert(sword);
}
}
void CScriptBuilder::ClearAll()
{
includedScripts.clear();
#if AS_PROCESS_METADATA == 1
currentClass = "";
currentNamespace = "";
foundDeclarations.clear();
typeMetadataMap.clear();
funcMetadataMap.clear();
varMetadataMap.clear();
#endif
}
bool CScriptBuilder::IncludeIfNotAlreadyIncluded(const char *filename)
{
string scriptFile = filename;
if( includedScripts.find(scriptFile) != includedScripts.end() )
{
// Already included
return false;
}
// Add the file to the set of included sections
includedScripts.insert(scriptFile);
return true;
}
int CScriptBuilder::LoadScriptSection(const char *filename)
{
// Open the script file
string scriptFile = filename;
#if _MSC_VER >= 1500 && !defined(__S3E__)
FILE *f = 0;
fopen_s(&f, scriptFile.c_str(), "rb");
#else
FILE *f = fopen(scriptFile.c_str(), "rb");
#endif
if( f == 0 )
{
// Write a message to the engine's message callback
string msg = "Failed to open script file '" + GetAbsolutePath(scriptFile) + "'";
engine->WriteMessage(filename, 0, 0, asMSGTYPE_ERROR, msg.c_str());
// TODO: Write the file where this one was included from
return -1;
}
// Determine size of the file
fseek(f, 0, SEEK_END);
int len = ftell(f);
fseek(f, 0, SEEK_SET);
// On Win32 it is possible to do the following instead
// int len = _filelength(_fileno(f));
// Read the entire file
string code;
size_t c = 0;
if( len > 0 )
{
code.resize(len);
c = fread(&code[0], len, 1, f);
}
fclose(f);
if( c == 0 && len > 0 )
{
// Write a message to the engine's message callback
string msg = "Failed to load script file '" + GetAbsolutePath(scriptFile) + "'";
engine->WriteMessage(filename, 0, 0, asMSGTYPE_ERROR, msg.c_str());
return -1;
}
// Process the script section even if it is zero length so that the name is registered
return ProcessScriptSection(code.c_str(), (unsigned int)(code.length()), filename, 0);
}
int CScriptBuilder::ProcessScriptSection(const char *script, unsigned int length, const char *sectionname, int lineOffset)
{
vector<string> includes;
// Perform a superficial parsing of the script first to store the metadata
if( length )
modifiedScript.assign(script, length);
else
modifiedScript = script;
// First perform the checks for #if directives to exclude code that shouldn't be compiled
unsigned int pos = 0;
int nested = 0;
while( pos < modifiedScript.size() )
{
asUINT len = 0;
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_UNKNOWN && modifiedScript[pos] == '#' && (pos + 1 < modifiedScript.size()) )
{
int start = pos++;
// Is this an #if directive?
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
string token;
token.assign(&modifiedScript[pos], len);
pos += len;
if( token == "if" )
{
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_WHITESPACE )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
}
if( t == asTC_IDENTIFIER )
{
string word;
word.assign(&modifiedScript[pos], len);
// Overwrite the #if directive with space characters to avoid compiler error
pos += len;
OverwriteCode(start, pos-start);
// Has this identifier been defined by the application or not?
if( definedWords.find(word) == definedWords.end() )
{
// Exclude all the code until and including the #endif
pos = ExcludeCode(pos);
}
else
{
nested++;
}
}
}
else if( token == "endif" )
{
// Only remove the #endif if there was a matching #if
if( nested > 0 )
{
OverwriteCode(start, pos-start);
nested--;
}
}
}
else
pos += len;
}
#if AS_PROCESS_METADATA == 1
// Preallocate memory
string metadata, name, declaration;
metadata.reserve(500);
declaration.reserve(100);
#endif
// Then check for meta data and #include directives
pos = 0;
while( pos < modifiedScript.size() )
{
asUINT len = 0;
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_COMMENT || t == asTC_WHITESPACE )
{
pos += len;
continue;
}
#if AS_PROCESS_METADATA == 1
// Check if class
if( currentClass == "" && modifiedScript.substr(pos,len) == "class" )
{
// Get the identifier after "class"
do
{
pos += len;
if( pos >= modifiedScript.size() )
{
t = asTC_UNKNOWN;
break;
}
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
} while(t == asTC_COMMENT || t == asTC_WHITESPACE);
if( t == asTC_IDENTIFIER )
{
currentClass = modifiedScript.substr(pos,len);
// Search until first { or ; is encountered
while( pos < modifiedScript.length() )
{
engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
// If start of class section encountered stop
if( modifiedScript[pos] == '{' )
{
pos += len;
break;
}
else if (modifiedScript[pos] == ';')
{
// The class declaration has ended and there are no children
currentClass = "";
pos += len;
break;
}
// Check next symbol
pos += len;
}
}
continue;
}
// Check if end of class
if( currentClass != "" && modifiedScript[pos] == '}' )
{
currentClass = "";
pos += len;
continue;
}
// Check if namespace
if( modifiedScript.substr(pos,len) == "namespace" )
{
// Get the identifier after "namespace"
do
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
} while(t == asTC_COMMENT || t == asTC_WHITESPACE);
if( currentNamespace != "" )
currentNamespace += "::";
currentNamespace += modifiedScript.substr(pos,len);
// Search until first { is encountered
while( pos < modifiedScript.length() )
{
engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
// If start of namespace section encountered stop
if( modifiedScript[pos] == '{' )
{
pos += len;
break;
}
// Check next symbol
pos += len;
}
continue;
}
// Check if end of namespace
if( currentNamespace != "" && modifiedScript[pos] == '}' )
{
size_t found = currentNamespace.rfind( "::" );
if( found != string::npos )
{
currentNamespace.erase( found );
}
else
{
currentNamespace = "";
}
pos += len;
continue;
}
// Is this the start of metadata?
if( modifiedScript[pos] == '[' )
{
// Get the metadata string
pos = ExtractMetadataString(pos, metadata);
// Determine what this metadata is for
int type;
ExtractDeclaration(pos, name, declaration, type);
// Store away the declaration in a map for lookup after the build has completed
if( type > 0 )
{
SMetadataDecl decl(metadata, name, declaration, type, currentClass, currentNamespace);
foundDeclarations.push_back(decl);
}
}
else
#endif
// Is this a preprocessor directive?
if( modifiedScript[pos] == '#' && (pos + 1 < modifiedScript.size()) )
{
int start = pos++;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_IDENTIFIER )
{
string token;
token.assign(&modifiedScript[pos], len);
if( token == "include" )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_WHITESPACE )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
}
if( t == asTC_VALUE && len > 2 && (modifiedScript[pos] == '"' || modifiedScript[pos] == '\'') )
{
// Get the include file
string includefile;
includefile.assign(&modifiedScript[pos+1], len-2);
pos += len;
// Store it for later processing
includes.push_back(includefile);
// Overwrite the include directive with space characters to avoid compiler error
OverwriteCode(start, pos-start);
}
}
}
}
// Don't search for metadata/includes within statement blocks or between tokens in statements
else
{
pos = SkipStatement(pos);
}
}
// Build the actual script
engine->SetEngineProperty(asEP_COPY_SCRIPT_SECTIONS, true);
module->AddScriptSection(sectionname, modifiedScript.c_str(), modifiedScript.size(), lineOffset);
if( includes.size() > 0 )
{
// If the callback has been set, then call it for each included file
if( includeCallback )
{
for( int n = 0; n < (int)includes.size(); n++ )
{
int r = includeCallback(includes[n].c_str(), sectionname, this, callbackParam);
if( r < 0 )
return r;
}
}
else
{
// By default we try to load the included file from the relative directory of the current file
// Determine the path of the current script so that we can resolve relative paths for includes
string path = sectionname;
size_t posOfSlash = path.find_last_of("/\\");
if( posOfSlash != string::npos )
path.resize(posOfSlash+1);
else
path = "";
// Load the included scripts
for( int n = 0; n < (int)includes.size(); n++ )
{
// If the include is a relative path, then prepend the path of the originating script
if( includes[n].find_first_of("/\\") != 0 &&
includes[n].find_first_of(":") == string::npos )
{
includes[n] = path + includes[n];
}
// Include the script section
int r = AddSectionFromFile(includes[n].c_str());
if( r < 0 )
return r;
}
}
}
return 0;
}
int CScriptBuilder::Build()
{
int r = module->Build();
if( r < 0 )
return r;
#if AS_PROCESS_METADATA == 1
// After the script has been built, the metadata strings should be
// stored for later lookup by function id, type id, and variable index
for( int n = 0; n < (int)foundDeclarations.size(); n++ )
{
SMetadataDecl *decl = &foundDeclarations[n];
module->SetDefaultNamespace(decl->nameSpace.c_str());
if( decl->type == MDT_TYPE )
{
// Find the type id
int typeId = module->GetTypeIdByDecl(decl->declaration.c_str());
assert( typeId >= 0 );
if( typeId >= 0 )
typeMetadataMap.insert(map<int, string>::value_type(typeId, decl->metadata));
}
else if( decl->type == MDT_FUNC )
{
if( decl->parentClass == "" )
{
// Find the function id
asIScriptFunction *func = module->GetFunctionByDecl(decl->declaration.c_str());
assert( func );
if( func )
funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
else
{
// Find the method id
int typeId = module->GetTypeIdByDecl(decl->parentClass.c_str());
assert( typeId > 0 );
map<int, SClassMetadata>::iterator it = classMetadataMap.find(typeId);
if( it == classMetadataMap.end() )
{
classMetadataMap.insert(map<int, SClassMetadata>::value_type(typeId, SClassMetadata(decl->parentClass)));
it = classMetadataMap.find(typeId);
}
asITypeInfo *type = engine->GetTypeInfoById(typeId);
asIScriptFunction *func = type->GetMethodByDecl(decl->declaration.c_str());
assert( func );
if( func )
it->second.funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
}
else if( decl->type == MDT_VIRTPROP )
{
if( decl->parentClass == "" )
{
// Find the global virtual property accessors
asIScriptFunction *func = module->GetFunctionByName(("get_" + decl->declaration).c_str());
if( func )
funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
func = module->GetFunctionByName(("set_" + decl->declaration).c_str());
if( func )
funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
else
{
// Find the method virtual property accessors
int typeId = module->GetTypeIdByDecl(decl->parentClass.c_str());
assert( typeId > 0 );
map<int, SClassMetadata>::iterator it = classMetadataMap.find(typeId);
if( it == classMetadataMap.end() )
{
classMetadataMap.insert(map<int, SClassMetadata>::value_type(typeId, SClassMetadata(decl->parentClass)));
it = classMetadataMap.find(typeId);
}
asITypeInfo *type = engine->GetTypeInfoById(typeId);
asIScriptFunction *func = type->GetMethodByName(("get_" + decl->declaration).c_str());
if( func )
it->second.funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
func = type->GetMethodByName(("set_" + decl->declaration).c_str());
if( func )
it->second.funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
}
else if( decl->type == MDT_VAR )
{
if( decl->parentClass == "" )
{
// Find the global variable index
int varIdx = module->GetGlobalVarIndexByName(decl->declaration.c_str());
assert( varIdx >= 0 );
if( varIdx >= 0 )
varMetadataMap.insert(map<int, string>::value_type(varIdx, decl->metadata));
}
else
{
int typeId = module->GetTypeIdByDecl(decl->parentClass.c_str());
assert( typeId > 0 );
// Add the classes if needed
map<int, SClassMetadata>::iterator it = classMetadataMap.find(typeId);
if( it == classMetadataMap.end() )
{
classMetadataMap.insert(map<int, SClassMetadata>::value_type(typeId, SClassMetadata(decl->parentClass)));
it = classMetadataMap.find(typeId);
}
// Add the variable to class
asITypeInfo *objectType = engine->GetTypeInfoById(typeId);
int idx = -1;
// Search through all properties to get proper declaration
for( asUINT i = 0; i < (asUINT)objectType->GetPropertyCount(); ++i )
{
const char *name;
objectType->GetProperty(i, &name);
if( decl->declaration == name )
{
idx = i;
break;
}
}
// If found, add it
assert( idx >= 0 );
if( idx >= 0 ) it->second.varMetadataMap.insert(map<int, string>::value_type(idx, decl->metadata));
}
}
else if (decl->type == MDT_FUNC_OR_VAR)
{
if (decl->parentClass == "")
{
// Find the global variable index
int varIdx = module->GetGlobalVarIndexByName(decl->name.c_str());
if (varIdx >= 0)
varMetadataMap.insert(map<int, string>::value_type(varIdx, decl->metadata));
else
{
asIScriptFunction *func = module->GetFunctionByDecl(decl->declaration.c_str());
assert(func);
if (func)
funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
}
else
{
int typeId = module->GetTypeIdByDecl(decl->parentClass.c_str());
assert(typeId > 0);
// Add the classes if needed
map<int, SClassMetadata>::iterator it = classMetadataMap.find(typeId);
if (it == classMetadataMap.end())
{
classMetadataMap.insert(map<int, SClassMetadata>::value_type(typeId, SClassMetadata(decl->parentClass)));
it = classMetadataMap.find(typeId);
}
// Add the variable to class
asITypeInfo *objectType = engine->GetTypeInfoById(typeId);
int idx = -1;
// Search through all properties to get proper declaration
for (asUINT i = 0; i < (asUINT)objectType->GetPropertyCount(); ++i)
{
const char *name;
objectType->GetProperty(i, &name);
if (decl->name == name)
{
idx = i;
break;
}
}
// If found, add it
if (idx >= 0)
it->second.varMetadataMap.insert(map<int, string>::value_type(idx, decl->metadata));
else
{
// Look for the matching method instead
asITypeInfo *type = engine->GetTypeInfoById(typeId);
asIScriptFunction *func = type->GetMethodByDecl(decl->declaration.c_str());
assert(func);
if (func)
it->second.funcMetadataMap.insert(map<int, string>::value_type(func->GetId(), decl->metadata));
}
}
}
}
module->SetDefaultNamespace("");
#endif
return 0;
}
int CScriptBuilder::SkipStatement(int pos)
{
asUINT len = 0;
// Skip until ; or { whichever comes first
while( pos < (int)modifiedScript.length() && modifiedScript[pos] != ';' && modifiedScript[pos] != '{' )
{
engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
pos += len;
}
// Skip entire statement block
if( pos < (int)modifiedScript.length() && modifiedScript[pos] == '{' )
{
pos += 1;
// Find the end of the statement block
int level = 1;
while( level > 0 && pos < (int)modifiedScript.size() )
{
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_KEYWORD )
{
if( modifiedScript[pos] == '{' )
level++;
else if( modifiedScript[pos] == '}' )
level--;
}
pos += len;
}
}
else
pos += 1;
return pos;
}
// Overwrite all code with blanks until the matching #endif
int CScriptBuilder::ExcludeCode(int pos)
{
asUINT len = 0;
int nested = 0;
while( pos < (int)modifiedScript.size() )
{
engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( modifiedScript[pos] == '#' )
{
modifiedScript[pos] = ' ';
pos++;
// Is it an #if or #endif directive?
engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
string token;
token.assign(&modifiedScript[pos], len);
OverwriteCode(pos, len);
if( token == "if" )
{
nested++;
}
else if( token == "endif" )
{
if( nested-- == 0 )
{
pos += len;
break;
}
}
}
else if( modifiedScript[pos] != '\n' )
{
OverwriteCode(pos, len);
}
pos += len;
}
return pos;
}
// Overwrite all characters except line breaks with blanks
void CScriptBuilder::OverwriteCode(int start, int len)
{
char *code = &modifiedScript[start];
for( int n = 0; n < len; n++ )
{
if( *code != '\n' )
*code = ' ';
code++;
}
}
#if AS_PROCESS_METADATA == 1
int CScriptBuilder::ExtractMetadataString(int pos, string &metadata)
{
metadata = "";
// Overwrite the metadata with space characters to allow compilation
modifiedScript[pos] = ' ';
// Skip opening brackets
pos += 1;
int level = 1;
asUINT len = 0;
while( level > 0 && pos < (int)modifiedScript.size() )
{
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_KEYWORD )
{
if( modifiedScript[pos] == '[' )
level++;
else if( modifiedScript[pos] == ']' )
level--;
}
// Copy the metadata to our buffer
if( level > 0 )
metadata.append(&modifiedScript[pos], len);
// Overwrite the metadata with space characters to allow compilation
if( t != asTC_WHITESPACE )
OverwriteCode(pos, len);
pos += len;
}
return pos;
}
int CScriptBuilder::ExtractDeclaration(int pos, string &name, string &declaration, int &type)
{
declaration = "";
type = 0;
int start = pos;
std::string token;
asUINT len = 0;
asETokenClass t = asTC_WHITESPACE;
// Skip white spaces, comments, and leading 'shared', 'external', 'final', 'abstract'
do
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
token.assign(&modifiedScript[pos], len);
} while ( t == asTC_WHITESPACE || t == asTC_COMMENT || token == "shared" || token == "external" || token == "final" || token == "abstract" );
// We're expecting, either a class, interface, function, or variable declaration
if( t == asTC_KEYWORD || t == asTC_IDENTIFIER )
{
token.assign(&modifiedScript[pos], len);
if( token == "interface" || token == "class" || token == "enum" )
{
// Skip white spaces and comments
do
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
} while ( t == asTC_WHITESPACE || t == asTC_COMMENT );
if( t == asTC_IDENTIFIER )
{
type = MDT_TYPE;
declaration.assign(&modifiedScript[pos], len);
pos += len;
return pos;
}
}
else
{
// For function declarations, store everything up to the start of the statement block
// For variable declaration store just the name as there can only be one
// We'll only know if the declaration is a variable or function declaration when we see the statement block, or absense of a statement block.
bool hasParenthesis = false;
declaration.append(&modifiedScript[pos], len);
pos += len;
for(; pos < (int)modifiedScript.size();)
{
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_KEYWORD )
{
token.assign(&modifiedScript[pos], len);
if( token == "{" )
{
if( hasParenthesis )
{
// We've found the end of a function signature
type = MDT_FUNC;
}
else
{
// We've found a virtual property. Just keep the name
declaration = name;
type = MDT_VIRTPROP;
}
return pos;
}
if( (token == "=" && !hasParenthesis) || token == ";" )
{
if (hasParenthesis)
{
// The declaration is ambigous. It can be a variable with initialization, or a function prototype
type = MDT_FUNC_OR_VAR;
}
else
{
// Substitute the declaration with just the name
declaration = name;
type = MDT_VAR;
}
return pos;
}
else if( token == "(" )
{
// This is the first parenthesis we encounter. If the parenthesis isn't followed
// by a statement block, then this is a variable declaration, in which case we
// should only store the type and name of the variable, not the initialization parameters.
hasParenthesis = true;
}
}
else if( t == asTC_IDENTIFIER )
{
name.assign(&modifiedScript[pos], len);
}
declaration.append(&modifiedScript[pos], len);
pos += len;
}
}
}
return start;
}
const char *CScriptBuilder::GetMetadataStringForType(int typeId)
{
map<int,string>::iterator it = typeMetadataMap.find(typeId);
if( it != typeMetadataMap.end() )
return it->second.c_str();
return "";
}
const char *CScriptBuilder::GetMetadataStringForFunc(asIScriptFunction *func)
{
if( func )
{
map<int,string>::iterator it = funcMetadataMap.find(func->GetId());
if( it != funcMetadataMap.end() )
return it->second.c_str();
}
return "";
}
const char *CScriptBuilder::GetMetadataStringForVar(int varIdx)
{
map<int,string>::iterator it = varMetadataMap.find(varIdx);
if( it != varMetadataMap.end() )
return it->second.c_str();
return "";
}
const char *CScriptBuilder::GetMetadataStringForTypeProperty(int typeId, int varIdx)
{
map<int, SClassMetadata>::iterator typeIt = classMetadataMap.find(typeId);
if(typeIt == classMetadataMap.end()) return "";
map<int, string>::iterator propIt = typeIt->second.varMetadataMap.find(varIdx);
if(propIt == typeIt->second.varMetadataMap.end()) return "";
return propIt->second.c_str();
}
const char *CScriptBuilder::GetMetadataStringForTypeMethod(int typeId, asIScriptFunction *method)
{
if( method )
{
map<int, SClassMetadata>::iterator typeIt = classMetadataMap.find(typeId);
if(typeIt == classMetadataMap.end()) return "";
map<int, string>::iterator methodIt = typeIt->second.funcMetadataMap.find(method->GetId());
if(methodIt == typeIt->second.funcMetadataMap.end()) return "";
return methodIt->second.c_str();
}
return "";
}
#endif
string GetAbsolutePath(const string &file)
{
string str = file;
// If this is a relative path, complement it with the current path
if( !((str.length() > 0 && (str[0] == '/' || str[0] == '\\')) ||
str.find(":") != string::npos) )
{
str = GetCurrentDir() + "/" + str;
}
// Replace backslashes for forward slashes
size_t pos = 0;
while( (pos = str.find("\\", pos)) != string::npos )
str[pos] = '/';
// Replace /./ with /
pos = 0;
while( (pos = str.find("/./", pos)) != string::npos )
str.erase(pos+1, 2);
// For each /../ remove the parent dir and the /../
pos = 0;
while( (pos = str.find("/../")) != string::npos )
{
size_t pos2 = str.rfind("/", pos-1);
if( pos2 != string::npos )
str.erase(pos2, pos+3-pos2);
else
{
// The path is invalid
break;
}
}
return str;
}
string GetCurrentDir()
{
char buffer[1024];
#if defined(_MSC_VER) || defined(_WIN32)
#ifdef _WIN32_WCE
static TCHAR apppath[MAX_PATH] = TEXT("");
if (!apppath[0])
{
GetModuleFileName(NULL, apppath, MAX_PATH);
int appLen = _tcslen(apppath);
// Look for the last backslash in the path, which would be the end
// of the path itself and the start of the filename. We only want
// the path part of the exe's full-path filename
// Safety is that we make sure not to walk off the front of the
// array (in case the path is nothing more than a filename)
while (appLen > 1)
{
if (apppath[appLen-1] == TEXT('\\'))
break;
appLen--;
}
// Terminate the string after the trailing backslash
apppath[appLen] = TEXT('\0');
}
#ifdef _UNICODE
wcstombs(buffer, apppath, min(1024, wcslen(apppath)*sizeof(wchar_t)));
#else
memcpy(buffer, apppath, min(1024, strlen(apppath)));
#endif
return buffer;
#elif defined(__S3E__)
// Marmalade uses its own portable C library
return getcwd(buffer, (int)1024);
#elif _XBOX_VER >= 200
// XBox 360 doesn't support the getcwd function, just use the root folder
return "game:/";
#elif defined(_M_ARM)
// TODO: How to determine current working dir on Windows Phone?
return "";
#else
return _getcwd(buffer, (int)1024);
#endif // _MSC_VER
#elif defined(__APPLE__) || defined(__linux__)
return getcwd(buffer, 1024);
#else
return "";
#endif
}
END_AS_NAMESPACE
|