Exemple #1
0
        static void Main(string[] args)
        {
            var generator = new MbedBSPGenerator("5.9.2");

            bool skipRescan = args.Contains("/norescan");

            string suffix = "";

            generator.UpdateGitAndRescanTargets(skipRescan);

            ParsedTargetList parsedTargets = XmlTools.LoadObject <ParsedTargetList>(Path.Combine(generator.outputDir, "mbed", "ParsedTargets.xml"));

            generator.PatchBuggyFiles();

            BoardSupportPackage bsp = new BoardSupportPackage
            {
                PackageID            = "com.sysprogs.arm.mbed",
                PackageDescription   = "ARM mbed",
                PackageVersion       = generator.Version + suffix,
                GNUTargetID          = "arm-eabi",
                GeneratedMakFileName = "mbed.mak",
                BSPSourceFolderName  = "mbed Files"
            };

            var validTargets = parsedTargets.Targets.Where(t => t.BaseConfiguration != null).ToArray();

            MCUFamily commonFamily = new MCUFamily
            {
                ID = "MBED_CORE",
                AdditionalSourceFiles         = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.SourceFiles))),
                AdditionalHeaderFiles         = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.HeaderFiles))),
                SymbolsRequiredByLinkerScript = new[] { "__Vectors", "Stack_Size" },
                CompilationFlags = new ToolFlags
                {
                    IncludeDirectories = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.IncludeDirectories))),
                    PreprocessorMacros = Intersect(validTargets.Select(t => t.BaseConfiguration.EffectivePreprocessorMacros))
                }
            };

            bsp.MCUFamilies = new[] { commonFamily };

            List <MCU> mcus = new List <MCU>();
            Dictionary <string, ConditionalConfigAggregator> libraryAndFeatureConfigs = new Dictionary <string, ConditionalConfigAggregator>();

            Console.WriteLine("Generating target definitions...");

            foreach (var target in validTargets)
            {
                if (string.IsNullOrEmpty(target.BaseConfiguration.LinkerScript))
                {
                    Console.WriteLine($"Skipping {target.ID}: no linker script defined");
                    continue;
                }

                var mcu = new MCU
                {
                    FamilyID = commonFamily.ID,
                    ID       = target.ID,
                    AdditionalSourceFiles = generator.ConvertPaths(target.BaseConfiguration.SourceFiles),
                    AdditionalHeaderFiles = generator.ConvertPaths(target.BaseConfiguration.HeaderFiles),
                    CompilationFlags      = new ToolFlags
                    {
                        IncludeDirectories = generator.ConvertPaths(target.BaseConfiguration.IncludeDirectories),
                        PreprocessorMacros = target.BaseConfiguration.EffectivePreprocessorMacros,
                        LinkerScript       = generator.ConvertPaths(new[] { target.BaseConfiguration.LinkerScript })[0],
                        COMMONFLAGS        = target.CFLAGS.Replace(';', ' '),
                    },
                    ConfigurableProperties = new PropertyList
                    {
                        PropertyGroups = new List <PropertyGroup>
                        {
                            new PropertyGroup
                            {
                                UniqueID   = "com.sysprogs.mbed.",
                                Properties = target.BaseConfiguration.EffectiveConfigurableProperties.ToList()
                            }
                        }
                    }
                };

                generator.DetectAndApplyMemorySizes(mcu, target.BaseConfiguration.LinkerScript);

                if (mcu.CompilationFlags.COMMONFLAGS.Contains("-mfloat-abi"))
                {
                    string[] flags        = mcu.CompilationFlags.COMMONFLAGS.Split(' ');
                    string   defaultValue = flags.First(f => f.StartsWith("-mfloat-abi"));

                    var property = new PropertyEntry.Enumerated
                    {
                        Name           = "Floating point support",
                        UniqueID       = "floatmode",
                        SuggestionList = new PropertyEntry.Enumerated.Suggestion[]
                        {
                            new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = "-mfloat-abi=soft", UserFriendlyName = "Software"
                            },
                            new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = "-mfloat-abi=hard", UserFriendlyName = "Hardware"
                            },
                            new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = "-mfloat-abi=softfp", UserFriendlyName = "Hardware with Software interface"
                            },
                            new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = "", UserFriendlyName = "Unspecified"
                            },
                        },
                    };

                    property.DefaultEntryIndex = Enumerable.Range(0, property.SuggestionList.Length).First(i => property.SuggestionList[i].InternalValue == defaultValue);
                    flags[Array.IndexOf(flags, defaultValue)] = "$$" + mcu.ConfigurableProperties.PropertyGroups[0].UniqueID + property.UniqueID + "$$";
                    mcu.CompilationFlags.COMMONFLAGS          = string.Join(" ", flags);
                    mcu.ConfigurableProperties.PropertyGroups[0].Properties.Add(property);
                }

                mcu.AdditionalSourceFiles = mcu.AdditionalSourceFiles.Except(commonFamily.AdditionalSourceFiles).ToArray();
                mcu.AdditionalHeaderFiles = mcu.AdditionalHeaderFiles.Except(commonFamily.AdditionalHeaderFiles).ToArray();
                mcu.CompilationFlags.IncludeDirectories = mcu.CompilationFlags.IncludeDirectories.Except(commonFamily.CompilationFlags.IncludeDirectories).ToArray();
                mcu.CompilationFlags.PreprocessorMacros = mcu.CompilationFlags.PreprocessorMacros.Except(commonFamily.CompilationFlags.PreprocessorMacros).ToArray();

                foreach (var cfg in target.DerivedConfigurations)
                {
                    cfg.MergeScatteredConfigurations();

                    ConditionalConfigAggregator agg;
                    if (!libraryAndFeatureConfigs.TryGetValue(cfg.CanonicalKey, out agg))
                    {
                        agg = libraryAndFeatureConfigs[cfg.CanonicalKey] = new ConditionalConfigAggregator(cfg);
                    }

                    agg.AddedSettingsPerTargets[target.ID] = cfg.Configuration.Subtract(target.BaseConfiguration, cfg.CanonicalKey, cfg.Library != null);
                }

                if (!generator.ConvertSoftdevicesAndPatchTarget(mcu, target.BaseConfiguration.HexFiles))
                {
                    mcu.CompilationFlags.LinkerScript = generator.ConvertPath(generator.PreprocessLinkerScriptIfNeeded(mcu.CompilationFlags.LinkerScript));
                }

                generator.CopyAndAttachRegisterDefinitions(mcu);
                mcus.Add(mcu);
            }

            bsp.SupportedMCUs = mcus.ToArray();
            List <FileCondition>        fileConditions   = new List <FileCondition>();
            List <ConditionalToolFlags> conditionalFlags = new List <ConditionalToolFlags>();
            List <EmbeddedFramework>    frameworks       = new List <EmbeddedFramework>();

            Console.WriteLine("Merging library build settings...");

            foreach (var agg in libraryAndFeatureConfigs.Values)
            {
                EmbeddedFramework framework = new EmbeddedFramework
                {
                    ID = agg.ID,
                    UserFriendlyName             = agg.Name,
                    AdditionalSourceFiles        = generator.ConvertPaths(Union(agg.AddedSettingsPerTargets.Values.Select(t => t.SourceFiles))),
                    AdditionalHeaderFiles        = generator.ConvertPaths(Union(agg.AddedSettingsPerTargets.Values.Select(t => t.HeaderFiles))),
                    AdditionalIncludeDirs        = generator.ConvertPaths(Intersect(agg.AddedSettingsPerTargets.Values.Select(t => t.IncludeDirectories))),
                    AdditionalPreprocessorMacros = Intersect(agg.AddedSettingsPerTargets.Values.Select(t => t.EffectivePreprocessorMacros)),
                };

                var properties = Union(agg.AddedSettingsPerTargets.Values.Select(t => t.EffectiveConfigurableProperties), new PropertyComparerByID()).ToList();
                if (properties.Count > 0)
                {
                    framework.ConfigurableProperties = new PropertyList
                    {
                        PropertyGroups = new List <PropertyGroup>
                        {
                            new PropertyGroup
                            {
                                UniqueID   = "com.sysprogs.mbed.",
                                Properties = properties
                            }
                        }
                    }
                }
                ;

                foreach (var file in framework.AdditionalSourceFiles.Concat(framework.AdditionalHeaderFiles))
                {
                    var targetsWhereIncluded = agg.AddedSettingsPerTargets
                                               .Where(v => generator.ConvertPaths(v.Value.SourceFiles.Concat(v.Value.HeaderFiles)).Contains(file))
                                               .Select(kv => kv.Key)
                                               .ToArray();

                    if (targetsWhereIncluded.Length == agg.AddedSettingsPerTargets.Count)
                    {
                        continue;   //The file is included on all targets
                    }
                    fileConditions.Add(new FileCondition {
                        FilePath = file, ConditionToInclude = new Condition.MatchesRegex {
                            Expression = "$$SYS:MCU_ID$$", Regex = "^(" + string.Join("|", targetsWhereIncluded) + ")$"
                        }
                    });
                }


                foreach (var kv in agg.AddedSettingsPerTargets)
                {
                    var extraIncludeDirs        = generator.ConvertPaths(kv.Value.IncludeDirectories).Except(framework.AdditionalIncludeDirs).ToArray();
                    var extraPreprocessorMacros = kv.Value.EffectivePreprocessorMacros.Except(framework.AdditionalPreprocessorMacros).ToArray();
                    if (extraIncludeDirs.Length == 0 && extraPreprocessorMacros.Length == 0)
                    {
                        continue;
                    }

                    ToolFlags flags = new ToolFlags();
                    if (extraIncludeDirs.Length > 0)
                    {
                        flags.IncludeDirectories = extraIncludeDirs;
                    }
                    if (extraPreprocessorMacros.Length > 0)
                    {
                        flags.PreprocessorMacros = extraPreprocessorMacros;
                    }

                    conditionalFlags.Add(new ConditionalToolFlags
                    {
                        Flags         = flags,
                        FlagCondition = new Condition.And
                        {
                            Arguments = new Condition[]
                            {
                                new Condition.ReferencesFramework {
                                    FrameworkID = framework.ID
                                },
                                new Condition.Equals {
                                    Expression = "$$SYS:MCU_ID$$", ExpectedValue = kv.Key
                                }
                            }
                        }
                    });
                }

                frameworks.Add(framework);
            }

            bsp.FileConditions   = fileConditions.ToArray();
            bsp.ConditionalFlags = conditionalFlags.ToArray();
            bsp.Frameworks       = frameworks.ToArray();
            bsp.Examples         = generator.DetectSampleDirs();

            generator.ProduceBSPArchive(bsp);

            bool performTests = true;

            if (performTests)
            {
                RunTests(generator);
            }
        }
