compiler/ecc: Added generated macro in proper place for GNUC to fix __declspec errors...
[sdk] / compiler / ecc / ecc.ec
1 #ifdef ECERE_STATIC
2 import static "ecere"
3 import static "ec"
4 #else
5 import "ecere"
6 import "ec"
7 #endif
8
9 #include <stdarg.h>
10
11 static Context globalContext { };
12 static Module privateModule;
13 static ModuleImport mainModule;
14 static OldList _excludedSymbols { offset = (uint)&((Symbol)0).left }; 
15 static OldList defines, imports;
16 static NameSpace globalData
17 {
18    classes.CompareKey = (void *)BinaryTree::CompareString;
19    defines.CompareKey = (void *)BinaryTree::CompareString;
20    functions.CompareKey = (void *)BinaryTree::CompareString;
21    nameSpaces.CompareKey = (void *)BinaryTree::CompareString;
22 };
23 static OldList _precompDefines;
24
25 static void OutputImports(char * fileName)
26 {
27    File f = FileOpen(fileName, write);
28    if(f)
29    {
30       if(imports.first)
31       {
32          ModuleImport module;
33          f.Printf("[Imported Modules]\n");
34          for(module = imports.first; module; module = module.next)
35          {
36             ClassImport _class;
37             FunctionImport function;
38
39             if(module.name)
40                f.Printf("   %s\n", module.name);
41             else
42                f.Printf("   [This]\n");
43             if(module.importType == staticImport)
44                f.Printf("      [Static]\n");
45             else if(module.importType == remoteImport)
46                f.Printf("      [Remote]\n");
47
48             if(module.importAccess == privateAccess)
49                f.Printf("      [Private]\n");
50             else
51                f.Printf("      [Public]\n");
52
53             if(module.classes.first)
54             {
55                f.Printf("      [Imported Classes]\n");
56                for(_class = module.classes.first; _class; _class = _class.next)
57                {
58                   f.Printf("         %s\n", _class.name);
59                   if(_class.itself)
60                   {
61                      f.Printf("            [Instantiated]\n");
62                   }
63                   if(_class.isRemote)
64                   {
65                      f.Printf("            [Remote]\n");
66                   }
67
68                   if(_class.methods.first)
69                   {
70                      MethodImport method;
71                      f.Printf("            [Imported Methods]\n");
72                      for(method = _class.methods.first; method; method = method.next)
73                      {
74                         f.Printf("               %s\n", method.name);
75                         if(method.isVirtual)
76                            f.Printf("                  [Virtual]\n");
77
78                      }
79                      f.Printf("               .\n");
80                   }
81
82                   if(_class.properties.first)
83                   {
84                      PropertyImport prop;
85                      f.Printf("            [Imported Properties]\n");
86                      for(prop = _class.properties.first; prop; prop = prop.next)
87                      {
88                         f.Printf("               %s\n", prop.name);
89                         if(prop.isVirtual)
90                            f.Printf("                  [Virtual]\n");
91                         if(prop.hasSet)
92                            f.Printf("                  [Set]\n");
93                         if(prop.hasGet)
94                            f.Printf("                  [Get]\n");
95                      }
96                      f.Printf("               .\n");
97                   }
98                }
99                f.Printf("        .\n");
100             }
101             if(module.functions.first)
102             {
103                f.Printf("      [Imported Functions]\n");
104                for(function = module.functions.first; function; function = function.next)
105                {
106                   f.Printf("         %s\n", function.name);
107                }
108                f.Printf("        .\n");
109             }
110          }
111          f.Printf("   .\n");
112       }
113    }
114    delete f;
115 }
116
117 class CompilerApp : Application
118 {
119    void Main()
120    {
121       char * cppCommand = null;
122       char * cppOptions = null;
123       int cppOptionsLen = 0;
124       /*char ** argv = null;
125       int argc = 0;*/
126       int c;
127       bool valid = true;
128       char defaultOutputFile[MAX_LOCATION];
129
130       Platform targetPlatform = GetRuntimePlatform();
131       int targetBits = GetHostBits();
132
133       SetSymbolsDir("");
134
135       /*for(c = 0; c<this.argc; c++)
136       {
137          char * arg = this.argv[c];
138          int argLen = strlen(arg);
139
140          argv = renew argv char *[argc + 1];
141          argv[argc] = new char[argLen+1];
142          strcpy(argv[argc], arg);
143
144          while(argv[argc][argLen-1] == '\\' && c < this.argc-1)
145          {
146             int len;
147
148             c++;
149             arg = this.argv[c];
150             len = strlen(arg);
151             argv[argc] = renew argv[argc] char[argLen + len + 1];
152
153             argv[argc][argLen-1] = ' ';
154             strcpy(argv[argc] + argLen, arg);
155             argLen += len;
156          }
157          argc++;
158       }*/
159
160       for(c = 1; c<argc; c++)
161       {
162          char * arg = argv[c];
163          if(arg[0] == '-')
164          {
165             if(!strcmp(arg + 1, "m32") || !strcmp(arg + 1, "m64"))
166             {
167                int argLen = strlen(arg);
168                int newLen = cppOptionsLen + 1 + argLen;
169                cppOptions = renew cppOptions char[newLen + 1];
170                cppOptions[cppOptionsLen] = ' ';
171                strcpy(cppOptions + cppOptionsLen + 1, arg);
172                cppOptionsLen = newLen;
173                targetBits = !strcmp(arg + 1, "m32") ? 32 : 64;
174             }
175             else if(arg[1] == 'D')
176             {
177                int argLen = strlen(arg);
178                int newLen = cppOptionsLen + 1 + argLen;
179                cppOptions = renew cppOptions char[newLen + 1];
180                cppOptions[cppOptionsLen] = ' ';
181                strcpy(cppOptions + cppOptionsLen + 1, arg); 
182                cppOptionsLen = newLen;
183                if(!strcmp(arg, "-DBUILDING_ECERE_COM"))
184                   SetBuildingEcereCom(true);
185                else if(!strcmp(arg, "-DECERE_COM_MODULE"))
186                   SetBuildingEcereComModule(true);
187             }
188             else if(arg[1] == 'I')
189             {
190                int argLen = strlen(arg);
191                int newLen = cppOptionsLen + argLen + 3;
192                cppOptions = renew cppOptions char[newLen + 1];
193                cppOptions[cppOptionsLen] = ' ';
194                cppOptions[cppOptionsLen+1] = '-';
195                cppOptions[cppOptionsLen+2] = 'I';
196                cppOptions[cppOptionsLen+3] = '"';
197                strcpy(cppOptions + cppOptionsLen + 4, arg+2); 
198                cppOptions[newLen-1] = '\"';
199                cppOptions[newLen] = '\0';
200                cppOptionsLen = newLen;
201             }
202             else if(!strcmp(arg+1, "t"))
203             {
204                if(++c < argc)
205                   targetPlatform = argv[c];
206                else
207                   valid = false;
208             }
209             else if(!strcmp(arg+1, "cpp"))
210             {
211                if(++c < argc)
212                   cppCommand = CopyString(argv[c]);
213                else
214                   valid = false;
215             }
216             else if(!strcmp(arg+1, "o"))
217             {
218                if(!GetOutputFile() && c + 1 < argc)
219                {
220                   SetOutputFile(argv[c+1]);
221                   c++;
222                }
223                else
224                   valid = false;
225             }
226             else if(!strcmp(arg+1, "c"))
227             {
228                if(!GetSourceFile() && c + 1 < argc)
229                {
230                   SetSourceFile(argv[c+1]);
231                   c++;
232                }
233                else
234                   valid = false;
235             }
236             else if(!strcmp(arg+1, "isystem") || !strcmp(arg+1, "isysroot"))
237             {
238                if(c + 1 < argc)
239                {
240                   int argLen = strlen(arg);
241                   int arg1Len = strlen(argv[c+1]);
242                   int newLen = cppOptionsLen + argLen + arg1Len + 4;
243                   cppOptions = renew cppOptions char[newLen + 1];
244                   cppOptions[cppOptionsLen] = ' ';
245                   strcpy(cppOptions + cppOptionsLen + 1, arg); 
246                   cppOptions[cppOptionsLen+argLen+1] = ' ';
247                   cppOptions[cppOptionsLen+argLen+2] = '"';
248                   arg = argv[++c];
249                   strcpy(cppOptions + cppOptionsLen + argLen + 3, arg); 
250                   cppOptions[newLen-1] = '\"';
251                   cppOptions[newLen] = '\0';
252                   cppOptionsLen = newLen;
253                }
254                else
255                   valid = false;
256             }
257             else if(!strcmp(arg+1, "symbols"))
258             {
259                if(c + 1 < argc)
260                {
261                   SetSymbolsDir(argv[c+1]);
262                   c++;
263                }
264                else
265                   valid = false;
266             }
267             else if(!strcmp(arg+1, "memguard"))
268             {
269                SetMemoryGuard(true);
270             }
271             else if(!strcmp(arg+1, "defaultns"))
272             {
273                if(c + 1 < argc)
274                {
275                   SetDefaultNameSpace(argv[c+1]);
276                   //defaultNameSpaceLen = strlen(defaultNameSpace);
277                   c++;
278                }
279                else
280                   valid = false;
281             }
282             else if(!strcmp(arg+1, "strictns"))
283             {
284                SetStrictNameSpaces(true);
285             }
286             else if(!strcmp(arg+1, "nolinenumbers"))
287             {
288                SetOutputLineNumbers(false);
289             }
290          }
291          else
292             valid = false;
293       }
294       if(valid)
295       {
296          if(!cppCommand)
297             cppCommand = CopyString("gcc");
298          if(!GetSourceFile())
299             valid = false;
300          else if(!GetOutputFile())
301          {
302             strcpy(defaultOutputFile, "");
303             PathCat(defaultOutputFile, GetSourceFile());
304             ChangeExtension(defaultOutputFile, "c", defaultOutputFile);
305             SetOutputFile(defaultOutputFile);
306          }
307       }
308
309       if(!valid)
310          printf($"Syntax:\n   ecc [-t <target platform>] [-cpp <c preprocessor>] [-o <output>] [-symbols <outputdir>] [-I<includedir>]* [-isystem <sysincludedir>]* [-D<definition>]* -c <input>\n");
311       else
312       {
313          DualPipe cppOutput;
314          // TODO: Improve this
315          char command[MAX_F_STRING*3];
316          SetGlobalData(&globalData);
317          SetExcludedSymbols(&_excludedSymbols);
318          SetGlobalContext(globalContext);
319          SetCurrentContext(globalContext);
320          SetTopContext(globalContext);
321          SetDefines(&::defines);
322          SetImports(&imports);
323          SetInCompiler(true);
324          SetTargetPlatform(targetPlatform);
325          SetTargetBits(targetBits);
326          SetEchoOn(false);
327
328          privateModule = (Module)__ecere_COM_Initialize(true | ((targetBits == 64)?2:0), 1, null);
329          SetPrivateModule(privateModule);
330
331          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint"), type = ProcessTypeString("unsigned int", false) });
332          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint64"), type = ProcessTypeString("unsigned int64", false) });
333          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint32"), type = ProcessTypeString("unsigned int", false) });
334          globalContext.types.Add((BTNode)Symbol { string = CopyString("uint16"), type = ProcessTypeString("unsigned short", false) });
335          globalContext.types.Add((BTNode)Symbol { string = CopyString("byte"), type = ProcessTypeString("unsigned char", false) });
336
337          {
338             GlobalData data { fullName = CopyString("__thisModule"), dataTypeString = CopyString("Module"), module = privateModule };
339             data.key = (uintptr)data.fullName;
340             globalData.functions.Add((BTNode)data);
341          }
342
343          snprintf(command, sizeof(command), "%s%s -x c -E \"%s\"", cppCommand, cppOptions ? cppOptions : "", GetSourceFile());
344          command[sizeof(command)-1] = 0;
345          if((cppOutput = DualPipeOpen({ output = true }, command)))
346          {
347             char impFile[MAX_LOCATION];
348             ImportedModule module;
349             char mainModuleName[MAX_FILENAME];
350             int exitCode;
351             OldList * ast;
352
353             TempFile fileInput { };
354             SetFileInput(fileInput);
355
356             imports.Add((mainModule = ModuleImport { }));
357             SetMainModule(mainModule);
358
359             GetLastDirectory(GetSourceFile(), mainModuleName);
360
361 #if 0
362             // TEMP: UNTIL WE CAN HAVE PER SOURCE FILE PREPROCESSOR DEFINITIONS...
363             if(GetBuildingEcereCom() && 
364                !(strcmpi(mainModuleName, "instance.ec") && strcmpi(mainModuleName, "BinaryTree.ec") &&
365                strcmpi(mainModuleName, "dataTypes.ec") && strcmpi(mainModuleName, "OldList.ec") &&
366                strcmpi(mainModuleName, "String.ec") && strcmpi(mainModuleName, "BTNode.ec") &&
367                strcmpi(mainModuleName, "Array.ec") && strcmpi(mainModuleName, "AVLTree.ec") &&
368                strcmpi(mainModuleName, "BuiltInContainer.ec") && strcmpi(mainModuleName, "Container.ec") &&
369                strcmpi(mainModuleName, "CustomAVLTree.ec") && strcmpi(mainModuleName, "LinkList.ec") &&
370                strcmpi(mainModuleName, "List.ec") && strcmpi(mainModuleName, "Map.ec") &&
371                strcmpi(mainModuleName, "Mutex.ec")))
372                SetBuildingEcereComModule(true);
373             if(GetBuildingEcereCom() && 
374                !(strcmpi(mainModuleName, "instance.ec") && strcmpi(mainModuleName, "BinaryTree.ec") &&
375                /*strcmpi(mainModuleName, "dataTypes.ec") && strcmpi(mainModuleName, "OldList.ec") &&*/
376                /*strcmpi(mainModuleName, "String.ec") && */strcmpi(mainModuleName, "BTNode.ec") &&
377                strcmpi(mainModuleName, "Mutex.ec") && strcmpi(mainModuleName, "Thread.ec")))
378             //if(GetBuildingEcereCom() && !strcmpi(mainModuleName, "instance.ec"))
379                SetMemoryGuard(false);
380 #endif            
381
382             StripExtension(mainModuleName);
383             module = ImportedModule { name = CopyString(mainModuleName), type = moduleDefinition };
384             ::defines.AddName(module);
385
386             resetScanner();
387             while(!cppOutput.Eof())
388             {
389                char junk[4096];
390                int count = cppOutput.Read(junk, 1, 4096);
391                fileInput.Write(junk, 1, count);
392             }
393             exitCode = cppOutput.GetExitCode();
394             delete cppOutput;
395
396             fileInput.Seek(0, start);
397
398    #ifdef _DEBUG
399             // SetYydebug(true);
400    #endif
401
402             // Predeclare all classes
403             {
404                char symFile[MAX_FILENAME];
405                char symLocation[MAX_LOCATION];
406                ImportedModule module, next;
407
408                GetLastDirectory(GetSourceFile(), symFile);
409                ChangeExtension(symFile, "sym", symFile);
410
411                strcpy(symLocation, GetSymbolsDir());
412                PathCat(symLocation, symFile);
413                
414                // LoadSymbols(symLocation, normalImport, true);
415                LoadSymbols(symLocation, preDeclImport, false);
416                
417                for(module = ::defines.first; module; module = next)
418                {
419                   next = module.next;
420                   if(module.type == moduleDefinition && strcmpi(module.name, mainModuleName))
421                   {
422                      delete module.name;
423                      ::defines.Delete(module);
424                   }
425                }
426
427                if(!GetEcereImported() && !GetBuildingEcereCom())
428                   eModule_LoadStrict(privateModule, "ecereCOM", publicAccess /*privateAccess*/);
429             }
430
431             ParseEc();
432
433             CheckDataRedefinitions();
434
435             SetYydebug(false);
436             SetCurrentNameSpace(null);
437             SetDefaultNameSpace(null);
438             SetDeclMode(privateAccess);
439
440             delete fileInput;
441             SetFileInput(null);
442
443             ast = GetAST();
444
445             if(/*ast /*&& !parseError*/ /*&& */!exitCode)
446             {
447                ProcessDBTableDefinitions();
448
449                // *** PASS 0 - Register all classes, methods, properties and members ***
450                // ***          Build the constructors, destructors, properties as    ***
451                // ***          class functions                                       ***
452                PrePreProcessClassDefinitions();
453                ComputeModuleClasses(privateModule);
454                PreProcessClassDefinitions();
455
456                // For classes defined in this module...
457                ComputeModuleClasses(privateModule);
458
459                
460                // *** PASS 1 - Turn the class functions into functions               ***
461                // *** Write the RegisterModule (Register classes)                    ***
462                ProcessClassDefinitions();
463
464                // *** PASS 1.5 - Replace members by this.member, figure out types, do type checking / conversions
465                ComputeDataTypes();
466
467                // *** PASS 1.6 - Replace instantiations
468                ProcessInstantiations();
469
470                // *** PASS 2 - Replace Member Access ***
471                ProcessMemberAccess();
472
473                // *** PASS 3 - Replace pointers to objects by "Instance *" ***
474                ProcessInstanceDeclarations();
475
476                strcpy(impFile, GetSymbolsDir());
477                {
478                   char fileName[MAX_FILENAME];
479                   GetLastDirectory(GetSourceFile(), fileName);
480                   PathCat(impFile, fileName);
481                   ChangeExtension(impFile, "imp", impFile);
482                }
483                if(imports.first)
484                   OutputImports(impFile);
485                // For now use precomp to generate sym file only...
486
487                if(/*!strcmp(targetExt, "c") && */!this.exitCode)
488                {
489                   File output = FileOpen(GetOutputFile(), write);
490                   if(output)
491                   {
492                      output.Printf("#if defined(__GNUC__)\n");
493                         output.Printf("typedef long long int64;\n");
494                         output.Printf("typedef unsigned long long uint64;\n");
495                         output.Printf("#ifndef _WIN32\n");
496                            output.Printf("#define __declspec(x)\n");
497                         output.Printf("#endif\n");
498                      output.Printf("#elif defined(__TINYC__)\n");
499                         output.Printf("#include <stdarg.h>\n");
500                         output.Printf("#define __builtin_va_list va_list\n");
501                         output.Printf("#define __builtin_va_start va_start\n");
502                         output.Printf("#define __builtin_va_end va_end\n");
503                         output.Printf("#ifdef _WIN32\n");
504                            output.Printf("#define strcasecmp stricmp\n");
505                            output.Printf("#define strncasecmp strnicmp\n");
506                            output.Printf("#define __declspec(x) __attribute__((x))\n");
507                         output.Printf("#else\n");
508                            output.Printf("#define __declspec(x)\n");
509                         output.Printf("#endif\n");
510                         output.Printf("typedef long long int64;\n");
511                         output.Printf("typedef unsigned long long uint64;\n");
512                      output.Printf("#else\n");
513                         output.Printf("typedef __int64 int64;\n");
514                         output.Printf("typedef unsigned __int64 uint64;\n");
515                      output.Printf("#endif\n");
516                      output.Printf("#ifdef __BIG_ENDIAN__\n");
517                         output.Printf("#define __ENDIAN_PAD(x) (8 - (x))\n");
518                      output.Printf("#else\n");
519                         output.Printf("#define __ENDIAN_PAD(x) 0\n");
520                      output.Printf("#endif\n");
521                      output.Printf("#ifdef __MINGW32__\n");
522                      output.Printf("#ifdef _WIN64\n");
523                      output.Printf("typedef unsigned long long int uintptr_t;\n");
524                      output.Printf("typedef long long int intptr_t;\n");
525                      output.Printf("#else\n");
526                      output.Printf("typedef unsigned int uintptr_t;\n");
527                      output.Printf("typedef int intptr_t;\n");
528                      output.Printf("#endif\n");
529                      output.Printf("#else\n");
530                      output.Printf("#include <stdint.h>\n");
531                      output.Printf("#endif\n");
532
533                      // NOTE: If anything is changed up there, the start outputLine must be updated in libec's output.c or Debugging lines will be wrong
534
535                      if(ast)
536                         OutputTree(ast, output);
537                      delete output;
538                   }
539                }
540                /*
541                else if(!strcmp(targetExt, "o"))
542                {
543                   // Compile right away
544                   File output = FileOpen(GetOutputFile(), Write);
545                   output.Printf("#include <ecereCOM.h>\n\n");
546                   OutputTree(ast, output);
547                   delete output;
548                }*/
549             }
550             else
551                this.exitCode = exitCode;
552
553             if(ast)
554             {
555                FreeASTTree(ast);
556             }
557          }
558
559          FreeContext(globalContext);
560          FreeExcludedSymbols(_excludedSymbols);
561
562          ::defines.Free(FreeModuleDefine);
563          imports.Free(FreeModuleImport);
564
565          FreeTypeData(privateModule);
566          FreeIncludeFiles();
567          FreeGlobalData(globalData);
568
569          delete privateModule;
570       }
571
572       delete cppCommand;
573       delete cppOptions;
574
575       /*for(c = 0; c<argc; c++)
576          delete argv[c];
577       delete argv;
578       */
579       SetSymbolsDir(null); // Free symbols dir
580
581       OutputIntlStrings();
582
583 #if defined(_DEBUG) && defined(__WIN32__)
584       if(exitCode || GetNumWarnings())
585          getch();
586 #endif
587    }
588 }