Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gensources.cs « build « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d55c627d4dcf69522a27681df3dfab3837ff7f60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public static class Program {
    public static int Main (string[] _args) {
        var args = new List<string> (_args);
        bool useStdout = false, showHelp = false, strictMode = false;

        for (int i = 0; i < args.Count; i++) {
            var arg = args[i];
            if (!arg.StartsWith ("-"))
                continue;

            switch (arg) {
                case "-?":
                case "--help":
                case "-h":
                    showHelp = true;
                    break;
                case "--trace":
                case "--trace1":
                    SourcesParser.TraceLevel = 1;
                    break;
                case "--trace2":
                    SourcesParser.TraceLevel = 2;
                    break;
                case "--trace3":
                    SourcesParser.TraceLevel = 3;
                    break;
                case "--trace4":
                    SourcesParser.TraceLevel = 4;
                    break;
                case "--stdout":
                    useStdout = true;
                    break;
                case "--strict":
                    strictMode = true;
                    break;
                default:
                    Console.Error.WriteLine ("Unrecognized switch " + arg);
                    break;
            }

            args.RemoveAt (i);
            i--;            
        }

        if (args.Count != 4)
            showHelp = true;

        if (showHelp) {
            Console.Error.WriteLine ("Usage: mcs/build/gensources.exe [options] (outputFileName|--stdout) libraryDirectoryAndName platformName profileName");
            Console.Error.WriteLine ("You can specify * for platformName and profileName to read all sources files");
            Console.Error.WriteLine ("Available options:");
            Console.Error.WriteLine ("--help -h -?");
            Console.Error.WriteLine ("  Show command line info");
            Console.Error.WriteLine ("--trace1 --trace2 --trace3 --trace4");
            Console.Error.WriteLine ("  Enable diagnostic output");
            Console.Error.WriteLine ("--stdout");
            Console.Error.WriteLine ("  Writes results to standard output (omit outputFileName if you use this)");
            Console.Error.WriteLine ("--strict");
            Console.Error.WriteLine ("  Produces an error exit code if files or directories are invalid/missing");
            return 1;
        }

        var myAssembly = Assembly.GetExecutingAssembly ();
        var codeBase = new Uri (myAssembly.CodeBase);
        var executablePath = Path.GetFullPath (codeBase.LocalPath);
        var executableDirectory = Path.GetDirectoryName (executablePath);

        var outFile = Path.GetFullPath (args[0]);
        var libraryFullName = Path.GetFullPath (args[1]);
        var platformName = args[2];
        var profileName = args[3];
        var platformsFolder = Path.Combine (executableDirectory, "platforms");
        var profilesFolder = Path.Combine (executableDirectory, "profiles");

        var libraryDirectory = Path.GetDirectoryName (libraryFullName);
        var libraryName = Path.GetFileName (libraryFullName);

        var parser = new SourcesParser (platformsFolder, profilesFolder);
        var result = parser.Parse (libraryDirectory, libraryName, platformName, profileName);

        if (SourcesParser.TraceLevel > 0)
            Console.Error.WriteLine ($"// Writing sources for platform {platformName} and profile {profileName}, relative to {libraryDirectory}, to {outFile}.");

        TextWriter output;
        if (useStdout)
            output = Console.Out;
        else
            output = new StreamWriter (outFile);

        using (output) {
            foreach (var fileName in result.GetFileNames ().OrderBy (s => s, StringComparer.Ordinal))
                output.WriteLine (fileName);
        }

        if (strictMode)
            return result.ErrorCount;
        else
            return 0;
    }
}

public struct ParseEntry {
    public string SourcesFileName;
    public string Directory;
    public string Pattern;
    public string HostPlatform;
    public string ProfileName;
}

public struct Source {
    public string FileName;
}

public class ParseResult {
    public readonly string LibraryDirectory, LibraryName;

    public readonly List<ParseEntry> Sources = new List<ParseEntry> ();
    public readonly List<ParseEntry> Exclusions = new List<ParseEntry> ();

    // FIXME: This is a bad spot for this value but enumerators don't have outparam support
    public int ErrorCount = 0;

    public ParseResult (string libraryDirectory, string libraryName) {
        LibraryDirectory = libraryDirectory;
        LibraryName = libraryName;
    }