Exemple #2
0
        public ToolFlags CopyAndBuildFlags(BSPBuilder bsp, List <string> projectFiles, string subdir, ref PropertyList configurableProperties)
        {
            List <ParsedCondition> conditions    = null;
            List <string>          allConditions = new List <string>();

            if (SimpleFileConditions != null)
            {
                allConditions.AddRange(SimpleFileConditions);
            }
            if (SmartFileConditions != null)
            {
                foreach (var str in SmartFileConditions)
                {
                    int      idx    = str.IndexOf('|');
                    string   name   = str.Substring(0, idx);
                    string   id     = "com.sysprogs.bspoptions." + name.Replace(' ', '_');
                    string[] values = str.Substring(idx + 1).Split(';');

                    PropertyEntry entry;
                    if (values.Length == 1)
                    {
                        var    val = values[0];
                        string regex, value;
                        idx = val.IndexOf("=>");
                        if (idx == -1)
                        {
                            regex = val;
                            value = "1";
                        }
                        else
                        {
                            regex = val.Substring(0, idx);
                            value = val.Substring(idx + 2);
                        }

                        allConditions.Add($"{regex}: $${id}$$ == {value}");

                        entry = new PropertyEntry.Boolean {
                            ValueForTrue = value, Name = name, UniqueID = id, DefaultValue = true
                        };
                    }
                    else
                    {
                        List <PropertyEntry.Enumerated.Suggestion> suggestions = new List <PropertyEntry.Enumerated.Suggestion>();

                        foreach (var val in values)
                        {
                            idx = val.IndexOf("=>");
                            string regex = val.Substring(0, idx);
                            string value = val.Substring(idx + 2);
                            allConditions.Add($"{regex}: $${id}$$ == {value}");
                            suggestions.Add(new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = value
                            });
                        }

                        entry = new PropertyEntry.Enumerated {
                            Name = name, UniqueID = id, SuggestionList = suggestions.ToArray()
                        };
                    }

                    if (configurableProperties?.PropertyGroups == null)
                    {
                        configurableProperties = new PropertyList {
                            PropertyGroups = new List <PropertyGroup>()
                        }
                    }
                    ;

                    var grp = configurableProperties.PropertyGroups.FirstOrDefault(g => g.Name == null && g.UniqueID == null);
                    if (grp == null)
                    {
                        configurableProperties.PropertyGroups.Insert(0, grp = new PropertyGroup());
                    }

                    grp.Properties.Add(entry);
                }
            }

            if (allConditions.Count > 0)
            {
                conditions = new List <ParsedCondition>();
                foreach (var cond in allConditions)
                {
                    int idx = cond.IndexOf(':');
                    if (idx == -1)
                    {
                        throw new Exception("Invalid simple condition format");
                    }

                    Regex     rgFile     = new Regex(cond.Substring(0, idx), RegexOptions.IgnoreCase);
                    string    rawCond    = cond.Substring(idx + 1).Trim();
                    Condition parsedCond = ParseCondition(rawCond);
                    conditions.Add(new ParsedCondition {
                        Regex = rgFile, Condition = parsedCond
                    });
                }
            }

            string expandedSourceFolder = SourceFolder;

            bsp.ExpandVariables(ref expandedSourceFolder);

            if (TargetFolder == null)
            {
                TargetFolder = Path.GetFileName(expandedSourceFolder);
            }
            TargetFolder = TargetFolder.Replace('\\', '/');
            if (subdir == null)
            {
                subdir = "";
            }
            string absTarget = Path.Combine(bsp.BSPRoot, subdir, TargetFolder);

            Directory.CreateDirectory(absTarget);

            string folderInsideBSPPrefix = TargetFolder;

            if (!string.IsNullOrEmpty(subdir))
            {
                folderInsideBSPPrefix = subdir + "/" + TargetFolder;
            }
            folderInsideBSPPrefix = folderInsideBSPPrefix.Replace('\\', '/');
            if (folderInsideBSPPrefix == "/")
            {
                folderInsideBSPPrefix = "";
            }
            else if (folderInsideBSPPrefix != "" && !folderInsideBSPPrefix.StartsWith("/"))
            {
                folderInsideBSPPrefix = "/" + folderInsideBSPPrefix;
            }

            var copyMasks         = new CopyFilters(FilesToCopy);
            var autoIncludes      = new CopyFilters(AutoIncludeMask);
            var potentialSymlinks = new CopyFilters(SymlinkResolutionMask);
            var projectContents   = new CopyFilters(ProjectInclusionMask);
            var filesToCopy       = Directory.GetFiles(expandedSourceFolder, "*", SearchOption.AllDirectories).Select(f => f.Substring(expandedSourceFolder.Length + 1)).Where(f => copyMasks.IsMatch(f)).ToArray();

            foreach (var dir in filesToCopy.Select(f => Path.Combine(absTarget, Path.GetDirectoryName(f))).Distinct())
            {
                Directory.CreateDirectory(dir);
            }

            List <IRenameRule> rules = new List <IRenameRule>();

            foreach (var r in (RenameRules ?? "").Split(';').Where(s => s != ""))
            {
                int idx = r.IndexOf("=>");
                rules.Add(new RenameRule {
                    OldName = r.Substring(0, idx), NewName = r.Substring(idx + 2)
                });
            }
            foreach (var r in (AdvancedRenameRules ?? "").Split(';').Where(s => s != ""))
            {
                int idx = r.IndexOf("=>");
                rules.Add(new AdvancedRenamingRule {
                    OldName = new Regex(r.Substring(0, idx), RegexOptions.IgnoreCase), NewNameFormat = r.Substring(idx + 2)
                });
            }

            var includeDirs = filesToCopy.Where(f => autoIncludes.IsMatch(f)).Select(f => Path.GetDirectoryName(f).Replace('\\', '/')).Distinct().Select(d => "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + (string.IsNullOrEmpty(d) ? "" : ("/" + d))).ToList();

            foreach (var f in filesToCopy)
            {
                string renamedRelativePath = f;
                string pathInsidePackage   = Path.Combine(subdir, TargetFolder, f);
                if (pathInsidePackage.Length > 120)
                {
                    if (!bsp.OnFilePathTooLong(pathInsidePackage))
                    {
                        continue;
                    }
                }

                string targetFile = Path.Combine(absTarget, f);
                string newName    = rules?.FirstOrDefault(r => r.Matches(f))?.Apply(targetFile);

                if (newName == null)
                {
                    if (bsp.RenamedFileTable.TryGetValue(targetFile, out newName) || bsp.RenamedFileTable.TryGetValue(targetFile.Replace('/', '\\'), out newName))
                    {
                    }
                }

                if (newName != null)
                {
                    var oldTargetFile = targetFile;
                    targetFile          = Path.Combine(Path.GetDirectoryName(targetFile), newName);
                    renamedRelativePath = Path.Combine(Path.GetDirectoryName(renamedRelativePath), newName);
                    bsp.RenamedFileTable[oldTargetFile] = newName;
                }

                if (AlreadyCopied)
                {
                    if (!File.Exists(targetFile))
                    {
                        throw new Exception(targetFile + " required by a copy job marked as 'Already Copied' does not exist");
                    }
                }
                else
                {
                    bool resolved      = false;
                    var  absSourcePath = Path.Combine(expandedSourceFolder, f);
                    if (potentialSymlinks.IsMatch(f))
                    {
                        for (; ;)
                        {
                            var contents = File.ReadAllLines(absSourcePath);
                            if (contents.Length == 1 && File.Exists(Path.Combine(Path.GetDirectoryName(absSourcePath), contents[0])))
                            {
                                absSourcePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(absSourcePath), contents[0]));
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    if (!resolved)
                    {
                        File.Copy(absSourcePath, targetFile, true);
                    }
                }

                File.SetAttributes(targetFile, File.GetAttributes(targetFile) & ~FileAttributes.ReadOnly);
                string encodedPath = "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + "/" + renamedRelativePath.Replace('\\', '/');

                if (projectContents.IsMatch(f))
                {
                    projectFiles.Add(encodedPath.Replace('\\', '/'));
                }

                if (conditions != null)
                {
                    foreach (var cond in conditions)
                    {
                        if (cond.Regex.IsMatch(f))
                        {
                            bsp.MatchedFileConditions.Add(new FileCondition {
                                ConditionToInclude = cond.Condition, FilePath = encodedPath
                            });
                            cond.UseCount++;
                            break;
                        }
                    }
                }
            }

            if (AdditionalProjectFiles != null)
            {
                foreach (var spec in AdditionalProjectFiles.Split(';'))
                {
                    string encodedPath = "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + "/" + spec;
                    projectFiles.Add(encodedPath);
                }
            }

            var unusedConditions = conditions?.Where(c => c.UseCount == 0)?.ToArray();

            if ((unusedConditions?.Length ?? 0) != 0)
            {
                throw new Exception(string.Format("Found {0} unused conditions. Please recheck your rules.", unusedConditions.Length));
            }

            if (Patches != null)
            {
                foreach (var p in Patches)
                {
                    foreach (var fn in p.FilePath.Split(';'))
                    {
                        List <string> allLines = File.ReadAllLines(Path.Combine(absTarget, fn)).ToList();
                        p.Apply(allLines);

                        string targetPath = p.TargetPath;
                        if (targetPath == null)
                        {
                            targetPath = fn;
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(absTarget, targetPath)));
                        File.WriteAllLines(Path.Combine(absTarget, targetPath), allLines);
                    }
                }
            }

            if (GuardedFiles != null)
            {
                foreach (var gf in GuardedFiles)
                {
                    int    idx    = gf.IndexOf("=>");
                    Regex  rgFile = new Regex(gf.Substring(0, idx));
                    string macro  = gf.Substring(idx + 2);
                    var    fn     = Path.Combine(absTarget, filesToCopy.First(f => rgFile.IsMatch(f)));

                    List <string> lines = new List <string>(File.ReadAllLines(fn));
                    int           i     = 0;
                    //1. Find first #include
                    for (i = 0; i < lines.Count; i++)
                    {
                        if (lines[i].Trim().StartsWith("#include"))
                        {
                            break;
                        }
                    }

                    //2. Find first non-preprocessor line
                    for (; i < lines.Count; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(lines[i]) && !lines[i].Trim().StartsWith("#include"))
                        {
                            break;
                        }
                    }

                    if (i == lines.Count)
                    {
                        throw new Exception("Cannot find a place to insert guard in " + fn);
                    }

                    lines.Insert(i, string.Format("#if defined({0}) && {0}", macro));
                    lines.Add("#endif //" + macro);
                    File.WriteAllLines(fn, lines);
                }
            }

            if (AdditionalIncludeDirs != null)
            {
                includeDirs.AddRange(AdditionalIncludeDirs.Split(';').Select(d => MapIncludeDir(absTarget, d)));
            }

            return(new ToolFlags
            {
                PreprocessorMacros = (PreprocessorMacros == null) ? null : PreprocessorMacros.Split(';'),
                IncludeDirectories = includeDirs.ToArray()
            });
        }
        private PropertyEntry ParseSingleProperty(string name, string value, List <string> precedingComments)
        {
            var desc = precedingComments.Select(c => rgMacroDescription.Match(c)).FirstOrDefault(m => m.Success && m.Groups[1].Value != "i");

            string type = "o", text = name;

            if (desc != null && desc.Groups[2].Value == name)
            {
                type = desc.Groups[1].Value;
                text = desc.Groups[3].Value.Trim().TrimEnd('.') + $" ({name})";
            }

            PropertyEntry entry;

            switch (type)
            {
            case "q":
            case "e":
                entry = new PropertyEntry.Boolean {
                    ValueForTrue = "1", ValueForFalse = "0"
                };
                break;

            case "o":
            {
                var enumValues = precedingComments
                                 .Select(c => rgEnumValue.Match(c))
                                 .Where(m => m.Success)
                                 .Select(m => new PropertyEntry.Enumerated.Suggestion {
                        InternalValue = m.Groups[1].Value, UserFriendlyName = m.Groups[2].Value
                    })
                                 .ToArray();

                if (enumValues.Length > 0)
                {
                    entry = new PropertyEntry.Enumerated {
                        SuggestionList = enumValues
                    }
                }
                ;
                else
                {
                    entry = new PropertyEntry.String {
                    }
                };
                break;
            }

            case "s":
                entry = new PropertyEntry.String {
                };
                break;

            default:
                return(null);
            }


            entry.Name        = text;
            entry.UniqueID    = name;
            entry.Description = precedingComments.Select(c => rgMacroDescription.Match(c)).FirstOrDefault(m => m.Success && m.Groups[1].Value == "i")?.Groups[2].Value.Trim();

            return(entry);
        }
