ide: support compiler config environment variables in project node paths.
[sdk] / ide / src / project / ProjectNode.ec
1 #ifndef MAKEFILE_GENERATOR
2 import "ide"
3 #else
4 #ifdef ECERE_STATIC
5 import static "ecere"
6 #else
7 import "ecere"
8 #endif
9
10 import "Project"
11
12 static define app = ((GuiApplication)__thisModule);
13 #endif // #ifndef MAKEFILE_GENERATOR
14
15 #define OPTION(x) ((uint)(uintptr)(&((ProjectOptions)0).x))
16
17 static void OutputLog(const char * string)
18 {
19 #ifdef MAKEFILE_GENERATOR
20    printf("%s", string);
21 #else
22    ide.outputView.buildBox.Log(string);
23 #endif // #ifdef MAKEFILE_GENERATOR
24 }
25
26 bool eString_PathInsideOfMore(const char * path, const char * of, char * pathRest)
27 {
28    if(!path[0] || !of[0])
29       return false;  // What to do here? Ever used?
30    else
31    {
32       char ofPart[MAX_FILENAME], ofRest[MAX_LOCATION];
33       char pathPart[MAX_FILENAME]; //, pathRest[MAX_LOCATION];
34       strcpy(ofRest, of);
35       strcpy(pathRest, path);
36       for(; ofRest[0] && pathRest[0];)
37       {
38          SplitDirectory(ofRest, ofPart, ofRest);
39          SplitDirectory(pathRest, pathPart, pathRest);
40          if(fstrcmp(pathPart, ofPart))
41             return false;
42       }
43       if(!ofRest[0] && !pathRest[0])
44          return false;
45       else if(!pathRest[0])           // not inside of, it's the other way around
46          return false;
47       return true;
48    }
49 }
50
51 enum NodeTypes { project, file, folder, resources, folderOpen };
52 enum NodeIcons
53 {
54    genFile, ewsFile, epjFile, folder, openFolder, ecFile, ehFile,
55    sFile, cFile, hFile, cppFile, hppFile, textFile, webFile, pictureFile, soundFile,
56    archiveFile, packageFile, opticalMediaImageFile, mFile, mmFile;
57
58    NodeIcons ::SelectFileIcon(const char * filePath)
59    {
60       NodeIcons icon;
61       if(filePath && filePath[0])
62       {
63          char extension[MAX_EXTENSION];
64          GetExtension(filePath, extension);
65          if(strlen(extension))
66          {
67             if(!strcmpi(extension, WorkspaceExtension))
68                icon = ewsFile;
69             else if(!strcmpi(extension, ProjectExtension))
70                icon = epjFile;
71             else if(!strcmpi(extension, "ec"))
72                icon = ecFile;
73             else if(!strcmpi(extension, "eh"))
74                icon = ehFile;
75             else if(!strcmpi(extension, "cpp") || !strcmpi(extension, "cc") ||
76                   !strcmpi(extension, "cxx"))
77                icon = cppFile;
78             else if(!strcmpi(extension, "hpp") || !strcmpi(extension, "hh") ||
79                   !strcmpi(extension, "hxx"))
80                icon = hppFile;
81             else if(!strcmpi(extension, "s"))
82                icon = sFile;
83             else if(!strcmpi(extension, "c"))
84                icon = cFile;
85             else if(!strcmpi(extension, "h"))
86                icon = hFile;
87             else if(!strcmpi(extension, "m"))
88                icon = mFile;
89             else if(!strcmpi(extension, "mm"))
90                icon = mmFile;
91             else if(!strcmpi(extension, "txt") || !strcmpi(extension, "text") ||
92                   !strcmpi(extension, "nfo") || !strcmpi(extension, "info"))
93                icon = textFile;
94             else if(!strcmpi(extension, "htm") || !strcmpi(extension, "html") ||
95                   !strcmpi(extension, "css") || !strcmpi(extension, "php") ||
96                   !strcmpi(extension, "js"))
97                icon = webFile;
98             else if(!strcmpi(extension, "bmp") || !strcmpi(extension, "pcx") ||
99                   !strcmpi(extension, "jpg") || !strcmpi(extension, "jpeg") ||
100                   !strcmpi(extension, "gif") || !strcmpi(extension, "png") ||
101                   !strcmpi(extension, "ico"))
102                icon = pictureFile;
103             else if(!strcmpi(extension, "wav") || !strcmpi(extension, "mp3") ||
104                   !strcmpi(extension, "ogg") || !strcmpi(extension, "snd"))
105                icon = soundFile;
106             else if(!strcmpi(extension, "ear") || !strcmpi(extension, "7z") ||
107                   !strcmpi(extension, "rar") || !strcmpi(extension, "zip") ||
108                   !strcmpi(extension, "gz") || !strcmpi(extension, "bz2") ||
109                   !strcmpi(extension, "tar") || !strcmpi(extension, "arj") ||
110                   !strcmpi(extension, "lza") || !strcmpi(extension, "lzh") ||
111                   !strcmpi(extension, "cpio") || !strcmpi(extension, "z"))
112                icon = archiveFile;
113             else if(!strcmpi(extension, "cab") || !strcmpi(extension, "deb") ||
114                   !strcmpi(extension, "rpm"))
115                icon = packageFile;
116             else if(!strcmpi(extension, "iso") || !strcmpi(extension, "mds") ||
117                   !strcmpi(extension, "cue") || !strcmpi(extension, "bin") ||
118                   !strcmpi(extension, "ccd") || !strcmpi(extension, "bwt") ||
119                   !strcmpi(extension, "cdi") || !strcmpi(extension, "nrg"))
120                icon = opticalMediaImageFile;
121             else
122                icon = genFile;
123          }
124          else
125             icon = genFile;
126       }
127       else
128          icon = genFile; // tocheck: error icon?
129       return icon;
130    }
131
132    NodeIcons ::SelectNodeIcon(NodeTypes type)
133    {
134       switch(type)
135       {
136          case project:
137             return epjFile;
138          case file:
139             return genFile;
140          case folder:
141             return folder;
142          case resources:
143             return archiveFile;
144          case folderOpen:
145             return openFolder;
146       }
147       return genFile;
148    }
149 };
150
151 #define SELECTION_COLOR Color { 10, 36, 106 }
152
153 // On Windows & UNIX
154 #define SEPS    "/"
155 #define SEP     '/'
156
157 // this is so not working, why!
158 //struct TwoStrings
159 // return result was not even executed (did not step on while debugging)
160 class TwoStrings : struct
161 {
162    char * a;
163    char * b;
164
165    property bool
166    {
167       get
168       {
169          return a && a[0];
170       }
171    }
172
173    ~TwoStrings()
174    {
175       delete a;
176       delete b;
177    }
178 }
179
180 class DotMain : bool
181 {
182    //property char * { set { } }
183    DotMain ::FromFileName(const char * fileName)
184    {
185       DotMain dotMain = false;
186       if(fileName && fileName[0])
187       {
188          char ext[MAX_EXTENSION];
189          GetExtension(fileName, ext);
190          if(!strcmp(ext, "c") || !strcmp(ext, "ec"))
191          {
192             char stripExt[MAX_LOCATION];
193             strcpy(stripExt, fileName);
194             StripExtension(stripExt);
195             GetExtension(stripExt, ext);
196             if(!strcmp(ext, "main"))
197                dotMain = true;
198          }
199       }
200       return dotMain;
201    }
202 }
203
204 enum IntermediateFileType
205 {
206    none, ec, c, sym, imp, bowl, o;
207
208    //property char * { set { } }
209    IntermediateFileType ::FromExtension(char * extension)
210    {
211       IntermediateFileType type = none;
212       if(extension && extension[0])
213       {
214          if(!fstrcmp(extension, "ec"))
215             type = ec;
216          else if(!fstrcmp(extension, "c"))
217             type = c;
218          else if(!fstrcmp(extension, "sym"))
219             type = sym;
220          else if(!fstrcmp(extension, "imp"))
221             type = imp;
222          else if(!fstrcmp(extension, "bowl"))
223             type = bowl;
224          else if(!fstrcmp(extension, "o"))
225             type = o;
226       }
227       return type;
228    }
229 };
230
231 class ProjectNode : ListItem
232 {
233 public:
234    property String
235    {
236       set { return { fileName = value }; }
237       // TOCHECK: Is this isset necessary at all?
238       isset { return nodeType == file && !options && !configurations && !platforms && !files; }
239    };
240    property String folder
241    {
242       set
243       {
244          nodeType = folder;
245          if(strchr(value, '/'))
246          {
247             char p[MAX_LOCATION];
248             char n[MAX_FILENAME];
249             GetLastDirectory(value, n);
250             StripLastDirectory(value, p);
251             name = CopyString(n);
252             path = CopyString(p);
253          }
254          else
255             name = CopyString(value);
256       }
257       get
258       {
259          // TOCHECK: Non Reentrant
260          static char insidePath[MAX_LOCATION];
261
262          strcpy(insidePath, (parent.type == project) ? "" : parent.path);
263          PathCatSlash(insidePath, name);
264
265          if(!fstrcmp(path, insidePath))
266             return name;
267          else
268          {
269             strcpy(insidePath, path);
270             if(!insidePath[0]) strcpy(insidePath, ".");
271             PathCatSlash(insidePath, name);
272             return insidePath;
273          }
274       }
275       isset { return nodeType == folder; }
276    };
277    property const String fileName
278    {
279       set
280       {
281          nodeType = file;
282          if(strchr(value, '/'))
283          {
284             char p[MAX_LOCATION];
285             char n[MAX_FILENAME];
286             GetLastDirectory(value, n);
287             StripLastDirectory(value, p);
288             name = CopyValidateMakefilePath(n);
289             path = CopyValidateMakefilePath(p);
290          }
291          else
292             name = CopyValidateMakefilePath(value);
293       }
294       get
295       {
296          // TOCHECK: Non Reentrant
297          static char insidePath[MAX_LOCATION];
298
299          strcpy(insidePath, (parent.type == project) ? "" : parent.path);
300          if(!fstrcmp(path, insidePath))
301             return name;
302          else
303          {
304             strcpy(insidePath, path);
305             if(!insidePath[0]) strcpy(insidePath, ".");
306             PathCatSlash(insidePath, name);
307             return insidePath;
308          }
309       }
310       isset { return nodeType == file && (options || configurations || platforms); }
311    };
312
313    LinkList<ProjectNode> files;
314    property ProjectOptions options
315    {
316       get { return project ? project.options : options; }
317       set { if(project) { delete project.options; project.options = value; } else { delete options; options = value; } }
318       isset { ProjectOptions options = project ? project.options : this.options; return options && !options.isEmpty; }
319    }
320    property Array<PlatformOptions> platforms
321    {
322       get { return project ? project.platforms : platforms; }
323       set
324       {
325          if(project) { project.platforms = value; }
326          else
327          {
328             if(platforms) { platforms.Free(); delete platforms; }
329             if(value)
330             {
331                List<PlatformOptions> empty { };
332                Iterator<PlatformOptions> it { value };
333                platforms = value;
334                for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
335                for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
336                delete empty;
337             }
338          }
339       }
340       isset
341       {
342          Array<PlatformOptions> platforms = project ? project.platforms : this.platforms;
343          if(platforms)
344          {
345             for(p : platforms)
346             {
347                if(p.options && !p.options.isEmpty)
348                   return true;
349             }
350          }
351          return false;
352       }
353    }
354    property List<ProjectConfig> configurations
355    {
356       get { return project ? project.configurations : configurations; }
357       set
358       {
359          if(project)
360          {
361             if(project.configurations)
362             {
363                project.configurations.Free();
364                delete project.configurations;
365             }
366             project.configurations = value;
367          }
368          else
369          {
370             if(configurations) { configurations.Free(); delete configurations; }
371             if(value)
372             {
373                List<ProjectConfig> empty { };
374                Iterator<ProjectConfig> it { value };
375                configurations = value;
376                for(c : configurations)
377                {
378                   bool somethingSet = c.options && !c.options.isEmpty;
379                   // TODO: Implement isset keyword
380                   if(!somethingSet && c.platforms && c.platforms.count)
381                   {
382                      for(p : c.platforms)
383                      {
384                         if(p.options && !p.options.isEmpty)
385                         {
386                            somethingSet = true;
387                            break;
388                         }
389                      }
390                   }
391                   if(!somethingSet)
392                      empty.Add(c);
393                }
394                for(c : empty; it.Find(c)) configurations.Delete(it.pointer);
395                delete empty;
396             }
397          }
398       }
399       isset
400       {
401          if(!parent) return true;
402          if(configurations)
403          {
404             for(c : configurations)
405             {
406                bool somethingSet = c.options && !c.options.isEmpty;
407                if(!somethingSet && c.platforms && c.platforms.count)
408                {
409                   for(p : c.platforms)
410                   {
411                      if(p.options && !p.options.isEmpty)
412                      {
413                         somethingSet = true;
414                         break;
415                      }
416                   }
417                }
418                return somethingSet;
419             }
420          }
421          return false;
422       }
423    }
424
425 private:
426    ProjectOptions options;
427    Array<PlatformOptions> platforms;
428    List<ProjectConfig> configurations;
429    ProjectNodeType nodeType;
430    ProjectNode parent;
431    char * name;
432    char * info;
433
434    // This holds the absolute path of the .epj for the project topnode (without the filename)
435    // It holds a relative path to the topNode (project) for other nodes (folders and files)
436    // For folders, it includes the folder it refers to. If there is a name difference between the
437    // file system folder and the grouping folder of the project view, it maps to that folder.
438    char * path;
439
440    NodeTypes type;
441    NodeIcons icon;
442    int indent;
443    DataRow row;
444
445    bool modified;
446
447    // This is only set for Top Nodes
448    Project project;
449
450    void OpenRulesPlatformExclusionIfs(File f, int * ifCount, Array<Platform> platforms)
451    {
452       if(!platforms.Find(unknown))  // unknown is "Common"
453       {
454          // e.g. ifneq ($(or $(or $(OSX_TARGET),$(LINUX_TARGET)),$(WINDOWS_TARGET)),)
455          int i = 0;
456          f.Puts("ifneq (");
457          for(i = 0; platforms.count && i < platforms.count - 1; i++)
458             f.Puts("$(or ");
459          i = 0;
460          for(p : platforms)
461          {
462             if(i > 0)
463                f.Puts(",");
464             f.Puts("$(");
465             f.Puts(PlatformToMakefileTargetVariable(p));
466             f.Puts(")");
467             if(i > 0)
468                f.Puts(")");
469             i++;
470          }
471          f.Puts(",)\n");
472          (*ifCount)++;
473       }
474       else
475          *ifCount = 0;
476    }
477
478    ProjectConfig GetMatchingNodeConfig(ProjectConfig prjConfig)
479    {
480       ProjectConfig nodeConfig = null;
481       if(property::configurations && prjConfig)
482       {
483          const char * configName = prjConfig.name;
484          for(cfg : property::configurations)
485          {
486             if(!strcmpi(cfg.name, configName))
487             {
488                nodeConfig = cfg;
489                break;
490             }
491          }
492       }
493       return nodeConfig;
494    }
495
496    property ProjectNode root { get { ProjectNode n; for(n = this; n.parent; n = n.parent); return n; } }
497
498    property bool containsFile
499    {
500       get
501       {
502          bool result = false;
503          if(files)
504          {
505             for(child : files)
506             {
507                if(child.type == file ||
508                      ((child.type == folder || child.type == folderOpen) && child.containsFile))
509                {
510                   result = true;
511                   break;
512                }
513             }
514          }
515          else
516             result = false;
517          return result;
518       }
519    }
520
521    char * GetFullFilePath(char * buffer, bool resolveVars)
522    {
523       if(buffer)
524       {
525          strcpy(buffer, root.path);
526          if(resolveVars)
527          {
528             if(path && path[0])
529             {
530                DirExpression pathExp { };
531                Project project = property::project;
532                CompilerConfig compiler = GetCompilerConfig();
533                ProjectConfig config = project.config;
534                int bitDepth = GetBitDepth();
535                pathExp.Evaluate(path, project, compiler, config, bitDepth);
536                PathCatSlash(buffer, pathExp.dir);
537                delete compiler;
538                delete pathExp;
539             }
540             PathCatSlash(buffer, name);
541          }
542          else
543          {
544             PathCatSlash(buffer, path);
545             PathCatSlash(buffer, name);
546          }
547       }
548       return buffer;
549    }
550
551    char * GetObjectFileName(char * buffer, Map<String, NameCollisionInfo> namesInfo, IntermediateFileType type, bool dotMain, const char * objectFileExt)
552    {
553       if(buffer && (this.type == file || (this.type == project && dotMain == true)))
554       {
555          bool collision;
556          char extension[MAX_EXTENSION];
557          char moduleName[MAX_FILENAME];
558          const char * objFileExt = objectFileExt ? objectFileExt : objectDefaultFileExt;
559          NameCollisionInfo info;
560
561          GetExtension(name, extension);
562          ReplaceSpaces(moduleName, name);
563          StripExtension(moduleName);
564          info = namesInfo[moduleName];
565          collision = info ? info.IsExtensionColliding(extension) : false;
566
567          if(dotMain)
568          {
569             Project prj = property::project;
570             ReplaceSpaces(buffer, prj.moduleName);
571             StripExtension(buffer);
572             strcat(buffer, ".main.ec");
573          }
574          else
575             strcpy(buffer, name);
576          if(!strcmp(extension, "ec") || dotMain)
577          {
578             if(type == c)
579                ChangeExtension(buffer, "c", buffer);
580             else if(type == sym)
581                ChangeExtension(buffer, "sym", buffer);
582             else if(type == imp)
583                ChangeExtension(buffer, "imp", buffer);
584             else if(type == bowl)
585                ChangeExtension(buffer, "bowl", buffer);
586          }
587          if(type == o)
588          {
589             if(collision)
590             {
591                strcat(buffer, ".");
592                strcat(buffer, objFileExt);
593             }
594             else
595                ChangeExtension(buffer, objFileExt, buffer);
596          }
597       }
598       return buffer;
599    }
600
601    char * GetFileSysMatchingPath(char * buffer)
602    {
603       if(buffer)
604       {
605          ProjectNode n, root = this.root;
606          for(n = this; n && (n.type == folder || n.type == project); n = n.parent)
607          {
608             strcpy(buffer, root.path);
609             if(n != root)
610                PathCatSlash(buffer, n.path);
611             if(FileExists(buffer).isDirectory)
612                break;
613          }
614          if(!(n && (n.type == folder || n.type == project)))
615             buffer[0] = '\0';
616       }
617       return buffer;
618    }
619
620    void CollectPerFileAndDirOptions(ProjectConfig prjConfig, Array<String> perFilePreprocessorDefs, Array<DirPath> perFileIncludeDirs)
621    {
622       ProjectNode node = null;
623       ProjectConfig config = GetMatchingNodeConfig(prjConfig);
624       List<ProjectNode> nodeStack { };
625
626       for(node = this; node && node.parent; node = node.parent)
627          nodeStack.Add(node);
628
629       // Should we reverse this stack to give priority to the per-file includes? Does the following technique already reverse?
630
631       // TODO: Check how to fix duplication of following options when configuration is made per-config-per-file
632       while((node = nodeStack.lastIterator.data))
633       {
634          ProjectOptions nodeOptions = node.property::options;
635          if(nodeOptions && nodeOptions.preprocessorDefinitions)
636          {
637             for(def : nodeOptions.preprocessorDefinitions)
638                perFilePreprocessorDefs.Add(CopyString(def));
639          }
640          if(config && config.options && config.options.preprocessorDefinitions)
641          {
642             for(def : config.options.preprocessorDefinitions)
643                perFilePreprocessorDefs.Add(CopyString(def));
644          }
645          if(nodeOptions && nodeOptions.includeDirs)
646          {
647             for(dir : nodeOptions.includeDirs)
648                perFileIncludeDirs.Add(CopySystemPath(dir));
649          }
650          if(config && config.options && config.options.includeDirs)
651          {
652             for(dir : config.options.includeDirs)
653                perFileIncludeDirs.Add(CopySystemPath(dir));
654          }
655          nodeStack.lastIterator.Remove();
656       }
657       delete nodeStack;
658    }
659
660
661    property Project project
662    {
663       get
664       {
665          ProjectNode n = this;
666          while(n && n.type != project) n = n.parent;
667          return n ? (*&n.project) : null;
668       }
669    }
670
671    void RenameConfig(const char * oldName, const char * newName)
672    {
673       if(files)
674       {
675          for(f : files; (f.configurations || f.files)) { f.RenameConfig(oldName, newName); }
676       }
677       if(property::configurations)
678       {
679          for(c : property::configurations; !strcmp(c.name, oldName))
680          {
681             delete c.name;
682             c.name = CopyString(newName);
683          }
684       }
685    }
686
687    void DeleteConfig(ProjectConfig configToDelete)
688    {
689       if(files)
690       {
691          for(f : files; (f.configurations || f.files)) { f.DeleteConfig(configToDelete); }
692       }
693       if(property::configurations)
694       {
695          Iterator<ProjectConfig> c { property::configurations };
696          while(c.Next())
697          {
698             ProjectConfig config = c.data;
699             if(!strcmp(configToDelete.name, config.name))
700             {
701                c.Remove();
702                delete config;
703                break;
704             }
705          }
706          if(!property::configurations.count)
707             property::configurations = null;
708       }
709    }
710
711    ProjectNode Backup()
712    {
713       ProjectNode backupNode { };
714
715       if(files)
716       {
717          backupNode.files = { };
718          for(f : files) backupNode.files.Add(f.Backup());
719       }
720       if(property::options)
721          backupNode.options = property::options.Copy();
722
723       if(property::platforms)
724       {
725          backupNode.platforms = { };
726          for(p : property::platforms)
727             backupNode.platforms.Add(p.Copy());
728       }
729
730       if(property::configurations)
731       {
732          backupNode.configurations = { };
733          for(c : property::configurations)
734             backupNode.configurations.Add(c.Copy());
735       }
736       return backupNode;
737    }
738
739    void Revert(ProjectNode backupNode)
740    {
741       if(files)
742       {
743          Iterator<ProjectNode> it { backupNode.files };
744          for(f : files)
745          {
746             it.Next();
747             f.Revert(it.data);
748          }
749       }
750
751       property::options = backupNode.options ? backupNode.options.Copy() : null;
752       if(backupNode.platforms)
753       {
754          Array<PlatformOptions> platforms { };
755          property::platforms = platforms;
756
757          for(p : backupNode.platforms)
758             platforms.Add(p.Copy());
759       }
760       if(backupNode.configurations)
761       {
762          List<ProjectConfig> configurations { };
763          property::configurations = configurations;
764          for(c : backupNode.configurations)
765             configurations.Add(c.Copy());
766       }
767    }
768
769    void FixupNode(char * parentPath)
770    {
771       if(!parent)
772       {
773          type = project;
774       }
775       else if(nodeType == file)
776       {
777          type = file;
778          if(!path)
779          {
780             path = CopyString((parent.type == folder || parent.type == resources) ? parentPath : "");
781          }
782       }
783       else if(nodeType == folder)
784       {
785          type = folder;
786
787          if(!path)
788          {
789             char temp[MAX_LOCATION];
790             strcpy(temp, (parent.type == folder || parent.type == resources) ? parentPath : "");
791             PathCatSlash(temp, name);
792             path = CopyString(temp);
793          }
794       }
795
796       indent = parent ? parent.indent + 1 : 0;
797
798       if(type == file)
799          icon = NodeIcons::SelectFileIcon(name);
800       else
801          icon = NodeIcons::SelectNodeIcon(type);
802
803       if(files)
804       {
805          for(f : files)
806          {
807             f.parent = this;
808
809             if(type == project)
810                parentPath[0] = '\0';
811             else if(type == resources || type == folder)
812                strcpy(parentPath, path);
813
814             f.FixupNode(parentPath);
815          }
816       }
817    }
818
819    const char * OnGetString(char * tempString, void * fieldData, bool * needClass)
820    {
821       if(!needClass)
822       {
823          // TOCHECK: Called from JSON writer
824          if(nodeType == file && !property::options && !property::configurations && !property::platforms && name)
825          {
826             strcpy(tempString, "\"");
827             strcat(tempString, property::fileName);
828             strcat(tempString, "\"");
829             return tempString;
830          }
831          else
832             return null;
833       }
834       else
835          // TOCHECK: Called from ProjectView rendering
836          return name ? name : "";
837    }
838
839    ~ProjectNode()
840    {
841       if(files)
842       {
843          files.Free();
844          delete files;
845       }
846       if(!project)
847          delete options;
848
849       if(!project && platforms)
850       {
851          platforms.Free();
852          delete platforms;
853       };
854       if(!project && configurations)
855       {
856          configurations.Free();
857          delete configurations;
858       }
859
860       /////////////////////////////
861       delete path;
862       delete name;
863       delete info;
864    }
865
866    property bool isInResources
867    {
868       get
869       {
870          ProjectNode node;
871          for(node = this; node; node = node.parent)
872          {
873             if(node.type == resources)
874                return true;
875          }
876          return false;
877       }
878    }
879
880    TwoStrings GetPlatformSpecificFu(ProjectConfig prjConfig)
881    {
882       TwoStrings result { a = CopyString(""), b = CopyString("") };
883       // note: unknown platform is for common
884       Map<Platform, SetBool> exclusionInfo { };
885       MapNode<Platform, SetBool> mn;
886       char * exp;
887       const char * var;
888       int len;
889       SetBool common;
890
891       CollectExclusionInfo(exclusionInfo, prjConfig);
892       common = exclusionInfo[unknown];
893       {
894          Map<Platform, SetBool> cleaned { };
895          SetBool opposite = common == true ? false : true;
896          for(mn = exclusionInfo.root.minimum; mn; mn = mn.next)
897          {
898             if(mn.key == unknown || mn.value == opposite)
899               cleaned[mn.key] = mn.value;
900          }
901          delete exclusionInfo;
902          exclusionInfo = cleaned;
903       }
904
905       if(exclusionInfo.count > 1)
906       {
907          if(exclusionInfo.count > 2)
908          {
909             exp = result.a;
910             len = strlen(exp) + strlen("$(if $(or ");
911             exp = renew exp char[len+1];
912             strcat(exp, "$(if $(or ");
913             result.a = exp;
914
915             for(mn = exclusionInfo.root.minimum; mn; mn = mn.next)
916             {
917                if(mn.key != unknown)
918                {
919                   const char * comma = mn.next ? "," : "";
920
921                   var = PlatformToMakefileTargetVariable(mn.key);
922
923                   exp = result.a;
924                   len = strlen(exp) + strlen("$(") + strlen(var) + strlen(")") + strlen(comma);
925                   exp = renew exp char[len+1];
926                   strcat(exp, "$(");
927                   strcat(exp, var);
928                   strcat(exp, ")");
929                   strcat(exp, comma);
930                   result.a = exp;
931                }
932             }
933
934             exp = result.a;
935             len = strlen(exp) + strlen("),");
936             exp = renew exp char[len+1];
937          }
938          else
939          {
940             if(exclusionInfo.root.minimum.key != unknown)
941                var = PlatformToMakefileTargetVariable(exclusionInfo.root.minimum.key);
942             else
943                var = PlatformToMakefileTargetVariable(exclusionInfo.root.minimum.next.key);
944
945             exp = result.a;
946             len = strlen(exp) + strlen("$(if $(") + strlen(var) + strlen("),");
947             exp = renew exp char[len+1];
948             strcat(exp, "$(if $(");
949             strcat(exp, var);
950          }
951
952          strcat(exp, "),");
953          result.a = exp;
954
955          exp = common == true ? result.b : result.a;
956          len = strlen(exp) + strlen(",");
957          exp = renew exp char[len+1];
958          strcat(exp, ",");
959          if(common == true) result.b = exp; else result.a = exp;
960
961          exp = result.b;
962          len = strlen(exp) + strlen(")");
963          exp = renew exp char[len+1];
964          strcat(exp, ")");
965          result.b = exp;
966       }
967       delete exclusionInfo;
968
969       return result;
970    }
971
972    bool GetIsExcluded(ProjectConfig prjConfig)
973    {
974       bool result;
975       // note: unknown platform is for common
976       Map<Platform, SetBool> exclusionInfo { };
977       CollectExclusionInfo(exclusionInfo, prjConfig);
978       if(exclusionInfo.count == 0)
979          result = false;
980       else if(exclusionInfo.count == 1)
981          result = exclusionInfo.root.minimum.value == true;
982       else
983       {
984          SetBool check = exclusionInfo.root.minimum.value;
985          MapNode<Platform, SetBool> mn;
986          for(mn = exclusionInfo.root.minimum; mn; mn = mn.next)
987          {
988             if(check != mn.value)
989                break;
990          }
991          if(!mn) // all are same
992             result = check == true;
993          else
994             result = false;
995       }
996       delete exclusionInfo;
997       return result;
998    }
999
1000    bool GetIsExcludedForCompiler(ProjectConfig prjConfig, CompilerConfig compiler)
1001    {
1002       bool result;
1003       Map<Platform, SetBool> exclusionInfo { };
1004       SetBool common, platform;
1005       CollectExclusionInfo(exclusionInfo, prjConfig);
1006       common = exclusionInfo[unknown];
1007       platform = exclusionInfo[compiler.targetPlatform];
1008       result = platform == true || (common == true && platform == unset);
1009       delete exclusionInfo;
1010       return result;
1011    }
1012
1013    void CollectExclusionInfo(Map<Platform, SetBool> output, ProjectConfig prjConfig)
1014    {
1015       // note: unknown platform is for common
1016       Platform platform;
1017       ProjectConfig config = GetMatchingNodeConfig(prjConfig);
1018       ProjectOptions options = property::options;
1019       Array<PlatformOptions> platforms = property::platforms;
1020
1021       if(parent)
1022          parent.CollectExclusionInfo(output, prjConfig);
1023       else
1024          output[unknown] = unset;
1025
1026       if(options && options.excludeFromBuild)
1027          output[unknown] = options.excludeFromBuild;
1028
1029       if(config && config.options && config.options.excludeFromBuild)
1030          output[unknown] = config.options.excludeFromBuild;
1031
1032       if(platforms)
1033       {
1034          for(p : platforms)
1035          {
1036             if(p.options.excludeFromBuild && (platform = p.name))
1037                output[platform] = p.options.excludeFromBuild;
1038          }
1039       }
1040       if(config && config.platforms)
1041       {
1042          for(p : config.platforms)
1043          {
1044             if(p.options.excludeFromBuild && (platform = p.name))
1045                output[platform] = p.options.excludeFromBuild;
1046          }
1047       }
1048    }
1049
1050    void EnsureVisible()
1051    {
1052       if(parent)
1053          parent.EnsureVisible();
1054       row.collapsed = false;
1055    }
1056
1057    void Delete()
1058    {
1059       if(parent)
1060          parent.files.Delete(this);
1061    }
1062
1063    ProjectNode Find(const char * name, bool includeResources)
1064    {
1065       ProjectNode result = null;
1066       if(files)
1067       {
1068          for(child : files)
1069          {
1070             if(includeResources || child.type != resources)
1071             {
1072                if(child.type != folder && child.name && !strcmpi(child.name, name))
1073                {
1074                   result = child;
1075                   break;
1076                }
1077                result = child.Find(name, includeResources);
1078                if(result)
1079                   break;
1080             }
1081          }
1082       }
1083       return result;
1084    }
1085
1086    ProjectNode FindWithPath(const char * name, bool includeResources)
1087    {
1088       ProjectNode result = null;
1089       if(files)
1090       {
1091          for(child : files)
1092          {
1093             if(includeResources || child.type != resources)
1094             {
1095                char path[MAX_LOCATION];
1096                strcpy(path, child.path);
1097                if(child.type != folder && child.name)
1098                {
1099                   PathCatSlash(path, child.name);
1100                   if(!strcmpi(path, name))
1101                   {
1102                      result = child;
1103                      break;
1104                   }
1105                }
1106                result = child.FindWithPath(name, includeResources);
1107                if(result)
1108                   break;
1109             }
1110          }
1111       }
1112       return result;
1113    }
1114
1115    ProjectNode FindByFullPath(const char * path, bool includeResources)
1116    {
1117       if(files)
1118       {
1119          char name[MAX_FILENAME];
1120          GetLastDirectory(path, name);
1121          return InternalFindByFullPath(path, includeResources, name);
1122       }
1123       return null;
1124    }
1125
1126    ProjectNode InternalFindByFullPath(const char * path, bool includeResources, const char * lastDirName)
1127    {
1128       ProjectNode result = null;
1129       if(files)
1130       {
1131          for(child : files)
1132          {
1133             if(includeResources || child.type != resources)
1134             {
1135                if(child.type != file)
1136                   result = child.InternalFindByFullPath(path, includeResources, lastDirName);
1137                else if(child.name && !fstrcmp(lastDirName, child.name))
1138                {
1139                   char p[MAX_LOCATION];
1140                   child.GetFullFilePath(p, true);
1141                   if(!fstrcmp(p, path))
1142                   {
1143                      result = child;
1144                      break;
1145                   }
1146                }
1147                if(result)
1148                   break;
1149             }
1150          }
1151       }
1152       return result;
1153    }
1154
1155    ProjectNode FindByObjectFileName(const char * fileName, IntermediateFileType type, bool dotMain, Map<String, NameCollisionInfo> namesInfo, const char * objectFileExt)
1156    {
1157       char p[MAX_LOCATION];
1158       ProjectNode result = null;
1159       if(dotMain == true && this.type == project)
1160       {
1161          GetObjectFileName(p, namesInfo, type, dotMain, objectFileExt);
1162          if(!fstrcmp(p, fileName))
1163             result = this;
1164       }
1165       else if(files)
1166       {
1167          for(child : files; child.type != resources)
1168          {
1169             if(child.type != file && (result = child.FindByObjectFileName(fileName, type, dotMain, namesInfo, objectFileExt)))
1170                break;
1171             else if(child.type == file && child.name)
1172             {
1173                child.GetObjectFileName(p, namesInfo, type, dotMain, objectFileExt);
1174                if(!fstrcmp(p, fileName))
1175                {
1176                   result = child;
1177                   break;
1178                }
1179             }
1180          }
1181       }
1182       return result;
1183    }
1184
1185    ProjectNode FindSpecial(const char * name, bool recursive, bool includeResources, bool includeFolders)
1186    {
1187       ProjectNode result = null;
1188       if(files)
1189       {
1190          for(child : files)
1191          {
1192             if(includeResources || child.type != resources)
1193             {
1194                if((includeFolders || child.type != folder) && child.name && !strcmpi(child.name, name))
1195                {
1196                   result = child;
1197                   break;
1198                }
1199                if(recursive)
1200                   result = child.FindSpecial(name, recursive, includeResources, includeFolders);
1201                if(result)
1202                   break;
1203             }
1204          }
1205       }
1206       return result;
1207    }
1208
1209    ProjectNode FindSameNameConflict(const char * name, bool includeResources,
1210       Map<Platform, SetBool> exclusionInfo, ProjectConfig prjConfig)
1211    {
1212       ProjectNode result = null;
1213       Map<Platform, SetBool> compareExclusion { };
1214       SetBool common, commonComp;
1215       SetBool actual, actualComp;
1216       if(files)
1217       {
1218          for(child : files)
1219          {
1220             if(includeResources || child.type != resources)
1221             {
1222                if(child.type != folder && child.name && !strcmpi(child.name, name))
1223                {
1224                   child.CollectExclusionInfo(compareExclusion, prjConfig);
1225                   common = exclusionInfo[unknown];
1226                   commonComp = compareExclusion[unknown];
1227                   if(exclusionInfo.count == 1 && compareExclusion.count == 1)
1228                   {
1229                      if(!(common == true || commonComp == true))
1230                      {
1231                         result = child;
1232                         break;
1233                      }
1234                   }
1235                   else
1236                   {
1237                      Platform platform;
1238                      for(platform = (Platform)1; platform < Platform::enumSize; platform++)
1239                      {
1240                         actual = common;
1241                         actualComp = commonComp;
1242                         if(exclusionInfo[platform] != unset)
1243                            actual = exclusionInfo[platform];
1244                         if(compareExclusion[platform] != unset)
1245                            actualComp = compareExclusion[platform];
1246                         if(!(actual == true || actualComp == true))
1247                         {
1248                            result = child;
1249                            break;
1250                         }
1251                      }
1252                      if(result) break;
1253                   }
1254                   compareExclusion.Free();
1255                   break;
1256                }
1257                result = child.FindSameNameConflict(name, includeResources, exclusionInfo, prjConfig);
1258                if(result) break;
1259             }
1260          }
1261          compareExclusion.Free();
1262       }
1263       delete compareExclusion;
1264       return result;
1265    }
1266
1267    ProjectNode Add(Project project, const char * filePath, ProjectNode after, NodeTypes type, NodeIcons icon, bool checkIfExists)
1268    {
1269       ProjectNode node = null;
1270       if(!project.topNode.FindByFullPath(filePath, true))
1271       {
1272          char temp[MAX_LOCATION];
1273          Map<Platform, SetBool> exclusionInfo { };
1274
1275          GetLastDirectory(filePath, temp);
1276          //if(!checkIfExists || !project.topNode.Find(temp, false))
1277
1278          // TOCHECK: Shouldn't this apply either for all configs or none?
1279          CollectExclusionInfo(exclusionInfo, project.config);
1280          if(!checkIfExists || type == folder || !project.topNode.FindSameNameConflict(temp, false, exclusionInfo, project.config))
1281          {
1282             // Do the check for folder in the same parent or resource files only here
1283             if(type == folder || !checkIfExists)
1284             {
1285                for(node : files)
1286                {
1287                   if(node.name && !strcmpi(node.name, temp))
1288                      return null;
1289                }
1290             }
1291
1292             node = ProjectNode { parent = this, indent = indent + 1, type = type, icon = icon, name = CopyString(temp) };
1293             if(type != file)
1294             {
1295                node.files = { };
1296                node.nodeType = folder;
1297             }
1298             if(type != folder)
1299             {
1300                if(filePath)
1301                {
1302                   StripLastDirectory(filePath, temp);
1303                   MakePathRelative(temp, project.topNode.path, temp);
1304                   node.path = CopyUnixPath(temp);
1305                }
1306                node.nodeType = file;
1307             }
1308             else
1309             {
1310                strcpy(temp, (type == NodeTypes::project) ? "" : path);
1311                PathCatSlash(temp, node.name);
1312                node.path = CopyString(temp);
1313             }
1314             files.Insert(after, node);
1315          }
1316          delete exclusionInfo;
1317       }
1318       return node;
1319    }
1320
1321 #ifndef MAKEFILE_GENERATOR
1322    void OnDisplay(Surface surface, int x, int y, int width, ProjectView projectView, Alignment alignment, DataDisplayFlags displayFlags)
1323    {
1324       char label[MAX_FILENAME];
1325       int xStart;
1326       int len;
1327       int w, h;
1328       Bitmap bmp;
1329       bool showConfig = true;
1330
1331       if(!projectView)
1332       {
1333          showConfig = false;
1334          projectView = ide.projectView;
1335       }
1336
1337       bmp = projectView.icons[icon].bitmap;
1338       xStart = x + (bmp ? (bmp.width + 5) : 0);
1339
1340       GetLastDirectory(name, label);
1341       if(!showConfig || projectView.drawingInProjectSettingsDialogHeader)
1342       {
1343          if(projectView.drawingInProjectSettingsDialogHeader || (type == project && info))
1344          {
1345             if(projectView.projectSettingsDialog && projectView.projectSettingsDialog.buildTab)
1346             {
1347                const char * addendum = projectView.projectSettingsDialog.buildTab.selectedConfigName;
1348                if(strlen(addendum))
1349                {
1350                   strcat(label, " (");
1351                   strcat(label, addendum);
1352                   strcat(label, ")");
1353                }
1354                addendum = projectView.projectSettingsDialog.buildTab.selectedPlatformName;
1355                if(strlen(addendum))
1356                {
1357                   strcat(label, " (");
1358                   strcat(label, addendum);
1359                   strcat(label, ")");
1360                }
1361             }
1362          }
1363       }
1364       else if(!projectView.drawingInProjectSettingsDialog)
1365       {
1366          if(modified)
1367             strcat(label, " *");
1368          if(type == project && info)
1369          {
1370             int len = strlen(info) + 4;
1371             char * more = new char[len];
1372             sprintf(more, " (%s)", info);
1373             strcat(label, more);
1374             delete more;
1375          }
1376       }
1377       len = strlen(label);
1378
1379       if(!bmp)
1380       {
1381          if(type == folder || type == folderOpen)
1382             surface.SetForeground(yellow);
1383          indent = 8;
1384       }
1385
1386       surface.TextOpacity(false);
1387       surface.TextExtent(label, len, &w, &h);
1388       h = Max(h, 16);
1389
1390       // Draw the current row stipple
1391       if(displayFlags.selected)
1392          //surface.Area(xStart - 1, y, xStart - 1, y + h - 1);
1393          //surface.Area(xStart + w - 1, y, xStart + w + 1, y + h - 1);
1394          surface.Area(xStart - 3, y, xStart + w + 1, y + h - 1);
1395
1396       surface.WriteTextDots(alignment, xStart, y + 2, width, label, len);
1397
1398       if(!app.textMode)
1399       {
1400          if(displayFlags.current)
1401          {
1402             if(displayFlags.active)
1403             {
1404                surface.LineStipple(0x5555);
1405                if(displayFlags.selected)
1406                   surface.SetForeground(projectView.fileList.stippleColor);
1407                else
1408                   surface.SetForeground(projectView.fileList.foreground);
1409             }
1410             else
1411             {
1412                surface.SetForeground(SELECTION_COLOR);
1413             }
1414             surface.Rectangle(xStart - 3, y, xStart + w + 1, y + h - 1);
1415             surface.LineStipple(0);
1416          }
1417
1418          if(bmp)
1419          {
1420             surface.SetForeground(white);
1421             surface.Blit(bmp, x /*+ indent * indent*/,y,0,0, bmp.width, bmp.height);
1422          }
1423       }
1424    }
1425 #endif // #ifndef MAKEFILE_GENERATOR
1426
1427    int OnCompare(ProjectNode b)
1428    {
1429       int result = 0;
1430       if(type == b.type /*|| type >= TYPE_DRIVE*/)
1431          result = strcmpi(name, b.name);
1432       else
1433       {
1434          if(type == folder && b.type == file) result = -1;
1435          else if(type == file && b.type == folder) result = 1;
1436       }
1437       return result;
1438    }
1439
1440    bool ContainsFilesWithExtension(const char * extension, ProjectConfig prjConfig)
1441    {
1442       if(type == file && name && name[0])
1443       {
1444          char ext[MAX_EXTENSION];
1445          GetExtension(name, ext);
1446          if(!fstrcmp(ext, extension))
1447             return true;
1448       }
1449       else if(files)
1450       {
1451          for(child : files)
1452          {
1453             if(child.type != resources && (child.type == folder || !prjConfig || !child.GetIsExcluded(prjConfig)))
1454             {
1455                if(child.ContainsFilesWithExtension(extension, prjConfig))
1456                   return true;
1457             }
1458          }
1459       }
1460       return false;
1461    }
1462
1463    void GenMakefileGetNameCollisionInfo(Map<String, NameCollisionInfo> namesInfo, ProjectConfig prjConfig)
1464    {
1465       if(type == file)
1466       {
1467          char extension[MAX_EXTENSION];
1468          GetExtension(name, extension);
1469          if(!strcmpi(extension, "ec") || !strcmpi(extension, "s") || !strcmpi(extension, "c") ||
1470                !strcmpi(extension, "rc") || !strcmpi(extension, "cpp") || !strcmpi(extension, "cc") ||
1471                !strcmpi(extension, "cxx") || !strcmpi(extension, "m") || !strcmpi(extension, "mm"))
1472          {
1473             char moduleName[MAX_FILENAME];
1474             NameCollisionInfo info;
1475             ReplaceSpaces(moduleName, name);
1476             StripExtension(moduleName);
1477             info = namesInfo[moduleName];
1478             if(!info)
1479                info = NameCollisionInfo { };
1480             info.count++; // += 1; unless this is for a bug?
1481             if(!strcmpi(extension, "ec"))
1482                info.ec = true;
1483             else if(!strcmpi(extension, "s"))
1484                info.s = true;
1485             else if(!strcmpi(extension, "c"))
1486                info.c = true;
1487             else if(!strcmpi(extension, "rc"))
1488                info.rc = true;
1489             else if(!strcmpi(extension, "cpp"))
1490                info.cpp = true;
1491             else if(!strcmpi(extension, "cc"))
1492                info.cc = true;
1493             else if(!strcmpi(extension, "cxx"))
1494                info.cxx = true;
1495             else if(!strcmpi(extension, "m"))
1496                info.m = true;
1497             else if(!strcmpi(extension, "mm"))
1498                info.mm = true;
1499             namesInfo[moduleName] = info;
1500          }
1501       }
1502       else if(files)
1503       {
1504          for(child : files)
1505          {
1506             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
1507                child.GenMakefileGetNameCollisionInfo(namesInfo, prjConfig);
1508          }
1509       }
1510    }
1511
1512    int GenMakefilePrintNode(File f, Project project, GenMakefilePrintTypes printType,
1513       Map<String, NameCollisionInfo> namesInfo, Array<String> items,
1514       ProjectConfig prjConfig, bool * containsCXX)
1515    {
1516       int count = 0;
1517       if(type == file)
1518       {
1519          char s[2048];
1520          TwoStrings ts = GetPlatformSpecificFu(prjConfig);
1521          char moduleName[MAX_FILENAME];
1522          char extension[MAX_EXTENSION];
1523          GetExtension(name, extension);
1524          if(printType == resources)
1525          {
1526             bool useRes;
1527             char tempPath[MAX_LOCATION];
1528             char modulePath[MAX_LOCATION];
1529
1530             tempPath[0] = '\0';
1531             if(eString_PathInsideOfMore(path, project.resNode.path, tempPath))
1532             {
1533                useRes = true;
1534                PathCatSlash(tempPath, name);
1535             }
1536             else
1537             {
1538                useRes = false;
1539                strcpy(tempPath, path);
1540                PathCatSlash(tempPath, name);
1541             }
1542             EscapeForMake(modulePath, tempPath, false, true, false);
1543             sprintf(s, "%s%s%s%s", ts.a, useRes ? "$(RES)" : "", modulePath, ts.b);
1544             items.Add(CopyString(s));
1545          }
1546          else if(printType == sources)
1547          {
1548             if(!strcmpi(extension, "s") || !strcmpi(extension, "c") || !strcmpi(extension, "cpp") ||
1549                   !strcmpi(extension, "cc") || !strcmpi(extension, "cxx") ||
1550                   !strcmpi(extension, "m") || !strcmpi(extension, "mm"))
1551             {
1552                char modulePath[MAX_LOCATION];
1553                EscapeForMake(modulePath, path, false, true, false);
1554                EscapeForMake(moduleName, name, false, true, false);
1555                sprintf(s, "%s%s%s%s%s", ts.a, modulePath, path[0] ? SEPS : "", moduleName, ts.b);
1556                items.Add(CopyString(s));
1557             }
1558          }
1559          else if(printType == eCsources)
1560          {
1561             if(!strcmpi(extension, "ec"))
1562             {
1563                char modulePath[MAX_LOCATION];
1564                EscapeForMake(modulePath, path, true, true, false);
1565                EscapeForMake(moduleName, name, true, true, false);
1566                sprintf(s, "%s%s%s%s%s", ts.a, modulePath, path[0] ? SEPS : "", moduleName, ts.b);
1567                items.Add(CopyString(s));
1568                count++;
1569             }
1570          }
1571          else if(printType == rcSources)
1572          {
1573             if(!strcmpi(extension, "rc"))
1574             {
1575                char modulePath[MAX_LOCATION];
1576                EscapeForMake(modulePath, path, false, true, false);
1577                EscapeForMake(moduleName, name, false, true, false);
1578                sprintf(s, "%s%s%s%s%s", ts.a, modulePath, path[0] ? SEPS : "", moduleName, ts.b);
1579                items.Add(CopyString(s));
1580                count++;
1581             }
1582          }
1583          else if(!strcmpi(extension, "s") || !strcmpi(extension, "c") || !strcmpi(extension, "cpp") ||
1584                !strcmpi(extension, "cc") || !strcmpi(extension, "cxx") ||
1585                !strcmpi(extension, "m") || !strcmpi(extension, "mm"))
1586          {
1587             if(printType == objects)
1588             {
1589                bool collision;
1590                NameCollisionInfo info;
1591                count++;
1592                EscapeForMake(moduleName, name, false, true, false);
1593                StripExtension(moduleName);
1594                info = namesInfo[moduleName];
1595                collision = info ? info.IsExtensionColliding(extension) : false;
1596                sprintf(s, "%s$(OBJ)%s%s%s$(O)%s", ts.a, moduleName, collision ? "." : "", collision ? extension : "", ts.b);
1597                items.Add(CopyString(s));
1598                if(containsCXX && (!strcmpi(extension, "cpp") || !strcmpi(extension, "cc") || !strcmpi(extension, "cxx")))
1599                   *containsCXX = true;
1600             }
1601          }
1602          delete ts;
1603       }
1604       else if(files)
1605       {
1606          for(child : files)
1607          {
1608             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
1609                count += child.GenMakefilePrintNode(f, project, printType, namesInfo, items, prjConfig, containsCXX);
1610          }
1611       }
1612       return count;
1613    }
1614
1615    void GenMakefilePrintSymbolRules(File f, Project project,
1616          ProjectConfig prjConfig, //Map<Platform, bool> parentExcludedPlatforms,
1617          Map<intptr, int> nodeCFlagsMapping, Map<intptr, int> nodeECFlagsMapping)
1618    {
1619       int ifCount = 0;
1620       Array<Platform> platforms = GetPlatformsArrayFromExclusionInfo(prjConfig);
1621       //ProjectNode child;
1622       //char objDir[MAX_LOCATION];
1623       //ReplaceSpaces(objDir, config.objDir.dir);
1624
1625       //eSystem_Log("Printing Symbol Rules\n");
1626       if(type == file)
1627       {
1628          char extension[MAX_EXTENSION];
1629          char modulePath[MAX_LOCATION];
1630          char moduleName[MAX_FILENAME];
1631
1632          GetExtension(name, extension);
1633          if(!strcmpi(extension, "ec"))
1634          {
1635             //DualPipe dep;
1636             //char command[2048];
1637
1638             ReplaceSpaces(moduleName, name);
1639             StripExtension(moduleName);
1640
1641             ReplaceSpaces(modulePath, path);
1642             if(modulePath[0]) strcat(modulePath, SEPS);
1643
1644             OpenRulesPlatformExclusionIfs(f, &ifCount, platforms);
1645 #if 0
1646             // *** Dependency command ***
1647             sprintf(command, "gcc -MT $(OBJ)%s.o -MM %s%s.%s", moduleName,
1648                modulePath, moduleName, extension);
1649
1650             // System Includes (from global settings)
1651             for(item : compiler.dirs[Includes])
1652             {
1653                strcat(command, " -isystem ");
1654                if(strchr(item, ' '))
1655                {
1656                   strcat(command, "\"");
1657                   strcat(command, item);
1658                   strcat(command, "\"");
1659                }
1660                else
1661                   strcat(command, item);
1662             }
1663
1664             for(item : project.includeDirs)
1665             {
1666                strcat(command, " -I");
1667                if(strchr(item, ' '))
1668                {
1669                   strcat(command, "\"");
1670                   strcat(command, item);
1671                   strcat(command, "\"");
1672                }
1673                else
1674                   strcat(command, item);
1675             }
1676             for(item : project.preprocessorDefs)
1677             {
1678                strcat(command, " -D");
1679                strcat(command, item);
1680             }
1681
1682             // Execute it
1683             if((dep = DualPipeOpen(PipeOpenMode { output = true, error = true/*, input = true*/ }, command)))
1684             {
1685                char line[1024];
1686                bool firstLine = true;
1687                bool result = true;
1688
1689                // To do some time: auto save external dependencies?
1690                while(!dep.Eof())
1691                {
1692                   if(dep.GetLine(line, sizeof(line)-1))
1693                   {
1694                      if(firstLine)
1695                      {
1696                         char * colon = strstr(line, ":");
1697                         if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
1698                         {
1699                            result = false;
1700                            break;
1701                         }
1702                         firstLine = false;
1703                      }
1704                      f.Puts(line);
1705                      f.Puts("\n");
1706                   }
1707                   if(!result) break;
1708                }
1709                delete dep;
1710
1711                // If we failed to generate dependencies...
1712                if(!result)
1713                {
1714 #endif
1715                   f.Printf("$(OBJ)%s.sym: %s%s.%s\n",
1716                      moduleName, modulePath, moduleName, extension);
1717
1718                   f.Puts("\t$(ECP)");
1719
1720                   f.Puts(" $(CFLAGS)");
1721                   f.Puts(" $(CECFLAGS)"); // tocheck: what of this? should this stuff be per-file customized?
1722
1723                   GenMakePrintNodeFlagsVariable(this, nodeECFlagsMapping, "ECFLAGS", f);
1724                   GenMakePrintNodeFlagsVariable(this, nodeCFlagsMapping, "PRJ_CFLAGS", f);
1725
1726                   f.Printf(" -c $(call quote_path,%s%s.%s) -o $(call quote_path,$@)\n",
1727                      modulePath, moduleName, extension);
1728                   if(ifCount) f.Puts("endif\n");
1729                   f.Puts("\n");
1730 #if 0
1731                }
1732             }
1733 #endif
1734          }
1735       }
1736       if(files)
1737       {
1738          if(ContainsFilesWithExtension("ec", prjConfig))
1739          {
1740             for(child : files)
1741             {
1742                if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
1743                   child.GenMakefilePrintSymbolRules(f, project, prjConfig, /*excludedPlatforms,*/
1744                         nodeCFlagsMapping, nodeECFlagsMapping);
1745             }
1746          }
1747       }
1748       delete platforms;
1749    }
1750
1751    void GenMakefilePrintPrepecsRules(File f, Project project,
1752          ProjectConfig prjConfig, /*Map<Platform, bool> parentExcludedPlatforms,*/
1753          Map<intptr, int> nodeCFlagsMapping, Map<intptr, int> nodeECFlagsMapping)
1754    {
1755       int ifCount = 0;
1756       Array<Platform> platforms = GetPlatformsArrayFromExclusionInfo(prjConfig);
1757       //ProjectNode child;
1758       //char objDir[MAX_LOCATION];
1759       //ReplaceSpaces(objDir, config.objDir.dir);
1760
1761       //eSystem_Log("Printing Symbol Rules\n");
1762       if(type == file)
1763       {
1764          char extension[MAX_EXTENSION];
1765          char modulePath[MAX_LOCATION];
1766          char moduleName[MAX_FILENAME];
1767
1768          GetExtension(name, extension);
1769          if(!strcmpi(extension, "ec"))
1770          {
1771             ReplaceSpaces(moduleName, name);
1772             StripExtension(moduleName);
1773
1774             ReplaceSpaces(modulePath, path);
1775             if(modulePath[0]) strcat(modulePath, SEPS);
1776
1777             OpenRulesPlatformExclusionIfs(f, &ifCount, platforms);
1778             f.Printf("$(OBJ)%s$(EC): %s%s.%s\n",
1779                moduleName, modulePath, moduleName, extension);
1780             /*f.Printf("\t$(CPP) %s%s.%s %s$(S)\n\n",
1781                modulePath, moduleName, extension, moduleName);*/
1782
1783             f.Puts("\t$(CPP)");
1784
1785             f.Puts(" $(CFLAGS)");
1786             //f.Puts(" $(CECFLAGS)");
1787             //GenMakePrintNodeFlagsVariable(this, nodeECFlagsMapping, "ECFLAGS", f);
1788             GenMakePrintNodeFlagsVariable(this, nodeCFlagsMapping, "PRJ_CFLAGS", f);
1789
1790             f.Printf(" -x c -E %s%s.%s -o $(OBJ)%s$(EC)\n",
1791                modulePath, moduleName, extension, moduleName);
1792             if(ifCount) f.Puts("endif\n");
1793             f.Puts("\n");
1794          }
1795       }
1796       if(files)
1797       {
1798          if(ContainsFilesWithExtension("ec", prjConfig))
1799          {
1800             for(child : files)
1801             {
1802                if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
1803                   child.GenMakefilePrintPrepecsRules(f, project, prjConfig, /*excludedPlatforms,*/
1804                         nodeCFlagsMapping, nodeECFlagsMapping);
1805             }
1806          }
1807       }
1808       delete platforms;
1809    }
1810
1811    void GenMakefilePrintCObjectRules(File f, Project project,
1812       ProjectConfig prjConfig, /*Map<Platform, bool> parentExcludedPlatforms,*/
1813       Map<intptr, int> nodeCFlagsMapping, Map<intptr, int> nodeECFlagsMapping)
1814    {
1815       int ifCount = 0;
1816       Array<Platform> platforms = GetPlatformsArrayFromExclusionInfo(prjConfig);
1817       //ProjectNode child;
1818       //char objDir[MAX_LOCATION];
1819       //ReplaceSpaces(objDir, config.objDir.dir);
1820       //eSystem_Log("Printing C Object Rules\n");
1821       if(type == file)
1822       {
1823          char extension[MAX_EXTENSION];
1824          char modulePath[MAX_LOCATION];
1825          char moduleName[MAX_FILENAME];
1826
1827          GetExtension(name, extension);
1828          if(!strcmpi(extension, "ec"))
1829          {
1830             //DualPipe dep;
1831             //char command[2048];
1832
1833             ReplaceSpaces(moduleName, name);
1834             StripExtension(moduleName);
1835
1836             ReplaceSpaces(modulePath, path);
1837             if(modulePath[0]) strcat(modulePath, SEPS);
1838
1839             OpenRulesPlatformExclusionIfs(f, &ifCount, platforms);
1840 #if 0
1841             // *** Dependency command ***
1842             sprintf(command, "gcc -MT $(OBJ)%s.o -MM %s%s.%s",
1843                moduleName, modulePath, moduleName, extension);
1844
1845             // System Includes (from global settings)
1846             for(item : compiler.dirs[Includes])
1847             {
1848                strcat(command, " -isystem ");
1849                if(strchr(item, ' '))
1850                {
1851                   strcat(command, "\"");
1852                   strcat(command, item);
1853                   strcat(command, "\"");
1854                }
1855                else
1856                   strcat(command, item);
1857             }
1858
1859             for(item : config.includeDirs)
1860             {
1861                strcat(command, " -I");
1862                if(strchr(item, ' '))
1863                {
1864                   strcat(command, "\"");
1865                   strcat(command, item);
1866                   strcat(command, "\"");
1867                }
1868                else
1869                   strcat(command, item);
1870             }
1871             for(item : config.preprocessorDefs)
1872             {
1873                strcat(command, " -D");
1874                strcat(command, item);
1875             }
1876
1877             // Execute it
1878             if((dep = DualPipeOpen(PipeOpenMode { output = true, error = true/*, input = true*/ }, command)))
1879             {
1880                char line[1024];
1881                bool result = true;
1882                bool firstLine = true;
1883
1884                // To do some time: auto save external dependencies?
1885                while(!dep.Eof())
1886                {
1887                   if(dep.GetLine(line, sizeof(line)-1))
1888                   {
1889                      if(firstLine)
1890                      {
1891                         char * colon = strstr(line, ":");
1892                         if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
1893                         {
1894                            result = false;
1895                            break;
1896                         }
1897                         firstLine = false;
1898                      }
1899                      f.Puts(line);
1900                      f.Puts("\n");
1901                   }
1902                   if(!result) break;
1903                }
1904                delete dep;
1905
1906                // If we failed to generate dependencies...
1907                if(!result)
1908                {
1909                   /* COMMENTED OUT FOR NOW
1910                   f.Printf("$(OBJ)%s.c: %s%s.%s $(Symbols)\n",
1911                      moduleName, modulePath, moduleName, extension);
1912                   */
1913 #endif
1914                   f.Printf("$(OBJ)%s.c: %s%s.%s $(OBJ)%s.sym | $(SYMBOLS)\n",
1915                      moduleName, modulePath, moduleName, extension, moduleName);
1916 #if 0
1917                }
1918             }
1919 #endif
1920          /*
1921             f.Printf("\t$(ECC) %s%s.%s $(OBJ)%s.c\n\n",
1922                modulePath, moduleName, extension, moduleName);
1923          */
1924
1925             f.Puts("\t$(ECC)");
1926
1927             f.Puts(" $(CFLAGS)");
1928             f.Puts(" $(CECFLAGS)"); // what of this? should this stuff be per-file customized?
1929             GenMakePrintNodeFlagsVariable(this, nodeECFlagsMapping, "ECFLAGS", f);
1930             GenMakePrintNodeFlagsVariable(this, nodeCFlagsMapping, "PRJ_CFLAGS", f);
1931             f.Puts(" $(FVISIBILITY)");
1932
1933             f.Printf(" -c $(call quote_path,%s%s.%s) -o $(call quote_path,$@) -symbols $(OBJ)\n",
1934                modulePath, moduleName, extension);
1935             if(ifCount) f.Puts("endif\n");
1936             f.Puts("\n");
1937          }
1938       }
1939       if(files)
1940       {
1941          if(ContainsFilesWithExtension("ec", prjConfig))
1942          {
1943             for(child : files)
1944             {
1945                if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
1946                   child.GenMakefilePrintCObjectRules(f, project, prjConfig, /*excludedPlatforms,*/
1947                         nodeCFlagsMapping, nodeECFlagsMapping);
1948             }
1949          }
1950       }
1951       delete platforms;
1952    }
1953
1954    void GenMakefilePrintObjectRules(File f, Project project,
1955       Map<String, NameCollisionInfo> namesInfo,
1956       ProjectConfig prjConfig,
1957       //Map<Platform, bool> parentExcludedPlatforms,
1958       Map<intptr, int> nodeCFlagsMapping, Map<intptr, int> nodeECFlagsMapping)
1959    {
1960       int ifCount = 0;
1961       Array<Platform> platforms = GetPlatformsArrayFromExclusionInfo(prjConfig);
1962       //ProjectNode child;
1963       //char objDir[MAX_LOCATION];
1964       //ReplaceSpaces(objDir, config.objDir.dir);
1965       //eSystem_Log("Printing Object Rules\n");
1966       if(type == file)
1967       {
1968          bool collision;
1969          char extension[MAX_EXTENSION];
1970          char modulePath[MAX_LOCATION];
1971          char moduleName[MAX_FILENAME];
1972
1973          GetExtension(name, extension);
1974          if(!strcmpi(extension, "s") || !strcmpi(extension, "c") || !strcmpi(extension, "rc") ||
1975                !strcmpi(extension, "cpp") || !strcmpi(extension, "cc") || !strcmpi(extension, "cxx") ||
1976                !strcmpi(extension, "m") || !strcmpi(extension, "mm") || !strcmpi(extension, "ec"))
1977          {
1978             //DualPipe dep;
1979             //char command[2048];
1980             NameCollisionInfo info;
1981
1982             ReplaceSpaces(moduleName, name);
1983             StripExtension(moduleName);
1984
1985             info = namesInfo[moduleName];
1986             collision = info ? info.IsExtensionColliding(extension) : false;
1987
1988             ReplaceSpaces(modulePath, path);
1989             if(modulePath[0]) strcat(modulePath, SEPS);
1990
1991             /*
1992 #if 0
1993             // *** Dependency command ***
1994             if(!strcmpi(extension, "ec"))
1995                sprintf(command, "%s -MT $(OBJ)%s.o -MM $(OBJ)%s.c", "$(CPP)", moduleName, moduleName);
1996             else
1997                sprintf(command, "%s -MT $(OBJ)%s.o -MM %s%s.%s", (!strcmpi(extension, "cc") || !strcmpi(extension, "cxx") || !strcmpi(extension, "cpp")) ? "$(CXX)" : "$(CC)",
1998                   moduleName, modulePath, moduleName, extension);
1999
2000             if(!strcmpi(extension, "ec"))
2001             {
2002                f.Printf("$(OBJ)%s.o: $(OBJ)%s.c\n", moduleName, moduleName);
2003             }
2004             else
2005             {
2006                // System Includes (from global settings)
2007                for(item : compiler.dirs[includes])
2008                {
2009                   strcat(command, " -isystem ");
2010                   if(strchr(item, ' '))
2011                   {
2012                      strcat(command, "\"");
2013                      strcat(command, item);
2014                      strcat(command, "\"");
2015                   }
2016                   else
2017                      strcat(command, item);
2018                }
2019
2020                for(item : config.includeDirs)
2021                {
2022                   strcat(command, " -I");
2023                   if(strchr(item, ' '))
2024                   {
2025                      strcat(command, "\"");
2026                      strcat(command, item);
2027                      strcat(command, "\"");
2028                   }
2029                   else
2030                      strcat(command, item);
2031                }
2032                for(item : config.preprocessorDefs)
2033                {
2034                   strcat(command, " -D");
2035                   strcat(command, item);
2036                }
2037
2038                // Execute it
2039                if((dep = DualPipeOpen(PipeOpenMode { output = true, error = true, input = false }, command)))
2040                {
2041                   char line[1024];
2042                   bool firstLine = true;
2043                   bool result = true;
2044
2045                   // To do some time: auto save external dependencies?
2046
2047                   while(!dep.Eof())
2048                   {
2049                      if(dep.GetLine(line, sizeof(line)-1))
2050                      {
2051                         if(firstLine)
2052                         {
2053                            char * colon = strstr(line, ":");
2054                            if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2055                            {
2056                               result = false;
2057                               break;
2058                            }
2059                            firstLine = false;
2060                         }
2061                         f.Puts(line);
2062                         f.Puts("\n");
2063                      }
2064                      if(!result) break;
2065                   }
2066                   delete dep;
2067
2068                   // If we failed to generate dependencies...
2069                   if(!result)
2070                   {
2071
2072                   }
2073                }
2074             }
2075 #endif
2076          */
2077             if(!strcmpi(extension, "rc"))
2078             {
2079                ifCount++;
2080                f.Puts("ifdef WINDOWS_TARGET\n\n");
2081             }
2082             else
2083                OpenRulesPlatformExclusionIfs(f, &ifCount, platforms);
2084
2085             if(!strcmpi(extension, "ec"))
2086                f.Printf("$(OBJ)%s$(O): $(OBJ)%s.c\n", moduleName, moduleName);
2087             else
2088                f.Printf("$(OBJ)%s%s%s$(O): %s%s.%s\n",
2089                      moduleName, collision ? "." : "", collision ? extension : "",
2090                      modulePath, moduleName, extension);
2091             if(!strcmpi(extension, "cc") || !strcmpi(extension, "cpp") || !strcmpi(extension, "cxx"))
2092                f.Printf("\t$(CXX)");
2093             else if(!strcmpi(extension, "rc"))
2094                f.Printf("\t$(WINDRES) $(WINDRES_FLAGS) $< \"$(call escspace,$(call quote_path,$@))\"\n");
2095             else
2096                f.Printf("\t$(CC)");
2097
2098             if(strcmpi(extension, "rc") != 0)
2099             {
2100                f.Puts(" $(CFLAGS)");
2101                GenMakePrintNodeFlagsVariable(this, nodeCFlagsMapping, "PRJ_CFLAGS", f);
2102
2103                if(!strcmpi(extension, "ec"))
2104                   f.Printf(" $(FVISIBILITY) -c $(call quote_path,$(OBJ)%s.c) -o $(call quote_path,$@)\n",
2105                         moduleName);
2106                else
2107                   f.Printf(" -c $(call quote_path,%s%s.%s) -o $(call quote_path,$@)\n",
2108                         modulePath, moduleName, !strcmpi(extension, "ec") ? "c" : extension);
2109             }
2110             if(ifCount) f.Puts("endif\n");
2111             f.Puts("\n");
2112          }
2113       }
2114       if(files)
2115       {
2116          bool needed = false;
2117          for(child : files)
2118          {
2119             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
2120             {
2121                needed = true;
2122                break;
2123             }
2124          }
2125          if(needed)
2126          {
2127             for(child : files)
2128             {
2129                if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
2130                   child.GenMakefilePrintObjectRules(f, project, namesInfo, prjConfig, /*excludedPlatforms,*/
2131                         nodeCFlagsMapping, nodeECFlagsMapping);
2132             }
2133          }
2134       }
2135       delete platforms;
2136    }
2137
2138    void GenMakefileAddResources(File f, String resourcesPath, ProjectConfig prjConfig)
2139    {
2140       int count = 0;
2141       if(files)
2142       {
2143          int c;
2144          bool prev = false;
2145          //Iterator<ProjectNode> i { files };
2146          //Iterator<ProjectNode> prev { files };
2147          //for(child : files)
2148          //while(i.Next())
2149          for(c = 0; c < files.count; c++)
2150          {
2151             ProjectNode child = files[c];
2152             TwoStrings ts = child.GetPlatformSpecificFu(prjConfig);
2153             if(count > 0 && ts)
2154                prev = true;
2155             if(child.type == file && !child.GetIsExcluded(prjConfig) && !(count > 0 && ts))
2156             {
2157                bool useRes;
2158                char tempPath[MAX_LOCATION];
2159                char resPath[MAX_LOCATION];
2160
2161                // $(EAR) aw%s --- /*quiet ? "q" : */""
2162                if(count == 0)
2163                   f.Printf("\t%s$(EAR) aw$(EARFLAGS) $(TARGET)", ts.a);
2164
2165                tempPath[0] = '\0';
2166                if(eString_PathInsideOfMore(child.path, resourcesPath, tempPath))
2167                {
2168                   useRes = true;
2169                   PathCatSlash(tempPath, child.name);
2170                }
2171                else
2172                {
2173                   useRes = false;
2174                   strcpy(tempPath, child.path);
2175                   PathCatSlash(tempPath, child.name);
2176                }
2177                EscapeForMake(resPath, tempPath, false, true, false);
2178                f.Printf(" %s%s", useRes ? "$(RES)" : "", resPath);
2179                count++;
2180             }
2181             if(count == 10 || (count > 0 && (ts || !child.next)))
2182             {
2183                char path[MAX_LOCATION] = "", temp[MAX_LOCATION];
2184                ProjectNode parent;
2185
2186                for(parent = this; parent.type == folder; parent = parent.parent)
2187                {
2188                   strcpy(temp, path);
2189                   strcpy(path, parent.name);
2190                   if(temp[0])
2191                   {
2192                      strcat(path, "/");
2193                      strcat(path, temp);
2194                   }
2195                }
2196                f.Printf(" \"%s\"%s\n", path, ts.b);
2197                count = 0;
2198                if(prev)
2199                {
2200                   c--;
2201                   prev = false;
2202                }
2203             }
2204             delete ts;
2205          }
2206          for(child : files)
2207          {
2208             if(child.type == folder)
2209                child.GenMakefileAddResources(f, resourcesPath, prjConfig);
2210          }
2211       }
2212    }
2213
2214    void GenMakeCollectAssignNodeFlags(ProjectConfig prjConfig, bool prjWithEcFiles,
2215          Map<String, int> cflagsVariations, Map<intptr, int> nodeCFlagsMapping,
2216          Map<String, int> ecflagsVariations, Map<intptr, int> nodeECFlagsMapping,
2217          Map<Platform, ProjectOptions> parentByPlatformOptions)
2218    {
2219       Map<Platform, ProjectOptions> byPlatformOptions = parentByPlatformOptions;
2220       if(type == file || type == folder || type == project)
2221       {
2222          bool hasPerNodeOptions = type == project;
2223          if(!hasPerNodeOptions)
2224          {
2225             if(options && !options.isEmpty)
2226                hasPerNodeOptions = true;
2227             else if(configurations)
2228             {
2229                for(c : configurations)
2230                {
2231                   if(c.options && !c.options.isEmpty)
2232                   {
2233                      hasPerNodeOptions = true;
2234                      break;
2235                   }
2236                   if(c.platforms)
2237                   {
2238                      for(p : c.platforms)
2239                      {
2240                         if(p.options && !p.options.isEmpty)
2241                         {
2242                            hasPerNodeOptions = true;
2243                            break;
2244                         }
2245                      }
2246                      if(hasPerNodeOptions)
2247                         break;
2248                   }
2249                }
2250             }
2251             if(!hasPerNodeOptions && platforms)
2252             {
2253                for(p : platforms)
2254                {
2255                   if(p.options && !p.options.isEmpty)
2256                   {
2257                      hasPerNodeOptions = true;
2258                      break;
2259                   }
2260                }
2261             }
2262
2263          }
2264          if(hasPerNodeOptions)
2265          {
2266             bool isEqual = false, isGreater = false;
2267             ComplexComparison complexCmp;
2268             DynamicString s;
2269             Map<Platform, ProjectOptions> additionsByPlatformOptions { };
2270             ProjectOptions platformsCommonOptions;
2271             ProjectOptions byFileConfigPlatformProjectOptions;
2272
2273             DynamicString cflags { };
2274             DynamicString ecflags { };
2275
2276             Platform platform;
2277
2278             byPlatformOptions = { };
2279
2280             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2281             {
2282                byFileConfigPlatformProjectOptions =
2283                      BlendFileConfigPlatformProjectOptions(this, prjConfig, platform);
2284                byPlatformOptions[platform] = byFileConfigPlatformProjectOptions;
2285             }
2286
2287             CollectPlatformsCommonOptions(byPlatformOptions, &platformsCommonOptions);
2288
2289             byPlatformOptions[unknown] = platformsCommonOptions;
2290
2291             if(parentByPlatformOptions)
2292             {
2293                complexCmp = PlatformsOptionsGreaterEqual(byPlatformOptions,
2294                      parentByPlatformOptions, additionsByPlatformOptions);
2295                isGreater = complexCmp == greater;
2296                isEqual = complexCmp == equal;
2297             }
2298
2299             if(!isEqual)
2300             {
2301                for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2302                {
2303                   byFileConfigPlatformProjectOptions = isGreater ? additionsByPlatformOptions[platform] : byPlatformOptions[platform];
2304                   s = { };
2305                   GenCFlagsFromProjectOptions(byFileConfigPlatformProjectOptions, prjWithEcFiles, false, isGreater, s);
2306                   if(s.count > 1)
2307                      cflags.concatf(" \\\n\t $(if $(%s),%s,)", PlatformToMakefileTargetVariable(platform), (String)s);
2308                   delete s;
2309                   s = { };
2310                   GenECFlagsFromProjectOptions(byFileConfigPlatformProjectOptions, prjWithEcFiles, s);
2311                   if(s.count > 1)
2312                      ecflags.concatf(" \\\n\t $(if $(%s),%s,)", PlatformToMakefileTargetVariable(platform), (String)s);
2313                   delete s;
2314                }
2315
2316                platformsCommonOptions = isGreater ? additionsByPlatformOptions[unknown] : byPlatformOptions[unknown];
2317                s = { };
2318                GenCFlagsFromProjectOptions(platformsCommonOptions, prjWithEcFiles, true, isGreater, s);
2319                if(s.count > 1)
2320                {
2321                   if(!isGreater) cflags.concat(" \\\n\t");
2322                   cflags.concat(s);
2323                }
2324                delete s;
2325                s = { };
2326                GenECFlagsFromProjectOptions(platformsCommonOptions, prjWithEcFiles, s);
2327                if(s.count > 1)
2328                {
2329                   ecflags.concat(" \\\n\t");
2330                   ecflags.concat(s);
2331                }
2332                delete s;
2333
2334                if(isGreater)
2335                {
2336                   cflags.concat(" \\\n\t");
2337                   DynStringPrintNodeFlagsVariable(parent, nodeCFlagsMapping, "PRJ_CFLAGS", cflags);
2338                }
2339             }
2340
2341             additionsByPlatformOptions.Free();
2342             delete additionsByPlatformOptions;
2343
2344             // output
2345             {
2346                if(isEqual)
2347                {
2348                   nodeCFlagsMapping[(intptr)this] = nodeCFlagsMapping[(intptr)parent];
2349                   nodeECFlagsMapping[(intptr)this] = nodeECFlagsMapping[(intptr)parent];
2350                }
2351                else
2352                {
2353                   String s;
2354                   int variationNum;
2355
2356                   variationNum = 1;
2357                   if((s = cflags) && s[0] && !(variationNum = cflagsVariations[s]))
2358                      cflagsVariations[s] = variationNum = cflagsVariations.count;
2359                   nodeCFlagsMapping[(intptr)this] = variationNum;
2360
2361                   variationNum = 1;
2362                   if((s = ecflags) && s[0] && !(variationNum = ecflagsVariations[s]))
2363                      ecflagsVariations[s] = variationNum = ecflagsVariations.count;
2364                   nodeECFlagsMapping[(intptr)this] = variationNum;
2365                }
2366             }
2367
2368             delete cflags;
2369             delete ecflags;
2370          }
2371          else
2372          {
2373             // output
2374             {
2375                nodeCFlagsMapping[(intptr)this] = nodeCFlagsMapping[(intptr)parent];
2376                nodeECFlagsMapping[(intptr)this] = nodeECFlagsMapping[(intptr)parent];
2377             }
2378          }
2379       }
2380       if(files)
2381       {
2382          for(child : files)
2383          {
2384             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
2385                child.GenMakeCollectAssignNodeFlags(prjConfig, prjWithEcFiles,
2386                      cflagsVariations, nodeCFlagsMapping, ecflagsVariations, nodeECFlagsMapping,
2387                      byPlatformOptions);
2388          }
2389       }
2390
2391       if(byPlatformOptions != parentByPlatformOptions)
2392       {
2393          byPlatformOptions.Free();
2394          delete byPlatformOptions;
2395       }
2396    }
2397
2398    Array<Platform> GetPlatformsArrayFromExclusionInfo(ProjectConfig prjConfig)
2399    {
2400       Array<Platform> platforms { };
2401       Map<Platform, SetBool> exclusionInfo { };
2402       CollectExclusionInfo(exclusionInfo, prjConfig);
2403
2404       if(exclusionInfo[unknown] == true)
2405       {
2406          if(exclusionInfo.count > 1)
2407             for(p : exclusionInfo; p == false)
2408                platforms.Add(&p);
2409       }
2410       else
2411       {
2412          bool onlyOnknown = true;
2413          for(p : exclusionInfo)
2414             if(&p != unknown && p == true)
2415             {
2416                onlyOnknown = false;
2417                break;
2418             }
2419          if(onlyOnknown)
2420             platforms.Add(unknown);
2421          else
2422          {
2423             Platform p;
2424             for(p = unknown + 1; p < Platform::enumSize; p++)
2425                if(exclusionInfo[p] != true)
2426                   platforms.Add(p);
2427          }
2428       }
2429       delete exclusionInfo;
2430       return platforms;
2431    }
2432
2433    void GetTargets(ProjectConfig prjConfig, Map<String, NameCollisionInfo> namesInfo, char * objDir, const char * objectFileExt, DynamicString output)
2434    {
2435       char moduleName[MAX_FILENAME];
2436       if(type == file)
2437       {
2438          bool headerAltFailed = false;
2439          bool collision;
2440          char extension[MAX_EXTENSION];
2441          NameCollisionInfo info;
2442          Project prj = property::project;
2443          Map<String, const String> headerToSource { [ { "eh", "ec" }, { "h", "c" }, { "hh", "cc" }, { "hpp", "cpp" }, { "hxx", "cxx" } ] };
2444
2445          GetExtension(name, extension);
2446          strcpy(moduleName, name);
2447          StripExtension(moduleName);
2448          info = namesInfo[moduleName];
2449          collision = info ? info.IsExtensionColliding(extension) : false;
2450
2451          for(h2s : headerToSource)
2452          {
2453             if(!strcmpi(extension, &h2s))
2454             {
2455                char filePath[MAX_LOCATION];
2456                GetFullFilePath(filePath, false);
2457                OutputLog($"No compilation required for header file "); OutputLog(filePath); OutputLog("\n");
2458                ChangeExtension(moduleName, h2s, moduleName);
2459                if(prj.topNode.Find(moduleName, false))
2460                {
2461                   strcpy(extension, h2s);
2462                   collision = info ? info.IsExtensionColliding(extension) : false;
2463                   ChangeExtension(filePath, h2s, filePath);
2464                   OutputLog($"Compiling source file "); OutputLog(filePath); OutputLog($" instead\n");
2465                   StripExtension(moduleName);
2466                }
2467                else
2468                {
2469                   headerAltFailed = true;
2470                   OutputLog($"Unable to locate source file "); OutputLog(moduleName); OutputLog($" to compile instead of "); OutputLog(filePath); OutputLog($"\n");
2471                   StripExtension(moduleName);
2472                }
2473                break;
2474             }
2475          }
2476
2477          if(!headerAltFailed)
2478          {
2479             output.concat(" \"");
2480             output.concat(objDir); //.concat(" $(OBJ)");
2481             output.concat("/");
2482
2483             if(collision)
2484             {
2485                strcat(moduleName, ".");
2486                strcat(moduleName, extension);
2487             }
2488             strcat(moduleName, ".");
2489             strcat(moduleName, objectFileExt);
2490             output.concat(moduleName);
2491             output.concat("\"");
2492          }
2493       }
2494       else if(type == project && ContainsFilesWithExtension("ec", prjConfig))
2495       {
2496          Project prj = property::project;
2497
2498          ReplaceSpaces(moduleName, prj.moduleName);
2499          strcat(moduleName, ".main.ec");
2500          output.concat(" \"");
2501          output.concat(objDir);
2502          output.concat("/");
2503          output.concat(moduleName);
2504          output.concat("\"");
2505
2506          ChangeExtension(moduleName, "c", moduleName);
2507          output.concat(" \"");
2508          output.concat(objDir);
2509          output.concat("/");
2510          output.concat(moduleName);
2511          output.concat("\"");
2512
2513          ChangeExtension(moduleName, "o", moduleName);
2514          output.concat(" \"");
2515          output.concat(objDir);
2516          output.concat("/");
2517          output.concat(moduleName);
2518          output.concat("\"");
2519       }
2520       else if(files)
2521       {
2522          for(child : files)
2523          {
2524             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
2525                child.GetTargets(prjConfig, namesInfo, objDir, objectFileExt, output);
2526          }
2527       }
2528    }
2529
2530    void DeleteIntermediateFiles(CompilerConfig compiler, ProjectConfig prjConfig, int bitDepth, Map<String, NameCollisionInfo> namesInfo, bool onlyCObject)
2531    {
2532       if(type == file)
2533       {
2534          bool collision;
2535          const char * objectFileExt = compiler ? compiler.objectFileExt : objectDefaultFileExt;
2536          char extension[MAX_EXTENSION];
2537          char fileName[MAX_FILENAME];
2538          char moduleName[MAX_FILENAME];
2539          NameCollisionInfo info;
2540          Project prj = property::project;
2541          DirExpression objDir = prj.GetObjDir(compiler, prjConfig, bitDepth);
2542
2543          GetExtension(name, extension);
2544          ReplaceSpaces(moduleName, name);
2545          StripExtension(moduleName);
2546          info = namesInfo[moduleName];
2547          collision = info ? info.IsExtensionColliding(extension) : false;
2548
2549          strcpy(fileName, prj.topNode.path);
2550          PathCatSlash(fileName, objDir.dir);
2551          PathCatSlash(fileName, name);
2552
2553          if(!onlyCObject && !strcmp(extension, "ec"))
2554          {
2555             ChangeExtension(fileName, "c", fileName);
2556             if(FileExists(fileName)) DeleteFile(fileName);
2557             ChangeExtension(fileName, "sym", fileName);
2558             if(FileExists(fileName)) DeleteFile(fileName);
2559             ChangeExtension(fileName, "imp", fileName);
2560             if(FileExists(fileName)) DeleteFile(fileName);
2561             ChangeExtension(fileName, "bowl", fileName);
2562             if(FileExists(fileName)) DeleteFile(fileName);
2563             ChangeExtension(fileName, "ec", fileName);
2564          }
2565
2566          if(collision)
2567          {
2568             strcat(fileName, ".");
2569             strcat(fileName, objectFileExt);
2570          }
2571          else
2572             ChangeExtension(fileName, objectFileExt, fileName);
2573          if(FileExists(fileName)) DeleteFile(fileName);
2574
2575          delete objDir;
2576       }
2577       else if(files)
2578       {
2579          for(child : files)
2580          {
2581             if(child.type != resources && (child.type == folder || !child.GetIsExcluded(prjConfig)))
2582                child.DeleteIntermediateFiles(compiler, prjConfig, bitDepth, namesInfo, onlyCObject);
2583          }
2584       }
2585    }
2586
2587    bool IsInNode(ProjectNode node)
2588    {
2589       bool result = false;
2590       ProjectNode n;
2591       for(n = this; n; n = n.parent)
2592       {
2593          if(n == node)
2594          {
2595             result = true;
2596             break;
2597          }
2598       }
2599       return result;
2600    }
2601 }
2602
2603 // the code in this function is closely matched to OptionsBox::Load
2604 // and accompanying derivations of OptionBox and their use of OptionSet,
2605 // OptionCheck, LoadOption and FinalizeLoading methods.
2606 // output changing modification should be mirrored in both implementations
2607 static ProjectOptions BlendFileConfigPlatformProjectOptions(ProjectNode node, ProjectConfig projectConfig, Platform platform)
2608 {
2609    ProjectOptions output { };
2610
2611    // legend: e Element
2612    //         o Option (of a ProjectOptions)
2613    //         n Node (ProjectNode)
2614    //         p Platform
2615    //         u Utility (GenericOptionTools)
2616
2617    int o;
2618    int priority = 0;
2619    int includeDirsOption = OPTION(includeDirs);
2620    ProjectNode n;
2621    const char * platformName = platform ? platform.OnGetString(0,0,0) : null;
2622
2623    // OPTION(ProjectOptions' last member) for size
2624    Array<bool> optionConfigXplatformSet   { size = OPTION(installCommands) };
2625    Array<bool> optionDone                 { size = OPTION(installCommands) };
2626    Array<Array<String>> optionTempStrings { size = OPTION(installCommands) };
2627
2628    GenericOptionTools<SetBool>              utilSetBool {
2629       bool OptionCheck(ProjectOptions options, int option) {
2630          return *(SetBool*)((byte *)options + option) == true;
2631       }
2632       void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2633          if(options && (*(SetBool*)((byte *)options + option) == true))
2634             *(SetBool*)((byte *)output + option) = true;
2635       }
2636    };
2637    GenericOptionTools<String>               utilString {
2638       void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2639          String * string = (String*)((byte *)output + option);
2640          if(*string) delete *string;
2641          if(options)
2642             *string = CopyString(*(String*)((byte *)options + option));
2643       }
2644    };
2645    StringArrayOptionTools                   utilStringArrays {
2646       mergeValues = true;
2647       caseSensitive = true;
2648       bool OptionCheck(ProjectOptions options, int option) {
2649          Array<String> strings = *(Array<String>*)((byte *)options + option);
2650          return strings && strings.count;
2651       }
2652       bool OptionSet(ProjectOptions options, int option) {
2653          Array<String> strings = *(Array<String>*)((byte *)options + option);
2654          if(mergeValues && !configReplaces)
2655             return strings && strings.count;
2656          else
2657             return strings != null;
2658       }
2659       void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2660          if(mergeValues)
2661          {
2662             Array<String> strings = options ? *(Array<String>*)((byte *)options + option) : null;
2663             if(strings)
2664             {
2665                int order = 0;
2666                Array<String> tempStrings = optionTempStrings[option];
2667                if(!tempStrings)
2668                   optionTempStrings[option] = tempStrings = { };
2669                for(s : strings)
2670                {
2671                   bool found = false;
2672                   char priorityMark[10];
2673                   order++;
2674                   if(priority)
2675                      sprintf(priorityMark, "%06d\n", priority * 1000 + order);
2676                   for(i : tempStrings; !(caseSensitive ? strcmp : strcmpi)(i, s)) { found = true; break; }
2677                   if(!found) tempStrings.Add(priority ? PrintString(priorityMark, s) : CopyString(s));
2678                }
2679             }
2680          }
2681          else
2682          {
2683             Array<String> * newStrings = (Array<String>*)((byte *)options + option);
2684             Array<String> * strings = (Array<String>*)((byte *)output + option);
2685             if(*strings) { strings->Free(); delete *strings; }
2686             if(*newStrings && newStrings->count) { *strings = { }; strings->Copy((void*)*newStrings); }
2687          }
2688       }
2689       void FinalizeLoading(int option, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2690          if(mergeValues)
2691          {
2692             Array<String> tempStrings = optionTempStrings[option];
2693             Array<String> * strings = (Array<String>*)((byte *)output + option);
2694             if(*strings) { strings->Free(); delete *strings; }
2695             if(tempStrings && tempStrings.count) { *strings = { }; strings->Copy((void*)tempStrings); }
2696             delete tempStrings;
2697          }
2698       }
2699    };
2700    GenericOptionTools<WarningsOption>       utilWarningsOption {
2701       bool OptionCheck(ProjectOptions options, int option) {
2702          WarningsOption value = *(WarningsOption*)((byte *)options + option);
2703          return value && value != none;
2704       }
2705       void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2706          WarningsOption value = options ? *(WarningsOption*)((byte *)options + option) : (WarningsOption)0;
2707          *(WarningsOption*)((byte *)output + option) = value;
2708       }
2709    };
2710    GenericOptionTools<OptimizationStrategy> utilOptimizationStrategy {
2711       bool OptionCheck(ProjectOptions options, int option) {
2712          OptimizationStrategy value = *(OptimizationStrategy*)((byte *)options + option);
2713          return value && value != none;
2714       }
2715       void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output) {
2716          OptimizationStrategy value = options ? *(OptimizationStrategy*)((byte *)options + option) : (OptimizationStrategy)0;
2717          *(OptimizationStrategy*)((byte *)output + option) = value;
2718       }
2719    };
2720
2721    Map<int, GenericOptionTools> ot { };
2722
2723    // The following are compiler options
2724
2725    ot[OPTION(debug)] =                   utilSetBool;
2726    ot[OPTION(memoryGuard)] =             utilSetBool;
2727    ot[OPTION(profile)] =                 utilSetBool;
2728    ot[OPTION(noLineNumbers)] =           utilSetBool;
2729    ot[OPTION(strictNameSpaces)] =        utilSetBool;
2730    ot[OPTION(fastMath)] =                utilSetBool;
2731
2732    ot[OPTION(defaultNameSpace)] =        utilString;
2733
2734    ot[OPTION(preprocessorDefinitions)] = utilStringArrays;
2735    ot[OPTION(includeDirs)] =             utilStringArrays;
2736
2737    ot[OPTION(warnings)] =                utilWarningsOption;
2738
2739    ot[OPTION(optimization)] =            utilOptimizationStrategy;
2740
2741    for(n = node; n; n = n.parent)
2742    {
2743       ProjectConfig nodeConfig = null;
2744       if(n.parent)
2745          priority = (priority / 10 + 1) * 10;
2746       else
2747          priority = 9990;
2748       if(projectConfig && n.configurations)
2749       {
2750          for(c : n.configurations; !strcmpi(c.name, projectConfig.name))
2751          {
2752             if(platform && c.platforms)
2753             {
2754                for(p : c.platforms; !strcmpi(p.name, platformName))
2755                {
2756                   for(uu : ot)
2757                   {
2758                      GenericOptionTools u = uu;
2759                      o = &uu;
2760                      if(!optionDone[o] && p.options && (u.mergeValues ? u.OptionCheck(p.options, o) : u.OptionSet(p.options, o)))
2761                      {
2762                         u.LoadOption(p.options, o, o == includeDirsOption ? priority : 0, optionTempStrings, output);
2763                         if(!u.mergeValues) { u.FinalizeLoading(o, optionTempStrings, output); optionDone[o] = true; }
2764                         optionConfigXplatformSet[o] = true;
2765                      }
2766                   }
2767                   break;
2768                }
2769             }
2770             nodeConfig = c;
2771             break;
2772          }
2773       }
2774       for(uu : ot)
2775       {
2776          GenericOptionTools u = uu;
2777          o = &uu;
2778          if(!optionDone[o])
2779          {
2780             if(platform && n.platforms && (!optionConfigXplatformSet[o] || !u.configReplaces))
2781             {
2782                for(p : n.platforms; !strcmpi(p.name, platformName))
2783                {
2784                   if(p.options && (u.mergeValues ? u.OptionCheck(p.options, o) : u.OptionSet(p.options, o)))
2785                   {
2786                      u.LoadOption(p.options, o, o == includeDirsOption ? priority + 1 : 0, optionTempStrings, output);
2787                      if(!u.mergeValues) { u.FinalizeLoading(o, optionTempStrings, output); optionDone[o] = true; }
2788                   }
2789                   break;
2790                }
2791             }
2792             if(!optionDone[o] && nodeConfig && nodeConfig.options &&
2793                   ((u.mergeValues && !u.configReplaces) ?
2794                         u.OptionCheck(nodeConfig.options, o) :
2795                         u.OptionSet(nodeConfig.options, o)))
2796             {
2797                u.LoadOption(nodeConfig.options, o, o == includeDirsOption ? priority : 0, optionTempStrings, output);
2798                if(!u.mergeValues || u.configReplaces) { u.FinalizeLoading(o, optionTempStrings, output); optionDone[o] = true; }
2799             }
2800             if(!optionDone[o])
2801             {
2802                if(n.options && (u.mergeValues ? u.OptionCheck(n.options, o) : u.OptionSet(n.options, o)))
2803                {
2804                   u.LoadOption(n.options, o, o == includeDirsOption ? priority + 1 : 0, optionTempStrings, output);
2805                   if(!u.mergeValues) { u.FinalizeLoading(o, optionTempStrings, output); optionDone[o] = true; }
2806                }
2807                else if(!n.parent)
2808                {
2809                   u.LoadOption(null, o, o == includeDirsOption ? priority + 1 : 0, optionTempStrings, output);
2810                   if(!u.mergeValues) { u.FinalizeLoading(o, optionTempStrings, output); optionDone[o] = true; }
2811                }
2812             }
2813          }
2814       }
2815    }
2816    for(uu : ot)
2817    {
2818       GenericOptionTools u = uu;
2819       o = &uu;
2820       if(!optionDone[o])
2821          u.FinalizeLoading(o, optionTempStrings, output);
2822    }
2823
2824    delete optionConfigXplatformSet;
2825    delete optionDone;
2826    delete optionTempStrings;
2827
2828    delete utilSetBool;
2829    delete utilString;
2830    delete utilStringArrays;
2831    delete utilWarningsOption;
2832    delete utilOptimizationStrategy;
2833
2834    delete ot;
2835
2836    return output;
2837 }
2838
2839 static void CollectPlatformsCommonOptions(Map<Platform, ProjectOptions> byPlatformOptions, ProjectOptions * platformsCommonOptions)
2840 {
2841    ProjectOptions first = null;
2842    ProjectOptions commonOptions;
2843
2844    Map<String, int> countIncludeDirs { };
2845    Map<String, int> countPreprocessorDefinitions { };
2846    Map<String, bool> commonIncludeDirs { };
2847    Map<String, bool> commonPreprocessorDefinitions { };
2848
2849    for(options : byPlatformOptions) { first = options; break; }
2850
2851    *platformsCommonOptions = commonOptions = first ? first.Copy() : { };
2852
2853    if(commonOptions.includeDirs)
2854       commonOptions.includeDirs.Free();
2855    if(commonOptions.preprocessorDefinitions)
2856       commonOptions.preprocessorDefinitions.Free();
2857
2858    for(options : byPlatformOptions)
2859    {
2860       if(options != first)
2861       {
2862          if(commonOptions.debug && options.debug != commonOptions.debug)
2863             commonOptions.debug = unset;
2864          if(commonOptions.memoryGuard && options.memoryGuard != commonOptions.memoryGuard)
2865             commonOptions.memoryGuard = unset;
2866          if(commonOptions.profile && options.profile != commonOptions.profile)
2867             commonOptions.profile = unset;
2868          if(commonOptions.noLineNumbers && options.noLineNumbers != commonOptions.noLineNumbers)
2869             commonOptions.noLineNumbers = unset;
2870          if(commonOptions.strictNameSpaces && options.strictNameSpaces != commonOptions.strictNameSpaces)
2871             commonOptions.strictNameSpaces = unset;
2872          if(commonOptions.fastMath && options.fastMath != commonOptions.fastMath)
2873             commonOptions.fastMath = unset;
2874
2875          if(commonOptions.warnings && options.warnings != commonOptions.warnings)
2876             commonOptions.warnings = unset;
2877          if(commonOptions.optimization && options.optimization != commonOptions.optimization)
2878             commonOptions.optimization = unset;
2879
2880          if(commonOptions.defaultNameSpace && strcmp(options.defaultNameSpace, commonOptions.defaultNameSpace))
2881             delete commonOptions.defaultNameSpace;
2882       }
2883
2884       CountSameNonEmptyOrNullStrings(options.includeDirs, countIncludeDirs);
2885       CountSameNonEmptyOrNullStrings(options.preprocessorDefinitions, countPreprocessorDefinitions);
2886    }
2887
2888    GetPlatformsCommonStrings(countIncludeDirs, byPlatformOptions.count,
2889          commonIncludeDirs, commonOptions.includeDirs);
2890    GetPlatformsCommonStrings(countPreprocessorDefinitions, byPlatformOptions.count,
2891          commonPreprocessorDefinitions, commonOptions.preprocessorDefinitions);
2892
2893    for(options : byPlatformOptions)
2894    {
2895       if(options.debug && options.debug == commonOptions.debug)
2896          options.debug = unset;
2897       if(options.memoryGuard && options.memoryGuard == commonOptions.memoryGuard)
2898          options.memoryGuard = unset;
2899       if(options.profile && options.profile == commonOptions.profile)
2900          options.profile = unset;
2901       if(options.noLineNumbers && options.noLineNumbers == commonOptions.noLineNumbers)
2902          options.noLineNumbers = unset;
2903       if(options.strictNameSpaces && options.strictNameSpaces == commonOptions.strictNameSpaces)
2904          options.strictNameSpaces = unset;
2905       if(options.fastMath && options.fastMath == commonOptions.fastMath)
2906          options.fastMath = unset;
2907
2908       if(options.warnings && options.warnings == commonOptions.warnings)
2909          options.warnings = unset;
2910       if(options.optimization && options.optimization == commonOptions.optimization)
2911          options.optimization = unset;
2912
2913       if(options.defaultNameSpace && !strcmp(options.defaultNameSpace, commonOptions.defaultNameSpace))
2914          delete options.defaultNameSpace;
2915
2916       RemovePlatformsCommonStrings(commonIncludeDirs, options.includeDirs);
2917       RemovePlatformsCommonStrings(commonPreprocessorDefinitions, options.preprocessorDefinitions);
2918    }
2919
2920    delete countIncludeDirs;
2921    delete countPreprocessorDefinitions;
2922    delete commonIncludeDirs;
2923    delete commonPreprocessorDefinitions;
2924 }
2925
2926 static ComplexComparison PlatformsOptionsGreaterEqual(Map<Platform, ProjectOptions> byPlatformOptions,
2927       Map<Platform, ProjectOptions> parentByPlatformOptions,
2928       Map<Platform, ProjectOptions> additionsByPlatformOptions)
2929 {
2930    ComplexComparison result = equal;
2931    ComplexComparison compare;
2932    Platform platform;
2933    for(platform = (Platform)0; platform < Platform::enumSize; platform++)
2934    {
2935       ProjectOptions additionalOptions;
2936       additionsByPlatformOptions[platform] = { };
2937       additionalOptions = additionsByPlatformOptions[platform];
2938       compare = ExtractPlatformsOptionsAdditions(byPlatformOptions[platform], parentByPlatformOptions[platform], additionalOptions);
2939       if(compare == greater && result == equal)
2940          result = greater;
2941       else if(compare == different)
2942       {
2943          result = different;
2944          break;
2945       }
2946    }
2947    return result;
2948 }
2949
2950 static ComplexComparison ExtractPlatformsOptionsAdditions(ProjectOptions options, ProjectOptions parentOptions, ProjectOptions additionalOptions)
2951 {
2952    ComplexComparison result = equal;
2953    if(options.debug != parentOptions.debug ||
2954          options.memoryGuard != parentOptions.memoryGuard ||
2955          options.profile != parentOptions.profile ||
2956          options.noLineNumbers != parentOptions.noLineNumbers ||
2957          options.strictNameSpaces != parentOptions.strictNameSpaces ||
2958          options.fastMath != parentOptions.fastMath ||
2959          options.warnings != parentOptions.warnings ||
2960          options.optimization != parentOptions.optimization ||
2961          (options.defaultNameSpace != parentOptions.defaultNameSpace &&
2962                strcmp(options.defaultNameSpace, parentOptions.defaultNameSpace)))
2963       result = different;
2964    else
2965    {
2966       if(!StringsAreSameOrMore(options.includeDirs, parentOptions.includeDirs, &additionalOptions.includeDirs) ||
2967             !StringsAreSameOrMore(options.preprocessorDefinitions, parentOptions.preprocessorDefinitions, &additionalOptions.preprocessorDefinitions))
2968          result = different;
2969       if((additionalOptions.includeDirs && additionalOptions.includeDirs.count) ||
2970             (additionalOptions.preprocessorDefinitions && additionalOptions.preprocessorDefinitions.count))
2971          result = greater;
2972    }
2973    return result;
2974 }
2975
2976 enum ComplexComparison { different/*, smaller*/, equal, greater };
2977
2978 static bool StringsAreSameOrMore(Array<String> strings, Array<String> originals, Array<String> * additions)
2979 {
2980    bool result = true;
2981    if((!strings || !strings.count) && originals && originals.count)
2982       result = false;
2983    else if(strings && strings.count && (!originals || !originals.count))
2984    {
2985       if(!*additions)
2986          *additions = { };
2987       for(s : strings)
2988          additions->Add(CopyString(s));
2989    }
2990    else if(strings && strings.count && originals && originals.count)
2991    {
2992       Map<String, String> map { };
2993       MapIterator<String, bool> mit { map = map };
2994       for(it : strings)
2995       {
2996          char * s = strstr(it, "\n");
2997          s = s ? s+1 : it;
2998          map[s] = it;
2999       }
3000       for(it : originals)
3001       {
3002          char * s = strstr(it, "\n");
3003          s = s ? s+1 : it;
3004          if(!mit.Index(s, false))
3005          {
3006             result = false;
3007             break;
3008          }
3009          else
3010             map[s] = null;
3011       }
3012       if(result)
3013       {
3014          if(!*additions)
3015             *additions = { };
3016          for(it : map)
3017          {
3018             if(it)
3019                additions->Add(CopyString(it));
3020          }
3021       }
3022       delete map;
3023    }
3024    return result;
3025 }
3026
3027 static void CountSameNonEmptyOrNullStrings(Array<String> strings, Map<String, int> counts)
3028 {
3029    if(strings)
3030    {
3031       for(it : strings)
3032       {
3033          char * s = it;
3034          if(s && s[0])
3035             counts[s]++;
3036       }
3037    }
3038 }
3039
3040 static void GetPlatformsCommonStrings(Map<String, int> counts, int goodCount, Map<String, bool> common, Array<String> strings)
3041 {
3042    for(it : counts)
3043    {
3044       int i = it;
3045       if(i == goodCount)
3046       {
3047          const char * s = &it;
3048          strings.Add(CopyString(s));
3049          common[s] = true;
3050       }
3051    }
3052 }
3053
3054 static void RemovePlatformsCommonStrings(Map<String, bool> common, Array<String> strings)
3055 {
3056    if(strings)
3057    {
3058       Array<String> tmp { };
3059       MapIterator<String, bool> mit { map = common };
3060       for(it : strings)
3061       {
3062          char * s = it;
3063          if(!mit.Index(s, false))
3064             tmp.Add(CopyString(s));
3065       }
3066       strings.Free();
3067       if(tmp.count)
3068       {
3069          for(s : tmp)
3070             strings.Add(CopyString(s));
3071          tmp.Free();
3072       }
3073       delete tmp;
3074    }
3075 }
3076
3077 static void GenMakePrintNodeFlagsVariable(ProjectNode node, Map<intptr, int> nodeFlagsMapping, const String variableName, File f)
3078 {
3079    int customFlags;
3080    customFlags = nodeFlagsMapping[(intptr)node];
3081    if(customFlags > 1)
3082       f.Printf(" $(CUSTOM%d_%s)", customFlags-1, variableName);
3083    else
3084       f.Printf(" $(%s)", variableName);
3085 }
3086
3087 static void DynStringPrintNodeFlagsVariable(ProjectNode node, Map<intptr, int> nodeFlagsMapping, const String variableName, DynamicString s)
3088 {
3089    int customFlags;
3090    customFlags = nodeFlagsMapping[(intptr)node];
3091    if(customFlags > 1)
3092       s.concatf(" $(CUSTOM%d_%s)", customFlags-1, variableName);
3093    else
3094       s.concatf(" $(%s)", variableName);
3095 }
3096
3097 static void GenCFlagsFromProjectOptions(ProjectOptions options, bool prjWithEcFiles, bool commonOptions, bool isGreater, DynamicString s)
3098 {
3099    if(!isGreater)
3100    {
3101       //if(gccCompiler)
3102       {
3103          if(options.optimization == speed || options.optimization == size ||
3104                options.fastMath == true || options.debug == true)
3105          {
3106             if(options.debug != true)
3107             {
3108                s.concat(" $(if $(DEBUG),");
3109                s.concat(" -g");
3110                s.concat(",");
3111             }
3112             switch(options.optimization)
3113             {
3114                case speed: s.concat(" -O2"); break;
3115                case size: s.concat(" -Os"); break;
3116             }
3117             if(options.fastMath == true)
3118                s.concat(" -ffast-math");
3119             if(options.debug == true)
3120                s.concat(" -g");
3121             if(options.debug != true)
3122                s.concat(")");
3123          }
3124          else if(commonOptions)
3125             s.concat(" $(if $(DEBUG),-g)");
3126          if(commonOptions)
3127             s.concat(" $(FPIC)");
3128       }
3129       switch(options.warnings)
3130       {
3131          case all: s.concat(" -Wall"); break;
3132          case none: s.concat(" -w"); break;
3133       }
3134       if(options.profile)
3135          s.concat(" -pg");
3136       if(commonOptions)
3137          s.concat(" -DREPOSITORY_VERSION=\"\\\"$(REPOSITORY_VER)\\\"\"");
3138    }
3139
3140    if(options && options.preprocessorDefinitions)
3141       ListOptionToDynamicString(s, _D, options.preprocessorDefinitions, false, lineEach, "\t\t\t");
3142    if(options && options.includeDirs)
3143       ListOptionToDynamicString(s, _I, options.includeDirs, true, lineEach, "\t\t\t");
3144 }
3145
3146 static void GenECFlagsFromProjectOptions(ProjectOptions options, bool prjWithEcFiles, DynamicString s)
3147 {
3148    if(options.memoryGuard == true)
3149       s.concat(" -memguard");
3150    if(options.noLineNumbers == true)
3151       s.concat(" -nolinenumbers");
3152    if(options.strictNameSpaces == true)
3153       s.concat(" -strictns");
3154    if(options.defaultNameSpace && options.defaultNameSpace[0])
3155       s.concatf(" -defaultns %s", options.defaultNameSpace);
3156 }
3157
3158 static void ListOptionToDynamicString(DynamicString output, ToolchainFlag flag, Array<String> list, bool prioritize,
3159       LineOutputMethod lineMethod, const String newLineStart)
3160 {
3161    if(list.count)
3162    {
3163       if(lineMethod == newLine)
3164       {
3165          output.concat(" \\\n");
3166          output.concat(newLineStart);
3167       }
3168       if(prioritize)
3169       {
3170          Map<String, int> sortedList { };
3171          MapNode<String, int> mn;
3172          for(item : list)
3173             sortedList[item] = 1;
3174          for(mn = sortedList.root.minimum; mn; mn = mn.next)
3175          {
3176             char * start = strstr(mn.key, "\n");
3177             if(lineMethod == lineEach)
3178             {
3179                output.concat(" \\\n");
3180                output.concat(newLineStart);
3181             }
3182             output.concat(" ");
3183             output.concat(flagNames[flag]);
3184             EscapeForMakeToDynString(output, start ? start+1 : mn.key, false, true, flag == _D);
3185          }
3186          delete sortedList;
3187       }
3188       else
3189       {
3190          for(item : list)
3191          {
3192             if(lineMethod == lineEach)
3193             {
3194                output.concat(" \\\n");
3195                output.concat(newLineStart);
3196             }
3197             output.concat(" ");
3198             output.concat(flagNames[flag]);
3199             EscapeForMakeToDynString(output, item, false, true, flag == _D);
3200          }
3201       }
3202    }
3203 }
3204
3205 class GenericOptionTools<class X>
3206 {
3207    bool mergeValues, configReplaces;
3208
3209    virtual bool OptionSet(ProjectOptions options, int option) {
3210       if(*(X*)((byte *)options + option))
3211          return true;
3212       return false;
3213    }
3214
3215    // BUG: OptionCheck = OptionSet; // Overrides derived classes OptionCheck ?
3216
3217    virtual bool OptionCheck(ProjectOptions options, int option) {
3218       return OptionSet(options, option);
3219    }
3220
3221    virtual void LoadOption(ProjectOptions options, int option, int priority, Array<Array<String>> optionTempStrings, ProjectOptions output);
3222    virtual void FinalizeLoading(int option, Array<Array<String>> optionTempStrings, ProjectOptions output);
3223 }
3224
3225 class StringArrayOptionTools : GenericOptionTools<Array<String>>
3226 {
3227    bool caseSensitive;
3228 }
3229
3230 class NameCollisionInfo
3231 {
3232    bool ec;
3233    bool s;
3234    bool c;
3235    bool rc;
3236    bool cpp;
3237    bool cc;
3238    bool cxx;
3239    bool m;
3240    bool mm;
3241    byte count;
3242
3243    bool IsExtensionColliding(char * extension)
3244    {
3245       bool colliding;
3246       if(count > 1 &&
3247             ((!strcmpi(extension, "c")   && ec) ||
3248              (!strcmpi(extension, "rc")  && (ec || c)) ||
3249              (!strcmpi(extension, "s")   && (ec || c || rc)) ||
3250              (!strcmpi(extension, "cpp") && (ec || c || rc || s)) ||
3251              (!strcmpi(extension, "cc")  && (ec || c || rc || s || cpp)) ||
3252              (!strcmpi(extension, "cxx") && (ec || c || rc || s || cpp || cc)) ||
3253              (!strcmpi(extension, "m")   && (ec || c || rc || s || cpp || cc || m)) ||
3254               !strcmpi(extension, "mm")))
3255          colliding = true;
3256       else
3257          colliding = false;
3258      return colliding;
3259    }
3260 }