    private static string GetRelativePath (string fullPath, string relativeToDirectory) {
        fullPath = fullPath.Replace (SourcesParser.DirectorySeparator, "/");
        relativeToDirectory = relativeToDirectory.Replace (SourcesParser.DirectorySeparator, "/");

        if (!relativeToDirectory.EndsWith (SourcesParser.DirectorySeparator))
            relativeToDirectory += SourcesParser.DirectorySeparator;
        var dirUri = new Uri (relativeToDirectory);
        var pathUri = new Uri (fullPath);

        var relativeUri = Uri.UnescapeDataString (
            dirUri.MakeRelativeUri (pathUri).OriginalString
        ).Replace ("/", SourcesParser.DirectorySeparator);

        if (SourcesParser.TraceLevel >= 4)
            Console.Error.WriteLine ($"// {fullPath} -> {relativeUri}");

        return relativeUri;
    }

    private IEnumerable<string> EnumerateMatches (
        IEnumerable<ParseEntry> entries,
        string hostPlatformName, string profileName
    ) {
        foreach (var entry in entries) {
            if (
                (hostPlatformName != null) &&
                (entry.HostPlatform ?? hostPlatformName) != hostPlatformName
            )
                continue;
            if (
                (profileName != null) &&
                (entry.ProfileName ?? profileName) != profileName
            )
                continue;

            var absolutePath = Path.Combine (entry.Directory, entry.Pattern);
            var absoluteDirectory = Path.GetDirectoryName (absolutePath);
            var absolutePattern = Path.GetFileName (absolutePath);

            if (SourcesParser.TraceLevel >= 3) {
                if ((absolutePattern != entry.Pattern) || (absoluteDirectory != entry.Directory))
                    Console.Error.WriteLine ($"// {entry.Directory} / {entry.Pattern} -> {absoluteDirectory} / {absolutePattern}");
            }            

            if (!Directory.Exists (absoluteDirectory)) {
                Console.Error.WriteLine ($"Directory does not exist: {Path.GetFullPath (absoluteDirectory)}");
                ErrorCount += 1;
                continue;
            }

            var matchingFiles = Directory.GetFiles (absoluteDirectory, absolutePattern);
            foreach (var fileName in matchingFiles) {
                var relativePath = GetRelativePath (fileName, LibraryDirectory);
                yield return relativePath;
            }
        }
    }

    // If you loaded sources files for multiple profiles, you can use the arguments here
    //  to filter the results
    public IEnumerable<string> GetFileNames (
        string hostPlatformName = null, string profileName = null
    ) {
        var encounteredFileNames = new HashSet<string> (StringComparer.Ordinal);

        var excludedFiles = new HashSet<string> (
            EnumerateMatches (Exclusions, hostPlatformName, profileName),
            StringComparer.Ordinal
        );

        foreach (var fileName in EnumerateMatches (Sources, hostPlatformName, profileName)) {
            if (excludedFiles.Contains (fileName)) {
                if (SourcesParser.TraceLevel >= 3)
                    Console.Error.WriteLine ($"// Excluding {fileName}");
                continue;
            }

            // Skip duplicates
            if (encounteredFileNames.Contains (fileName))
                continue;

            encounteredFileNames.Add (fileName);
            yield return fileName;
        }
    }
}

public class SourcesParser {
    public static readonly string DirectorySeparator = new String (Path.DirectorySeparatorChar, 1);    
    public static int TraceLevel = 0;

    private class State {
        public ParseResult Result;
        public string HostPlatform;
        public string ProfileName;

        public int SourcesFilesParsed, ExclusionsFilesParsed;

        public List<ParseEntry> ParsedSources {
            get {
                return Result.Sources;
            }
        }

        public List<ParseEntry> ParsedExclusions {
            get {
                return Result.Exclusions;
            }
        }
    }

    public readonly string[] AllHostPlatformNames;
    public readonly string[] AllProfileNames;

    private int ParseDepth = 0;

    public SourcesParser (
        string platformsFolder, string profilesFolder
    ) {
        AllHostPlatformNames = Directory.GetFiles (platformsFolder, "*.make")
            .Select (Path.GetFileNameWithoutExtension)
            .ToArray ();
        AllProfileNames = Directory.GetFiles (profilesFolder, "*.make")
            .Select (Path.GetFileNameWithoutExtension)
            .ToArray ();
    }