Exemple #4
0
        //parsing KConfig
        static PropertyList ParserKConfig(string pKFile)
        {
            string typ = "";
            string name = "", UID = "", min = "", max = "";
            bool   newProperty = false, flHelp = false, flEnum = false;
            var    def     = "";
            string lstHelp = "";
            List <PropertyEntry> ListProperties = new List <PropertyEntry>();
            PropertyEntry        PropEntry      = new PropertyEntry.Boolean();
            bool BoolNameChoice = false;

            PropertyEntry.Enumerated.Suggestion        SugEnum    = null;// new PropertyEntry.Enumerated.Suggestion();
            List <PropertyEntry.Enumerated.Suggestion> lstSugEnum = new List <PropertyEntry.Enumerated.Suggestion>();
            int    aCounrEnumDef = 0;
            int    resParse;
            string lnHist = "";

            foreach (var ln in File.ReadAllLines(pKFile))
            {
                if (ln.Contains("menu \"Example Configuration\""))
                {
                    resParse = 3;
                }
                Match m = Regex.Match(ln, "^(menuconfig|config|choice)[ ]+([A-Z0-9_]+)");
                if (m.Success)
                {
                    if (flEnum)
                    {
                        SugEnum = new PropertyEntry.Enumerated.Suggestion();
                        SugEnum.InternalValue = m.Groups[2].Value;
                        if (m.Groups[2].Value == def)
                        {
                            def = $"{aCounrEnumDef}";
                        }
                        aCounrEnumDef++;
                    }

                    if (m.Groups[1].Value == "choice")
                    {
                        BoolNameChoice = true; flEnum = true;
                    }
                    if (m.Groups[1].Value == "config")
                    {
                        BoolNameChoice = false;
                    }

                    if (name != "")//save
                    {
                        if (typ == "string")
                        {
                            PropEntry = new PropertyEntry.String
                            {
                                Name         = name,
                                UniqueID     = UID,
                                Description  = lstHelp,
                                DefaultValue = def
                            };
                        }
                        if (typ == "int")
                        {
                            PropEntry = new PropertyEntry.Integral
                            {
                                Name         = name,
                                UniqueID     = UID,
                                Description  = lstHelp,
                                DefaultValue = Int32.TryParse(def, out resParse) ? Int32.Parse(def) : 0,
                                MinValue     = Int32.TryParse(min, out resParse) ? Int32.Parse(min) : 0,
                                MaxValue     = Int32.TryParse(max, out resParse) ? Int32.Parse(max) : 0x0FFFFFFF
                            };
                            //    break;
                        }
                        if (typ == "bool")
                        {
                            PropEntry = new PropertyEntry.Boolean
                            {
                                Name         = name,
                                UniqueID     = UID,
                                Description  = lstHelp,
                                DefaultValue = def.ToLower().Contains("y") ? true : false
                            };
                            //      break;
                        }
                        ListProperties.Add(PropEntry);
                        if (!flEnum)
                        {
                            lstHelp = "";//.Clear();
                        }
                        flHelp = false;
                    }

                    UID         = m.Groups[2].Value;
                    newProperty = true;
                }
                if (!newProperty)
                {
                    continue;
                }

                if (flHelp && !ln.TrimStart().StartsWith("#") && ln.Length > 1)
                {
                    lstHelp += ln.Trim();
                }


                m = Regex.Match(ln, "^[ \t]+(int|bool|hex|prompt)[ ]+[\"]?([\\w0-9_ ]*)[\"]?");
                if (m.Success)
                {
                    if (flEnum)
                    {
                        if (m.Groups[1].Value == "bool" && !BoolNameChoice)
                        {
                            SugEnum.UserFriendlyName = m.Groups[2].Value;
                            lstSugEnum.Add(SugEnum);
                            continue;
                        }
                        //  if (m.Groups[1].Value == "prompt")
                        //     throw new Exception(" no endchoice "+ lnHist);
                    }
                    typ = m.Groups[1].Value; name = m.Groups[2].Value;
                    // if (typ == "prompt") flEnum = true;
                    continue;
                }

                m = Regex.Match(ln, "^[ \t]+default[ \t]([\\w\\d]+)");
                if (m.Success)
                {
                    def = m.Groups[1].Value; continue;
                }

                m = Regex.Match(ln, "^[ \t]+range[ \t]([\\w\\d]+)[ \t]+([\\w\\d]+)");
                if (m.Success)
                {
                    min = m.Groups[1].Value; max = m.Groups[2].Value; continue;
                }

                if (Regex.IsMatch(ln, "^[ \t]+help[ \t]*"))
                {
                    flHelp = true; continue;
                }

                if (Regex.IsMatch(ln, "^[ \t]*endchoice[ \t]*")) // end prompt
                {
                    if (typ != "prompt" && typ != "bool")
                    {
                        throw new Exception(" no prompt in endchoice");
                    }
                    flEnum    = false;
                    PropEntry = new PropertyEntry.Enumerated
                    {
                        Name = name,
                        // UniqueID = UID,
                        Description       = lstHelp,
                        DefaultEntryIndex = 1,// def.ToLower().StartsWith("y") ? true : false
                        SuggestionList    = lstSugEnum.ToArray()
                    };
                    //      break;

                    ListProperties.Add(PropEntry);
                    lstHelp       = "";//.Clear();
                    flHelp        = false;
                    aCounrEnumDef = 0;
                }

                lnHist = ln;
            }

            // end file
            //save old record , need it to new function or class
            if (typ == "int")
            {
                PropEntry = new PropertyEntry.Integral
                {
                    Name         = name,
                    UniqueID     = UID,
                    Description  = lstHelp,
                    DefaultValue = Int32.TryParse(def, out resParse) ? Int32.Parse(def) : 0,
                    MinValue     = Int32.TryParse(min, out resParse) ? Int32.Parse(min) : 0,
                    MaxValue     = Int32.TryParse(max, out resParse) ? Int32.Parse(max) : 0x0FFFFFFF
                };
                //    break;
            }
            if (typ == "bool")
            {
                PropEntry = new PropertyEntry.Boolean
                {
                    Name         = name,
                    UniqueID     = UID,
                    Description  = lstHelp,
                    DefaultValue = def.ToLower().Contains("y") ? true : false
                };
                //      break;
            }
            ListProperties.Add(PropEntry);
            //-----------------------
            List <PropertyGroup> lstPrGr = new List <PropertyGroup>();
            PropertyGroup        PrGr    = new PropertyGroup();

            PrGr.Properties = ListProperties;
            lstPrGr.Add(PrGr);

            PropertyList ConfigurableProperties = new PropertyList
            {
                PropertyGroups = lstPrGr
            };

            return(ConfigurableProperties);
        }
