internal void GenerateSource(SourceStreamWriter sw, RegistryContext ctx) { if (sw == null) { throw new ArgumentNullException("sw"); } if (ctx == null) { throw new ArgumentNullException("ctx"); } bool bitmask = Enums.TrueForAll(delegate(Enumerant item) { Enumerant actualEnumerant = ctx.Registry.GetEnumerant(item.Name); return(actualEnumerant == null || actualEnumerant.ParentEnumerantBlock.Type == "bitmask"); }); // Collect group enumerants by their value Dictionary <string, List <Enumerant> > groupEnums = new Dictionary <string, List <Enumerant> >(); // ...include all enums defined in this group foreach (Enumerant item in Enums) { Enumerant itemValue = ctx.Registry.GetEnumerant(item.Name); if (itemValue != null) { if (!groupEnums.ContainsKey(itemValue.Value)) { groupEnums.Add(itemValue.Value, new List <Enumerant>()); } groupEnums[itemValue.Value].Add(itemValue); } } // Modify canonical enumeration (value/block/group) definition CommandFlagsDatabase.EnumerantItem enumerantExtension = CommandFlagsDatabase.FindEnumerant(Name); if (enumerantExtension != null) { // ...override group information if (enumerantExtension.Type != null) { switch (enumerantExtension.Type) { case "bitmask": bitmask = true; break; } } // ...include all enums to be added by additional configuration foreach (string addedEnum in enumerantExtension.AddEnumerants) { Enumerant addedEnumValue = ctx.Registry.GetEnumerant(addedEnum); if (addedEnumValue != null) { if (!groupEnums.ContainsKey(addedEnumValue.Value)) { groupEnums.Add(addedEnumValue.Value, new List <Enumerant>()); } // Note: since specification can be updated while the CommandFlags.xml is not in synch, the specification // may defined missed enumerant values. In this case do not add enumerant value if (groupEnums[addedEnumValue.Value].Contains(addedEnumValue) == false) { groupEnums[addedEnumValue.Value].Add(addedEnumValue); } } } } // Make enumerants distinct (discard duplicated enumerants, mainly from extensions _ARB, _EXT, ...) List <Enumerant> uniqueEnums = new List <Enumerant>(); foreach (KeyValuePair <string, List <Enumerant> > pair in groupEnums) { if (pair.Value.Count > 1) { List <Enumerant> uniqueNames = new List <Enumerant>(); foreach (Enumerant item in pair.Value) { if (item.Alias != null) { continue; } if (item.EnumAlias != null) { continue; } if (uniqueNames.FindIndex(delegate(Enumerant item1) { return(item.Name.StartsWith(item1.Name)); }) >= 0) { continue; } if (uniqueNames.FindIndex(delegate(Enumerant item1) { return(item1.Name.StartsWith(item.Name)); }) >= 0) { uniqueNames.RemoveAll(delegate(Enumerant item1) { return(item1.Name.StartsWith(item.Name)); }); } uniqueNames.Add(item); } uniqueEnums.AddRange(uniqueNames); } else { uniqueEnums.AddRange(pair.Value); } } sw.WriteLine("/// <summary>"); sw.WriteLine("/// Strongly typed enumeration {0}.", Name); sw.WriteLine("/// </summary>"); if (bitmask) { sw.WriteLine("[Flags()]"); } sw.WriteLine("public enum {0}{1}", Name, bitmask ? " : uint" : String.Empty); sw.WriteLine("{"); sw.Indent(); foreach (Enumerant enumerant in uniqueEnums) { List <Enumerant> allEnums = groupEnums[enumerant.Value]; string bindingName = enumerant.EnumAlias == null ? enumerant.ImplementationName : enumerant.EnumAlias.ImplementationName; string camelCase = SpecificationStyle.GetCamelCase(bindingName); if (enumerantExtension != null && enumerantExtension.ItemPrefix != null && camelCase.StartsWith(enumerantExtension.ItemPrefix)) { camelCase = camelCase.Substring(enumerantExtension.ItemPrefix.Length); } sw.WriteLine("/// <summary>"); if (allEnums.Count > 1) { StringBuilder sb = new StringBuilder(); sb.Append("Strongly typed for value "); for (int i = 0; i < allEnums.Count; i++) { sb.Append(allEnums[i].Name); if (i < allEnums.Count - 1) { sb.Append(", "); } } sb.Append("."); foreach (string docLine in RegistryDocumentation.SplitDocumentationLines(sb.ToString())) { sw.WriteLine("/// {0}", docLine); } } else { sw.WriteLine("/// Strongly typed for value {0}.", enumerant.Name); } sw.WriteLine("/// </summary>"); Enumerant enumvalue = ctx.Registry.GetEnumerant(ctx.Class.ToUpperInvariant() + "_" + bindingName); string classDefaultApi = ctx.Class.ToLower(); if (enumvalue != null) { // RequiredByFeature foreach (IFeature feature in enumvalue.RequiredBy) { sw.WriteLine(feature.GenerateRequiredByAttribute(null, classDefaultApi)); } // RequiredByFeature (from aliases) Note: not sure that Profile is considered here foreach (Enumerant aliasOf in enumvalue.AliasOf) { foreach (IFeature feature in aliasOf.RequiredBy) { sw.WriteLine(feature.GenerateRequiredByAttribute(null, classDefaultApi)); } } // RemovedByFeature foreach (IFeature feature in enumvalue.RemovedBy) { sw.WriteLine(feature.GenerateRemovedByAttribute(classDefaultApi)); } } sw.WriteLine("{0} = {1}.{2},", camelCase, ctx.Class, bindingName); sw.WriteLine(); } sw.Unindent(); sw.WriteLine("}"); }
internal void GenerateSource(SourceStreamWriter sw, RegistryContext ctx) { if (sw == null) { throw new ArgumentNullException("sw"); } if (ctx == null) { throw new ArgumentNullException("ctx"); } bool bitmask = Enums.TrueForAll(delegate(Enumerant item) { Enumerant actualEnumerant = ctx.Registry.GetEnumerant(item.Name); return(actualEnumerant == null || actualEnumerant.ParentEnumerantBlock.Type == "bitmask"); }); // Collect group enumerants by their value Dictionary <string, List <Enumerant> > groupEnums = new Dictionary <string, List <Enumerant> >(); // ...include all enums defined in this group foreach (Enumerant item in Enums) { Enumerant itemValue = ctx.Registry.GetEnumerant(item.Name); if (itemValue != null) { if (!groupEnums.ContainsKey(itemValue.Value)) { groupEnums.Add(itemValue.Value, new List <Enumerant>()); } groupEnums[itemValue.Value].Add(itemValue); } } // Modify canonical enumeration (value/block/group) definition CommandFlagsDatabase.EnumerantItem enumerantExtension = CommandFlagsDatabase.FindEnumerant(Name); if (enumerantExtension != null) { // ...override group information if (enumerantExtension.Type != null) { switch (enumerantExtension.Type) { case "bitmask": bitmask = true; break; } } // ...include all enums to be added by additional configuration foreach (string addedEnum in enumerantExtension.AddEnumerants) { Enumerant addedEnumValue = ctx.Registry.GetEnumerant(addedEnum); if (addedEnumValue != null) { if (!groupEnums.ContainsKey(addedEnumValue.Value)) { groupEnums.Add(addedEnumValue.Value, new List <Enumerant>()); } // Note: since specification can be updated while the CommandFlags.xml is not in synch, the specification // may defined missed enumerant values. In this case do not add enumerant value if (groupEnums[addedEnumValue.Value].Contains(addedEnumValue) == false) { groupEnums[addedEnumValue.Value].Add(addedEnumValue); } } } } // Make enumerants distinct (discard duplicated enumerants, mainly from extensions _ARB, _EXT, ...) List <Enumerant> uniqueEnums = new List <Enumerant>(); foreach (KeyValuePair <string, List <Enumerant> > pair in groupEnums) { if (pair.Value.Count > 1) { Enumerant shorterNameEnum = null; foreach (Enumerant item in pair.Value) { if ((shorterNameEnum == null) || (shorterNameEnum.Name.Length > item.Name.Length)) { shorterNameEnum = item; } } uniqueEnums.Add(shorterNameEnum); } else { uniqueEnums.Add(pair.Value[0]); } } sw.WriteLine("/// <summary>"); sw.WriteLine("/// Strongly typed enumeration {0}.", Name); sw.WriteLine("/// </summary>"); if (bitmask) { sw.WriteLine("[Flags()]"); } sw.WriteLine("public enum {0}{1}", Name, bitmask ? " : uint" : String.Empty); sw.WriteLine("{"); sw.Indent(); foreach (Enumerant enumerant in uniqueEnums) { List <Enumerant> allEnums = groupEnums[enumerant.Value]; string bindingName = enumerant.EnumAlias == null ? enumerant.ImplementationName : enumerant.EnumAlias.ImplementationName; string camelCase = SpecificationStyle.GetCamelCase(bindingName); sw.WriteLine("/// <summary>"); if (allEnums.Count > 1) { StringBuilder sb = new StringBuilder(); sb.Append("Strongly typed for value "); for (int i = 0; i < allEnums.Count; i++) { sb.Append(allEnums[i].Name); if (i < allEnums.Count - 1) { sb.Append(", "); } } sb.Append("."); foreach (string docLine in RegistryDocumentation.SplitDocumentationLines(sb.ToString())) { sw.WriteLine("/// {0}", docLine); } } else { sw.WriteLine("/// Strongly typed for value {0}.", enumerant.Name); } sw.WriteLine("/// </summary>"); sw.WriteLine("{0} = Gl.{1},", camelCase, bindingName); sw.WriteLine(); } sw.Unindent(); sw.WriteLine("}"); }
/// <summary> /// Append definitions recognized in a header file. /// </summary> /// <param name="path"> /// A <see cref="System.String"/> that specified the path of the header file. /// </param> public void AppendHeader(string path, string headerFeatureName) { if (path == null) { throw new ArgumentNullException(nameof(path)); } string headerText; // Read the whole header using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { headerText = sr.ReadToEnd(); } } // Remove comments string inlineComment = @"//(.*?)\r?\n"; string blockComment = @"/\*(.*?)\*/"; headerText = Regex.Replace(headerText, String.Format("{0}|{1}", inlineComment, blockComment), delegate(Match match) { if (match.Value.StartsWith("/*")) { return(String.Empty); } if (match.Value.StartsWith("//")) { return(Environment.NewLine); } return(match.Value); }, RegexOptions.Singleline); // Extract C preprocessor #define directives string defineDirective = @"#define (?<Symbol>[\w\d_]+) +(?<Value>.*)\r?\n"; EnumerantBlock definesBlock = new EnumerantBlock(); definesBlock.Group = "Defines"; headerText = Regex.Replace(headerText, defineDirective, delegate(Match match) { // Collect symbol/value if (match.Value.StartsWith("#define ")) { Enumerant enumerant = new Enumerant(); // Replace enumeration macros string enumDefinition = ReplaceEnumMacros(match.Groups["Value"].Value.Trim()); // Replace constants in enumeration value enumDefinition = ReplaceEnumConstants(enumDefinition); enumerant.Name = match.Groups["Symbol"].Value.Trim(); enumerant.Value = enumDefinition; enumerant.ParentEnumerantBlock = definesBlock; bool useDefine = true; if (enumerant.Value.StartsWith("__")) { useDefine = false; } if (enumerant.Value.StartsWith("{") && enumerant.Value.EndsWith("}")) { useDefine = false; } if (useDefine) { definesBlock.Enums.Add(enumerant); // Collect enumerant _Enumerants.Add(enumerant); } return(String.Empty); } return(match.Value); }, RegexOptions.Multiline); // Remove no more necessary C preprocessor string preprocessorDirective = @"#(if|ifndef|else|endif|define|include) ?.*\r?\n"; headerText = Regex.Replace(headerText, preprocessorDirective, String.Empty); // Remove new lines headerText = Regex.Replace(headerText, @"\r?\n", String.Empty); // Remove structures typedefs string structTypedef = @"typedef struct ?\{(.*?)\}( +?)(.*?);"; headerText = Regex.Replace(headerText, structTypedef, String.Empty); // Remove multiple spaces headerText = Regex.Replace(headerText, @" +", " "); // Extract extern "C" scope string externBlock = "extern \"C\" {"; if (headerText.StartsWith(externBlock)) { headerText = headerText.Substring(externBlock.Length, headerText.Length - externBlock.Length - 1); } // Split into statements string[] statements = Regex.Split(headerText, ";"); foreach (string statement in statements) { Match match; // Parse enumeration block if ((match = Regex.Match(statement, @"(typedef )?enum(?<Name> [\w\d_]+)? ?\{(?<Enums>.*)\}(?<Tag> +?[\w\d_]+)?")).Success) { string name; if (match.Groups["Tag"].Success) { name = match.Groups["Tag"].Value.Trim(); } else if (match.Groups["Name"].Success) { name = match.Groups["Name"].Value.Trim(); } else { throw new InvalidOperationException("unable to determine name of enum"); } if (Regex.IsMatch(name, "WF(C|D)boolean")) { continue; } #region Enumeration // Skip enumeration if required CommandFlagsDatabase.EnumerantItem enumItem = CommandFlagsDatabase.FindEnumerant(name); if (enumItem != null && enumItem.Disable) { continue; } EnumerantBlock enumerantBlock = new EnumerantBlock(); enumerantBlock.Group = headerFeatureName; EnumerantGroup enumerantGroup = new EnumerantGroup(); enumerantGroup.Name = name; // Override name if (enumItem != null && enumItem.Alias != null) { enumerantGroup.Name = enumItem.Alias; } // Replace enumeration macros string enumDefinition = ReplaceEnumMacros(match.Groups["Enums"].Value); // Replace constants in enumeration value enumDefinition = ReplaceEnumConstants(enumDefinition); // Parse enumerations string[] enumValues = Regex.Split(enumDefinition, ","); for (int i = 0; i < enumValues.Length; i++) { string enumValue = enumValues[i].Trim(); if ((match = Regex.Match(enumValue, @"(?<Name>(\w|_)+)\s*=\s*(?<Value>.*)")).Success) { Enumerant enumerant = new Enumerant(); enumerant.Name = match.Groups["Name"].Value; enumerant.Value = match.Groups["Value"].Value.Trim(); enumerant.ParentEnumerantBlock = enumerantBlock; enumerantBlock.Enums.Add(enumerant); enumerantGroup.Enums.Add(enumerant); // Collect enumerant _Enumerants.Add(enumerant); } } _Groups.Add(enumerantGroup); #endregion continue; } else if ((match = Regex.Match(statement, CommandExportRegex + @"(?<Return>.*) " + CommandCallConventionRegex + @"(?<Name>.*)\((?<Args>.*)\)" + CommandExitRegex)).Success) { #region Command Command command = new Command(); command.Prototype = new CommandPrototype(); command.Prototype.Type = match.Groups["Return"].Value; command.Prototype.Name = match.Groups["Name"].Value; string[] args = Regex.Split(match.Groups["Args"].Value, ","); for (int i = 0; i < args.Length; i++) { string arg = args[i].Trim(); if (arg == String.Empty) { break; } // '*' denotes types, not names arg = arg.Replace(" **", "** "); arg = arg.Replace(" *", "* "); if ((match = Regex.Match(arg, @"(const +)?(?<Type>(\w|_|\* (const)?|\*)+) +(?<Name>[\w\d_]+)(?<ArraySize>\[([\w\d_]+)?\])?$")).Success) { string arraySize = match.Groups["ArraySize"].Success ? match.Groups["ArraySize"].Value : null; CommandParameter commandParameter = new CommandParameter(); commandParameter.Name = match.Groups["Name"].Value; commandParameter.Type = arraySize != null ? match.Groups["Type"].Value + "*" : match.Groups["Type"].Value; command.Parameters.Add(commandParameter); } else if (arg == "...") { CommandParameter commandParameter = new CommandParameter(); commandParameter.Name = "vaArgs"; commandParameter.Type = "IntPtr"; command.Parameters.Add(commandParameter); } else { throw new InvalidOperationException(String.Format("unable to parse argument '{0}'", arg)); } } _Commands.Add(command); #endregion } } Feature headerFeature = _Features.Find(delegate(Feature item) { return(item.Name == headerFeatureName); }); if (headerFeature == null) { headerFeature = new Feature(); headerFeature.Name = headerFeatureName; headerFeature.Api = Class.ToLowerInvariant(); _Features.Add(headerFeature); } FeatureCommand headerFeatureCommand = new FeatureCommand(); headerFeature.Requirements.Add(headerFeatureCommand); headerFeatureCommand.Enums.AddRange(_Enumerants.ConvertAll(delegate(Enumerant input) { return(new FeatureCommand.Item(input.Name)); })); headerFeatureCommand.Commands.AddRange(_Commands.ConvertAll(delegate(Command input) { return(new FeatureCommand.Item(input.Prototype.Name)); })); }