    public ParseResult Parse (string libraryDirectory, string libraryName, string hostPlatform, string profile) {
        var state = new State {
            Result = new ParseResult (libraryDirectory, libraryName),
            ProfileName = profile,
            HostPlatform = hostPlatform
        };

        var testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{profile}_{libraryName}");
        var ok = TryParseSingleFile (state, testPath + ".sources", false);
        TryParseSingleFile (state, testPath + ".exclude.sources", true);

        if (ok) {
            PrintSummary (state);
            return state.Result;
        }

        state.HostPlatform = null;

        testPath = Path.Combine (libraryDirectory, $"{profile}_{libraryName}");
        ok = TryParseSingleFile (state, testPath + ".sources", false);
        TryParseSingleFile (state, testPath + ".exclude.sources", true);

        if (ok) {
            PrintSummary (state);
            return state.Result;
        }

        state.ProfileName = null;

        testPath = Path.Combine (libraryDirectory, libraryName);
        TryParseSingleFile (state, testPath + ".sources", false);
        TryParseSingleFile (state, testPath + ".exclude.sources", true);

        PrintSummary (state);

        return state.Result;
    }

    public ParseResult Parse (string libraryDirectory, string libraryName) {
        var state = new State {
            Result = new ParseResult (libraryDirectory, libraryName)
        };

        string testPath = Path.Combine (libraryDirectory, libraryName);
        TryParseSingleFile (state, testPath + ".sources", false);
        TryParseSingleFile (state, testPath + ".exclude.sources", true);

        foreach (var profile in AllProfileNames) {
            state.ProfileName = profile;

            foreach (var hostPlatform in AllHostPlatformNames) {
                state.HostPlatform = hostPlatform;

                testPath = Path.Combine (libraryDirectory, $"{hostPlatform}_{profile}_{libraryName}");
                TryParseSingleFile (state, testPath + ".sources", false);
                TryParseSingleFile (state, testPath + ".exclude.sources", true);
            }

            state.HostPlatform = null;

            testPath = Path.Combine (libraryDirectory, $"{profile}_{libraryName}");
            TryParseSingleFile (state, testPath + ".sources", false);
            TryParseSingleFile (state, testPath + ".exclude.sources", true);
        }

        PrintSummary (state);

        return state.Result;
    }

    private void PrintSummary (State state) {
        if (TraceLevel > 0)
            Console.Error.WriteLine ($"// Parsed {state.SourcesFilesParsed} sources file(s) and {state.ExclusionsFilesParsed} exclusions file(s).");
    }

    private void HandleMetaDirective (State state, string directory, bool asExclusionsList, string directive) {
        var include = "#include ";
        if (directive.StartsWith (include))
            ParseSingleFile (state, Path.Combine (directory, directive.Substring (include.Length)), asExclusionsList);
    }

    private bool TryParseSingleFile (State state, string fileName, bool asExclusionsList) {
        if (!File.Exists (fileName))
            return false;

        ParseSingleFile (state, fileName, asExclusionsList);
        return true;
    }

    private void ParseSingleFile (State state, string fileName, bool asExclusionsList) {
        var nullStr = "<none>";
        if (TraceLevel >= 1)
            Console.Error.WriteLine ($"// {new String (' ', ParseDepth * 2)}{fileName}  [{state.HostPlatform ?? nullStr}] [{state.ProfileName ?? nullStr}]");
        ParseDepth += 1;

        var directory = Path.GetDirectoryName (fileName);

        using (var sr = new StreamReader (fileName)) {
            if (asExclusionsList)
                state.ExclusionsFilesParsed++;
            else
                state.SourcesFilesParsed++;

            string line;
            while ((line = sr.ReadLine ()) != null) {
                if (String.IsNullOrWhiteSpace (line))
                    continue;

                if (line.StartsWith ("#")) {
                    HandleMetaDirective (state, directory, asExclusionsList, line);
                    continue;
                }

                var parts = line.Split (':');

                if (parts.Length > 1) {
                    var explicitExclusions = parts[1].Split (',');

                    // gensources.sh implemented these explicit exclusions like so:
                    // ../foo/bar/*.cs:A.cs,B.cs
                    // This would generate exclusions for ../foo/bar/A.cs and ../foo/bar/B.cs,
                    //  not ./A.cs and ./B.cs as you might expect

                    var mainPatternDirectory = Path.GetDirectoryName (parts[0]);

                    foreach (var pattern in explicitExclusions) {
                        state.ParsedExclusions.Add (new ParseEntry {
                            SourcesFileName = fileName,
                            Directory = directory,
                            Pattern = Path.Combine (mainPatternDirectory, pattern),
                            HostPlatform = state.HostPlatform,
                            ProfileName = state.ProfileName
                        });
                    }
                }

                (asExclusionsList ? state.ParsedExclusions : state.ParsedSources)
                    .Add (new ParseEntry {
                        SourcesFileName = fileName,
                        Directory = directory,
                        Pattern = parts[0],
                        HostPlatform = state.HostPlatform,
                        ProfileName = state.ProfileName
                    });
            }
        }

        ParseDepth -= 1;
    }
}