Exemple #5
0
        // perset Choice type
        static PropertyEntry ParserChoice(string[] pKFile, ref int countline)
        {
            string ln, NamePromptr = "", DefValueChoice = "", lsHelp = "", EnumUID = "";
            List <PropertyEntry> ListProperties = new List <PropertyEntry>();
            List <PropertyEntry.Enumerated.Suggestion> lstSugEnum = new List <PropertyEntry.Enumerated.Suggestion>();

            while (countline < pKFile.Count())
            {
                ln = pKFile[countline];
                if (ln.StartsWith("#"))
                {
                    countline++; continue;
                }

                Match m = Regex.Match(ln, "^(choice)[ ]+([A-Z0-9_]+)");
                if (m.Success)
                {
                    EnumUID = m.Groups[2].Value;
                }
                else if (EnumUID == "")
                {
                    return(null);
                }

                if (ln.StartsWith("endchoice"))
                {
                    break;
                }

                m = Regex.Match(ln, "^[ \t]+(prompt|bool)[ ]*[\"]?(['\\w0-9_ ]*)[\"]?");
                if (m.Success)
                {
                    if (m.Groups[2].Value != "")
                    {
                        NamePromptr = m.Groups[2].Value;
                    }
                    else
                    {
                        countNoNameProp++;
                        Console.WriteLine(ln);
                    }
                }

                m = Regex.Match(ln, "^[ \t]+default[ \t]([\\w\\d]+)");
                if (m.Success)
                {
                    DefValueChoice = m.Groups[1].Value;
                }


                if (Regex.IsMatch(ln, "^[ \t]+help[ \t]*"))
                {
                    while (countline < pKFile.Count())
                    {
                        countline++;
                        ln = pKFile[countline];
                        m  = Regex.Match(ln, "^(config|choice)[ ]+([A-Z0-9_]+)");
                        if (m.Success)
                        {
                            break;
                        }
                        if (!ln.StartsWith("#"))
                        {
                            lsHelp += ln;
                        }
                    }
                }

                var prop = ParserProperty(pKFile, ref countline);

                if (prop != null)
                {
                    //----------------------
                    if (prop.UniqueID == "TWO_UNIVERSAL_MAC_ADDRESS")
                    {
                        prop.UniqueID = "2//UNIVERSAL_MAC_ADDRESS";
                    }

                    if (prop.UniqueID == "FOUR_UNIVERSAL_MAC_ADDRESS")
                    {
                        prop.UniqueID = "4//UNIVERSAL_MAC_ADDRESS";
                    }


                    //----------------------
                    lstSugEnum.Add(new PropertyEntry.Enumerated.Suggestion()
                    {
                        UserFriendlyName = prop.Name,
                        InternalValue    = prop.UniqueID
                    });
                }
                countline++;
            }
            int defIndex = lstSugEnum.FindIndex(pr => pr.InternalValue.Remove(0, strPrefixConfProperty.Length) == DefValueChoice);

            if (!lstSugEnum[0].InternalValue.Contains("//UNIVERSAL_MAC_ADDRESS"))
            {
                lstShortMacr.Add($"#define    CONFIG_{ChangeInternelValue(ref lstSugEnum)}$${EnumUID}$$    1");
            }
            else
            {
                defIndex = 1;
            }

            PropertyEntry.Enumerated Enum = new PropertyEntry.Enumerated()
            {
                Name              = NamePromptr,
                Description       = lsHelp,
                UniqueID          = EnumUID,
                SuggestionList    = lstSugEnum.ToArray(),
                DefaultEntryIndex = defIndex
            };
            return(Enum);
        }